这是此 question 的后续行动.问题是我对 removeEventListener
的调用不起作用。我必须在下面进行哪些更改才能使其正常工作?
我的自定义对象:
//Custom Editor Example with event listeners
var CE = function (id) {
'use strict';
// assume not a valid object
this.isValid = false;
this.element = document.getElementById(id);
if (this.element !== null) {
this.id = id;
this.init();
this.isValid = true;
}
};
CE.prototype.addEvent = function (event, callback, caller) {
'use strict';
// check for modern browsers first
if (typeof window.addEventListener === 'function') {
return caller.element.addEventListener(event, function (e) {callback.call(caller, e); }, false);
}
// then for older versions of IE
return this.element.attachEvent('on' + event, function (e) {callback.call(caller, window.event); });
};
CE.prototype.init = function () {
'use strict';
this.addEvent('keydown', this.onCustomKeyDown, this);
// add other event listeners
};
这就是我尝试删除事件处理程序的方式:
CE.prototype.removeEvent = function (event, callback, caller) {
'use strict';
caller.element.removeEventListener(event, callback, false);
};
CE.prototype.destroy = function () {
'use strict';
this.removeEvent('keydown', this.onCustomKeyDown, this);
// remove other event listeners
};
这是处理事件的原型(prototype)函数的签名。
CE.prototype.onCustomKeyDown = function onCustomKeyDown(e) {
如果我理解正确,removeEventListener 不能用于删除作为匿名函数的事件处理程序。是这里的问题吗?我是否需要更改调用 addEventListener
的方式?
最佳答案
If I understand correctly, removeEventListener cannot be used to remove event handlers which are anonymous functions. Is that the issue here?
是的。添加的函数是匿名函数表达式,不是callback
,所以用callback
调用removeEventListener
将不起作用。
Do I need to change the way I'm calling addEventListener?
是的,您需要以某种方式保留对实际处理程序函数的引用,以便稍后可以将其传递给 removeEventListener
。基本上有两种方法可以做到这一点:
- 使用闭包并从
addEvent
返回一个remover
函数,这将取消订阅。 - 在某处存储对事件处理程序的引用,以便您可以在调用
removeEvent
方法时通过回调识别它 - 并确保它不会泄漏。
关于javascript - 当事件处理程序是原型(prototype)函数时如何使用 removeEventListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28386665/