Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use removeEventListener when event handler is a prototype function?

This is a follow-up to this question. The problem is that my call to removeEventListener does not work. What do I have to change below so that it does work?

My custom object:

//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
};

This is how I'm trying to remove the event handler:

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
};

And this is the signature of the prototype function that handles the event.

CE.prototype.onCustomKeyDown = function onCustomKeyDown(e) {

If I understand correctly, removeEventListener cannot be used to remove event handlers which are anonymous functions. Is that the issue here? Do I need to change the way I'm calling addEventListener?

like image 538
Karl Avatar asked Mar 18 '23 03:03

Karl


1 Answers

If I understand correctly, removeEventListener cannot be used to remove event handlers which are anonymous functions. Is that the issue here?

Yes. The function that is added is the anonymous function expression, not callback, so calling removeEventListener with callback will not work.

Do I need to change the way I'm calling addEventListener?

Yes, you somehow need to retain a reference to the actual handler function so that you can pass it to removeEventListener later. There are basically two ways to do this:

  • use a closure and return a remover function from addEvent that will cancel the subscription.
  • store a reference to the event handler somewhere so that you can identify it by the callback when removeEvent method is called - and make sure that it doesn't leak.
like image 108
Bergi Avatar answered Mar 19 '23 15:03

Bergi