Javascript / Prototype范围混乱

时间:2009-06-09 14:44:32

标签: javascript scope prototypejs

我正在创建一个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();
    })
}

});

1 个答案:

答案 0 :(得分:2)

假设你的意思是它在SendIdleSignal中有效,并且在SendActiveSignal中无效......

您的事件侦听器也应该使用bind,如下所示:

Event.observe(document, "mousemove", this.sendActiveSignal.bind(this));
Event.observe(document, "keypress", this.sendActiveSignal.bind(this));

此外,如果您使用的是原型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);