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.
fiddle
relevant (stripped down) 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);
}
(...)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…