Event Listener Removal
A quick look at an important event listener gotcha.
To properly remove an event listener, the callback of your event listener must be the same function reference.
Function Objects
The reason for this is that Functions are Objects.
We can see that this is the case by checking the instance of a function.
Memory Reference
When objects are created, they're stored in memory as unique pieces of information. We can prove this by checking equality or strict equality of two seemingly identical objects.
This check evaluates to false
because the JavaScript engine is basically seeing
Of course that wouldn't be equal.
Event Removal
If we added an event with an anonymous function as the callback, it wouldn't get removed for the reasons above. Even though the function looks identical to us, in memory they are two completely separate, unique references.
To make this work, you need both callbacks to be the same function reference.