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.
In your example clickHandler is an identifier. Identifiers can't be converted to strings, so there is no way for JavaScript to remember if the same identifier name has been used as an argument before. They are merely names meant to be read by developers.
So yes, you will need to pass the reference to the function. Even if you pass that reference via another identifier.
function clickHandler() {
console.log('Clicked!');
}
const buttonElement = document.querySelector('button');
buttonElement.addEventListener('click', clickHandler);
setTimeout(() => {
const differentHandlerName = clickHandler;
buttonElement.removeEventListener('click', differentHandlerName);
console.log('Removed event listener via a different identifier name');
}, 2000);
<button>
Click
</button>
You must pass a reference to the same function used for addEventListener when calling removeEventListener