为什么removeeventlistener在此对象上下文中不起作用? [英] Why does removeeventlistener not work in this object context?

查看:139
本文介绍了为什么removeeventlistener在此对象上下文中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作游戏,我想抽象我的ui,并根据各种游戏状态绑定非绑定事件。但我无法弄清楚为什么这个事件没有被删除。似乎处理程序中的范围是正确的。

I am working on a game and I would like to abstract my ui, and bind unbind events based on various game states. But I can't figure out why this event is not being removed. It seems the scope is correct in the handler.

小提琴

相关(剥离)js:

var controls = {
    game : {
        el : null,
        cb : null,

        bind : function(el, cb) {
            this.el = el;
            this.cb = cb;
            this.el.addEventListener('click', this.handler.bind(this), true);
        },

        unbind : function() {
            console.log('unbind');
            this.el.removeEventListener('click', this.handler, true);
        },

        handler : function() {
            this.cb();
            this.unbind();
        }
    }
};

var manager = {
    init : function() {
        var c = document.getElementById('c');
        controls.game.bind(c, this.action.bind(this));
    },

    action : function() {
        console.log('c clicked');
    }
};
manager.init();

然而,如果我以这种方式移除事件它会起作用:

And yet if I remove the event this way it works:

(...)

bind : function(el, cb) {
    this.el = el;
    this.cb = cb;
    var self = this;
    this.el.addEventListener('click', function() {
        self.cb();
        self.el.removeEventListener('click', arguments.callee, true);
    }, true);
}

(...)

谢谢

推荐答案

.bind 返回函数。 this.handler.bind(this)!== this.handler !你必须以某种方式存储对新函数的引用。

.bind returns a new function. this.handler.bind(this) !== this.handler! You would have to store a reference to the new function somehow.

例如,在变量中存储引用并使用闭包:

For example, storing a reference in a variable and using a closure:

var handler = this.handler.bind(this);
this.el.addEventListener('click', handler, true);

this.unbind = function() {
    this.el.removeEventListener('click', handler, true);
}

替代 arguments.callee ,你也可以给这个函数命名:

As alternative to arguments.callee, you could also give the function a name:

this.el.addEventListener('click', function handler() {
    self.cb();
    self.el.removeEventListener('click', handler, true);
}, true);

这篇关于为什么removeeventlistener在此对象上下文中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆