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()