This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the javascript category.
Last Updated: 2024-11-21
In JavaScript, removeEventListener
fails for anonymous functions.
e.g. This event listener will not be removed:
element.addEventListener("keyup", () => { doSomething});
element.removeEventListener(() => { doSomething})
Instead you have to pass named functions. Here's an example of the happy case:
element.addEventListener("keyup", handleKeyUp);
element.removeEventListener("keyup", handleKeyUp);
It removes the function handleKeyUp
bound to the keyup
event on element
(FYI: There are three bits of info here to localize the effect)
So why the failure for anonymous functions? That's because it creates two separate functions that, from JS's point of view, which have nothing to do with one another (even though, from a human point of view, they do the same thing).
// The anonymous function here...
element.addEventListener("keyup", function() { doSomething} );
// is completely different in JavaScript's eyes to the one here:
element.removeEventListener("keyup", function () { doSomething } );
One solution would be to store the reference to the anonymous function in a shared variable:
_listener = function() { doSomething };
element.addEventListener("keyup", _listener);
// This works
element.removeEventListener("keyup", _listener);