Today I Learned - Rocky Kev

TIL using abortController to removing events

POSTED ON:

TAGS:

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();
  1. You create a controller.
  2. The third parameter in addeventListener is options. Options also contains a abortSignal.
  3. 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:

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL How to steal localData using an XSS attack

But that's just a red flag that opens the door to bigger issues.

TIL Clear-Site-Data

The Clear-Site-Data header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored by a client browser for their origins.