代码之家  ›  专栏  ›  技术社区  ›  yalestar

Javascript/原型范围混淆

  •  0
  • yalestar  · 技术社区  · 15 年前

    我正在创建一个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 回复  |  直到 13 年前
        1
  •  2
  •   Jonathan Fingland    15 年前

    假设您的意思是它在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);