我正在创建一个 JavaScript 类(使用 Prototype),如果在指定的秒数内没有鼠标移动,该类会将页面状态设置为空闲。当鼠标移动时,该类将通过向监听器列表发送消息来“唤醒”页面。
我不明白的是 this.handlers
在一个函数 (setIdle
) 中有效,但在另一个函数 (setActive
) 中无效)。下面带注释的代码说明了我的问题:
var IM2 = Class.create({
handlers: null,
initialize: function(callback, frequency) {
this.handlers = [];
Event.observe(document, "mousemove", this.sendActiveSignal);
Event.observe(document, "keypress", this.sendActiveSignal);
setInterval(this.sendIdleSignal.bind(this), 5000);
},
addListener: function(h) {
console.log(this.handlers.size()); // it's 0 here, as expected
this.handlers.push(h);
console.log(this.handlers.size()); // it's 1 here, as expected
},
sendIdleSignal: function(args) {
console.log("IDLE");
this.handlers.each(function(i){
i.setIdle();
})
},
sendActiveSignal: function() {
// this.handlers is undefined here. Why?
this.handlers.each(function(r) {
r.setActive();
})
}
});
最佳答案
假设您的意思是它在 SendIdleSignal 中有效,而在 SendActiveSignal 中无效...
您的事件监听器还应该使用绑定(bind),如下所示:
Event.observe(document, "mousemove", this.sendActiveSignal.bind(this));
Event.observe(document, "keypress", this.sendActiveSignal.bind(this));
此外,如果您使用的是原型(prototype) 1.6 或更高版本,则可以使用
document.observe("mousemove", this.sendActiveSignal.bind(this));
document.observe("keypress", this.sendActiveSignal.bind(this));
此外,如果您想要一种通用(与框架无关)的方法来执行此操作,您可以像这样定义函数:
sendActiveSignal: function() {
var that = this;
return function() {
that.handlers.each(function(r) {
r.setActive();
});
}
}
那么你的事件处理程序/setInterval 可以保留为
Event.observe(document, "keypress", this.sendActiveSignal);
关于Javascript/原型(prototype)范围混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/970479/