当事件处理程序是原型函数时,如何使用removeEventListener?

Kar*_*arl 3 javascript event-handling

这是这个问题的后续行动.问题是我的电话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
};
Run Code Online (Sandbox Code Playgroud)

这是我试图删除事件处理程序的方式:

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
};
Run Code Online (Sandbox Code Playgroud)

这是处理事件的原型函数的签名.

CE.prototype.onCustomKeyDown = function onCustomKeyDown(e) {
Run Code Online (Sandbox Code Playgroud)

如果我理解正确,removeEventListener不能用于删除作为匿名函数的事件处理程序.这是问题吗?我需要改变我打电话的方式addEventListener吗?

Ber*_*rgi 5

如果我理解正确,removeEventListener不能用于删除作为匿名函数的事件处理程序.这是问题吗?

是.所添加的功能是匿名函数表达式,没有callback,因此调用removeEventListenercallback将无法正常工作.

我是否需要更改我调用addEventListener的方式?

是的,您需要保留对实际处理程序函数的引用,以便您可以将其传递给removeEventListener以后.基本上有两种方法可以做到这一点:

  • 使用一个闭包并remover从中返回一个函数addEvent将取消订阅.
  • 在某处存储对事件处理程序的引用,以便在调用removeEvent方法时通过回调识别它- 并确保它不会泄漏.