在JavaScript中,使用bind()删除作为事件侦听器添加的函数的最佳方法是什么?
例
(function(){
// constructor
MyClass = function() {
this.myButton = document.getElementById("myButtonID");
this.myButton.addEventListener("click", this.clickListener.bind(this));
};
MyClass.prototype.clickListener = function(event) {
console.log(this); // must be MyClass
};
// public method
MyClass.prototype.disableButton = function() {
this.myButton.removeEventListener("click", ___________);
};
})();
Run Code Online (Sandbox Code Playgroud)
我能想到的唯一方法就是跟踪每个添加了bind的侦听器.
以上示例使用此方法:
(function(){
// constructor
MyClass = function() {
this.myButton = document.getElementById("myButtonID");
this.clickListenerBind = this.clickListener.bind(this);
this.myButton.addEventListener("click", this.clickListenerBind);
};
MyClass.prototype.clickListener = function(event) {
console.log(this); // must be MyClass
};
// public method
MyClass.prototype.disableButton = function() {
this.myButton.removeEventListener("click", this.clickListenerBind);
};
})();
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点?
我正在开发一个游戏,我想抽象我的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)