TIL using abortController to removing events
POSTED ON:
TAGS: mdn javascript
tl;dr - Trying to unhook a eventListener? Don't use removeEventListener
, instead use AbortController.
Removing Event Handlers #
One particularly annoying part of learning JS and the DOM is the realization that event handlers and function references don't work this way:
window.addEventListener('resize', () => doSomething());
// later (DON'T DO THIS)
window.removeEventListener('resize', () => doSomething());
The two callbacks are different objects, so the DOM, in its infinite wisdom—just fails to remove the callback silently, without an error.
Using the AbortController pattern:
const controller = new AbortController();
const { signal } = controller; // or you can just use controller.signal
window.addEventListener('resize', () => doSomething(), { signal });
// later
controller.abort();
- You create a controller.
- The third parameter in
addeventListener
is options. Options also contains a abortSignal. - Later on, you actually DO abort it, which then disables the eventListener.
The listener will be removed when the given AbortSignal object's abort() method is called. If not specified, no AbortSignal is associated with the listener.
the MDN: https://developer.mozilla.org/en-US/docs/Web/API/AbortController
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
via AbortController is your friend
Related TILs
Tagged: mdn