简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM