我正在开发一个游戏,我想抽象我的ui,并根据各种游戏状态绑定非绑定事件.但我无法弄清楚为什么这个事件没有被删除.似乎处理程序中的范围是正确的.
相关(剥离)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();
Run Code Online (Sandbox Code Playgroud)
然而,如果我以这种方式删除事件它的工作原理:
(...)
bind : function(el, cb) { …Run Code Online (Sandbox Code Playgroud)