Sub topic 9
Event Listeners: Callbacks That Fire Many Times
The callbacks you have seen so far run once. map calls its callback once per element and then finishes. fs.readFile calls its callback once, when the read completes or fails. An event listener is different. It is a callback you register to run every time a named event happens, for as long as it stays registered. A click handler, a data handler on a network stream and a tick handler on a timer all work this way.
This chapter assumes you know asynchronous callbacks, the error-first convention, and how this behaves when you pass a method as a callback. The code runs in Node.js 18 or later. It uses EventEmitter and the EventTarget interface that Node shares with browsers.
The Model: A Named List of Functions
An event source keeps a table. Each key is an event name, and each value is a list of callback functions. Registering a listener appends a function to the list. Emitting an event walks the list and calls each function with the event's arguments. Removing a listener takes a function out of the list.
Most listener bugs come from one of two facts in this model. The source holds a reference to your function, so the function and everything its closure captures stay alive until you remove it. And removal compares functions by identity, so you can only remove a listener if you still have the exact function object you registered.
Registering, Emitting and Removing with EventEmitter
Node's EventEmitter is the base class for streams, HTTP servers, child processes and many libraries. Here is the full lifecycle:
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
function onTick(n) {
console.log('tick', n);
}
function logEvery(n) {
console.log(' (listener 2 saw', n + ')');
}
emitter.on('tick', onTick);
emitter.on('tick', logEvery);
console.log('before emit');
const hadListeners = emitter.emit('tick', 1);
console.log('after emit, hadListeners =', hadListeners);
emitter.off('tick', onTick);
emitter.emit('tick', 2);
console.log('remaining listeners:', emitter.listenerCount('tick'));Output:
before emit
tick 1
(listener 2 saw 1)
after emit, hadListeners = true
(listener 2 saw 2)
remaining listeners: 1The output shows several things:
emitis synchronous. Both listeners run beforeemitreturns, soafter emitprints last. Events often come from asynchronous sources such as sockets and timers, but the dispatch itself is a plain loop over the list.- Listeners run in the order they were registered. Use
prependListenerif you need one to run first. emitreturnstrueif at least one listener was registered for that event.offis an alias forremoveListener.onis an alias foraddListener.
The Identity Trap: You Can't Remove What You Can't Name
Removal matches listeners with === on the function object. Two functions with identical source code are still two different objects. This is the most common listener bug:
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
// Bug 1: anonymous function, no reference kept
emitter.on('tick', (n) => console.log('anon', n));
emitter.off('tick', (n) => console.log('anon', n)); // a different function: no effect
// Bug 2: bind creates a new function every time it is called
class Clock {
constructor() {
this.ticks = 0;
}
handle(n) {
this.ticks += n;
}
}
const clock = new Clock();
emitter.on('tick', clock.handle.bind(clock));
emitter.off('tick', clock.handle.bind(clock)); // also a different function
console.log('listeners after bad removal:', emitter.listenerCount('tick')); // 2
// Fix: create the function once, keep the reference, remove with it
emitter.removeAllListeners('tick');
const boundHandle = clock.handle.bind(clock);
emitter.on('tick', boundHandle);
emitter.emit('tick', 5);
emitter.off('tick', boundHandle);
emitter.emit('tick', 5);
console.log('ticks:', clock.ticks); // 5
console.log('listeners after good removal:', emitter.listenerCount('tick')); // 0The earlier chapter on this showed that bind and arrow functions both fix a lost this. With listeners there is an extra rule: store the bound function or arrow function in a variable or property before you register it, because you will need that same object to remove it. A common pattern is to bind in the constructor, as in this.handle = this.handle.bind(this), or to define the handler as an arrow-function class field.
removeAllListeners('tick') removes every listener for that event, including listeners other code registered. Use it only on emitters you own completely.
Listeners That Remove Themselves: once
Many events matter only the first time, such as ready, connect or the first response. once registers a wrapper that removes itself and then calls your function:
const { EventEmitter } = require('node:events');
const server = new EventEmitter();
function onReady(port) {
console.log('ready on port', port);
}
server.once('ready', onReady);
server.emit('ready', 3000); // ready on port 3000
server.emit('ready', 3001); // nothing
// A once-listener can be cancelled before it fires, using the original function
server.once('ready', onReady);
server.off('ready', onReady);
console.log(server.listenerCount('ready')); // 0The registered entry is a wrapper, but Node records your original function on it, so off(onReady) still finds it.
Order and Mutation During an Emit
What happens if a listener adds or removes listeners while an emit is running? EventEmitter copies the listener array before it starts calling listeners. Listeners added during an emit don't run in that emit. Listeners removed during an emit still run in that emit if they had not been called yet.
const { EventEmitter } = require('node:events');
const e = new EventEmitter();
function second() {
console.log('second');
}
e.on('go', () => {
console.log('first');
e.off('go', second); // still runs this time
e.on('go', () => console.log('late')); // waits for the next emit
});
e.on('go', second);
e.emit('go');
console.log('---');
e.emit('go');Output:
first
second
---
first
lateThe second emit runs first again. That run registers another late listener, which shows how a listener that adds listeners can grow the list each time it fires.
Errors in Listeners
Listener errors are handled differently from the error-first convention, so check two cases.
The first case is the error event. If an EventEmitter emits 'error' and nobody is listening, emit throws the error. In Node, that usually crashes the process. Any emitter that can fail, such as a stream, socket or server, needs an error listener.
The second case is a listener that throws. The exception comes out of emit, and the listeners after it in the list do not run.
const { EventEmitter } = require('node:events');
const e = new EventEmitter();
try {
e.emit('error', new Error('disk full'));
} catch (err) {
console.log('emit threw:', err.message); // emit threw: disk full
}
e.on('error', (err) => console.log('handled:', err.message));
e.emit('error', new Error('disk full')); // handled: disk full
e.on('data', () => {
throw new Error('bad listener');
});
e.on('data', () => console.log('never reached'));
try {
e.emit('data');
} catch (err) {
console.log('caught from emit:', err.message);
}The Standard Interface: EventTarget and addEventListener
Browsers use EventTarget. DOM elements, window, WebSocket and AbortSignal all inherit from it. Node also provides EventTarget as a global, so the following runs in both environments:
const target = new EventTarget();
function onPing(event) {
console.log('ping received:', event.type);
}
// Adding the same function twice is ignored: EventTarget de-duplicates
target.addEventListener('ping', onPing);
target.addEventListener('ping', onPing);
target.dispatchEvent(new Event('ping')); // logs once
// once option: removed automatically after the first call
target.addEventListener('ping', () => console.log('only first'), { once: true });
// signal option: remove many listeners with one abort() call
const controller = new AbortController();
target.addEventListener('ping', () => console.log('A'), { signal: controller.signal });
target.addEventListener('ping', () => console.log('B'), { signal: controller.signal });
target.dispatchEvent(new Event('ping')); // ping received, only first, A, B
controller.abort();
target.dispatchEvent(new Event('ping')); // ping received
target.removeEventListener('ping', onPing);
target.dispatchEvent(new Event('ping')); // nothingThe signal option fixes the identity trap for anonymous listeners. You never need a reference to the function, only to the controller. A component can register a dozen anonymous handlers with one signal and remove them all with one abort() call when it is torn down.
In the browser, the capture flag is part of a listener's identity. If you registered with { capture: true }, you must remove with { capture: true }, or removeEventListener silently does nothing.
EventEmitter and EventTarget Compared
| Behavior | Node `EventEmitter` | `EventTarget` (browser and Node) |
|---|---|---|
| Register / remove | `on` / `off` | `addEventListener` / `removeEventListener` |
| Listener arguments | Whatever was passed to `emit` | A single `Event` object |
| Same function added twice | Runs twice | Added once (de-duplicated) |
| One-shot | `once(name, fn)` | `{ once: true }` |
| Bulk removal | `removeAllListeners(name)` | `{ signal }` with `AbortController` |
| Listener throws | Exception leaves `emit`, later listeners skipped | Error reported as uncaught, later listeners still run |
| Unhandled `'error'` | `emit` throws | No special meaning |
| `this` in a regular function | The emitter | The target (`event.currentTarget`) |
Listener Leaks
Each registered listener keeps its closure alive. If an object registers a listener on a long-lived emitter and never removes it, the object can't be garbage-collected. Every new instance adds another listener. Node detects a common form of this leak. When more than 10 listeners are registered for one event on one emitter, Node prints a MaxListenersExceededWarning. This is a warning, not an error, and nothing stops the leak.
const { EventEmitter } = require('node:events');
const bus = new EventEmitter();
class Widget {
constructor(id) {
this.id = id;
this.onUpdate = (value) => console.log(`widget ${this.id} got`, value);
bus.on('update', this.onUpdate);
}
destroy() {
bus.off('update', this.onUpdate);
}
}
const widgets = [];
for (let i = 0; i < 3; i++) widgets.push(new Widget(i));
bus.emit('update', 42);
widgets.forEach((w) => w.destroy());
console.log('listeners left:', bus.listenerCount('update')); // 0A clean design pairs each registration with its removal in one place. Keep the handler on the instance and remove it in destroy. Alternatively, have the subscribe function return an unsubscribe function, as in const stop = subscribe(fn); ... stop();. Raise the warning threshold with setMaxListeners only when you have confirmed that many listeners are intended.
When a Listener Is the Wrong Tool
A listener fits when something can happen any number of times. If you only need to know that something happened once, such as a connection opening or a file finishing, a single callback or a Promise expresses that more directly. A one-shot listener also races with the event: if you register after the event has already fired, you wait forever. Node's events.once(emitter, name) returns a Promise for the next occurrence. The final chapter on Promises covers that style.
Exercise
A class registers emitter.on('data', this.handle.bind(this)) in its constructor and calls emitter.off('data', this.handle.bind(this)) in close(). After creating and closing 11 instances, Node prints MaxListenersExceededWarning. Why, and what is the smallest fix?
Show answer
Each bind call returns a new function, so the function passed to off never matches the one passed to on, and no listener is ever removed. Eleven instances leave 11 listeners, which exceeds the default limit of 10. The fix is to create the bound function once, for example this.handle = this.handle.bind(this) in the constructor, then register and remove that same reference with emitter.on('data', this.handle) and emitter.off('data', this.handle).
Exercise
Predict the output: const e = new EventEmitter(); e.on('x', () => console.log(1)); e.on('x', () => { throw new Error('boom'); }); e.on('x', () => console.log(3)); try { e.emit('x'); } catch (err) { console.log('caught', err.message); } console.log('done'); How would it differ with EventTarget?
Show answer
It logs 1, then caught boom, then done. The throw leaves emit, so the third listener never runs. With EventTarget and dispatchEvent, 1 and 3 would both log, the error would be reported as an uncaught exception instead of being thrown to the caller, and the catch block would not run.
Exercise
You register five anonymous arrow-function listeners on several DOM elements inside a component. How can you remove all of them when the component unmounts, without keeping references to the functions?
Show answer
Create one AbortController, pass { signal: controller.signal } to every addEventListener call, and call controller.abort() on unmount. Aborting the signal removes every listener registered with it.