Sub topic 15
Using a Signal to Remove Event Listeners
This chapter assumes you know addEventListener and have built cancellable functions with an AbortController, as in the earlier chapters. You will use the same signal to remove event listeners, so a function that subscribes to events can be cancelled like any other cancellable function.
The signal option of addEventListener
addEventListener accepts a signal in its options object. When that signal aborts, the browser removes the listener for you. You don't need to keep a reference to the handler or call removeEventListener.
function trackClicks(button, { signal } = {}) {
let count = 0;
button.addEventListener('click', () => {
count += 1;
console.log(`clicks: ${count}`);
}, { signal });
}
const controller = new AbortController();
trackClicks(document.querySelector('button'), { signal: controller.signal });
// Later: removes the click listener without keeping a reference to it
controller.abort();trackClicks follows the convention from earlier chapters. It takes an optional signal and forwards it. The handler is an inline arrow function, so removeEventListener could never reach it. The signal removes it anyway.
One signal, many listeners
A single signal can remove any number of listeners, on any number of targets. This suits setup functions that register several handlers together. The example below uses EventTarget directly, so it runs in Node.js as well as in a browser.
function subscribe(target, { signal } = {}) {
target.addEventListener('start', () => console.log('start'), { signal });
target.addEventListener('progress', (e) => console.log('progress', e.detail), { signal });
target.addEventListener('end', () => console.log('end'), { signal });
}
const bus = new EventTarget();
const controller = new AbortController();
subscribe(bus, { signal: controller.signal });
bus.dispatchEvent(new CustomEvent('progress', { detail: 50 })); // logs: progress 50
controller.abort();
bus.dispatchEvent(new CustomEvent('progress', { detail: 90 })); // logs nothingGotchas
| Situation | What happens |
|---|---|
| Signal is already aborted when `addEventListener` runs | The listener is never added, and no error is thrown |
| You want to subscribe again after aborting | Create a new `AbortController`, because a signal aborts only once |
| You pass both `once: true` and `signal` | The listener is removed by whichever happens first |
| You call `removeEventListener` by hand | It still works, and a later abort does nothing harmful |
Combining with other cleanup
Many subscriptions hold resources besides listeners, such as an interval or a socket. Use the same signal for those too, so one abort() cleans up everything:
function poll(target, ms, { signal } = {}) {
const id = setInterval(() => target.dispatchEvent(new Event('tick')), ms);
signal?.addEventListener('abort', () => clearInterval(id), { once: true });
target.addEventListener('tick', () => console.log('tick'), { signal });
}Exercise
You call subscribe(bus, { signal: controller.signal }), then controller.abort(), then subscribe(bus, { signal: controller.signal }) again. Do the new listeners receive events, and how would you fix it?
Show answer
They don't. The signal is already aborted, so addEventListener skips adding the listeners without throwing. To fix it, create a new AbortController for each subscription and pass its signal to the second call.
Exercise
In poll, why is the abort listener registered with { once: true } and not with { signal }?
Show answer
The abort listener is attached to the signal itself and only needs to run once to clear the interval. { once: true } removes it after it fires. Passing the same signal as its signal option would remove it at the moment of abort, so it might never run.