Skip to content
Advertisement

.removeEventListener(); by name or reference?

Say you have simple:

document.removeEventListener('click', clickHandler);

Does removeEventListener remove a registered listener for click events named clickHandler or does it remove a registered listener for click events referencing the very same function that clickHandler references?

Here they say:

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

When they say “the event listener function itself“, do they mean the very same reference?

I’m asking because I have (in a React project) a memoized function that removes a bunch of event listeners and I would like to know how often I need to get a new function.

If removeEventListener removes handlers by names, I can leave the dependecy array of useCallback empty.
But if removeEventListener removes by references, I need to put all the listeners in the dependency array. And maybe I would be better off without memoization.

Advertisement

Answer

You must pass a reference to the same function used for addEventListener when calling removeEventListener

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement