我正在制作一款游戏,我想抽象出我的UI,并根据各种游戏状态绑定解绑事件。但我不明白为什么这个事件没有被删除。看起来范围在处理程序中是正确的。为什么removeeventlistener在此对象上下文中不起作用?
相关(精简)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();
可是如果我删除事件这样它的工作原理:
(...)
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创建一个新的功能。 :) – 2013-04-04 19:01:11
非常有帮助谢谢! – 2015-05-11 17:41:30
为什么不呢? - > this.el.addEventListener('click',this.handler.bind(this),true);和this.el.removeEventListener('click',this.handler.bind(this),true); – 2016-02-25 09:40:59