brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: pass an AbortController signal to addEventListener to remove listeners in one call

Web-Development
~/tips/tip-javascript-addeventlistener-signal

const controller = new AbortController();

Removes several event listeners at once by aborting a shared AbortController signal.

Removing an event listener with removeEventListener() only works if you kept a reference to the exact same function. I find that annoying with inline arrow functions, and the signal option gets rid of the problem.

You give addEventListener() a signal from an AbortController. When you call abort() on the controller, every listener that got that signal is removed:

const controller = new AbortController();
const { signal } = controller;

window.addEventListener("resize", () => console.log("resized"), { signal });
window.addEventListener("keydown", (e) => console.log(e.key), { signal });

// later, for example when a panel closes:
controller.abort();

Both listeners use anonymous functions, so removeEventListener() could not have found them. One abort() cleans up the whole group, which is handy for a component that adds several listeners when it opens and must drop them all when it closes.

You can combine it with the other options in the same object:

container.addEventListener("wheel", onWheel, {
  passive: true,
  once: true,
  signal,
});

A caveat: a controller works only once. After abort() its signal stays aborted, and adding a listener with an already aborted signal does nothing. Create a fresh new AbortController() every time the component opens.

The same signal also works with fetch(), so one abort() can cancel a request and its listeners together.

Further reading: MDN: EventTarget.addEventListener()

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link