User81646
User81646

Reputation: 743

Problem with document.removeEventListener()

I have a function that creates an event listener:

document.addEventListener(name, handler.bind(null, name, callback), false);

I use .bind to pass the extra parameters, but when I try to remove it:

document.removeEventListener(name, handler, false);
// or
document.removeEventListener(name, handler.bind(null), false);

It doesn't actual get removed. I have tried various fixes and cannot seem to get it to work.

Upvotes: 2

Views: 100

Answers (2)

Rayon
Rayon

Reputation: 36609

The EventTarget.removeEventListener() method removes from the EventTarget an event listener previously registered with EventTarget.addEventListener(). The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process.

As you are using Function#bind, The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Hence while using removeEventListener, you are not passing same reference of the function which was added for addEventListener.

Have cached Handler function in a variable which could be used for the both, addEventListener as well as removeEventListener

let handlerFunction = handler.bind(null, name, callback);
document.addEventListener(name, handlerFunction, false);
document.removeEventListener(name, handlerFunction, false);

Upvotes: 0

Snow
Snow

Reputation: 4097

You need to save a reference to the bound function, so that removeEventListener can be called with it later:

const boundHandler = handler.bind(null, name, callback);
document.addEventListener(name, boundHandler, false);

// later:

document.removeEventListener(name, boundHandler, false);

Upvotes: 5

Related Questions