Sub topic 9
Event Listeners: Callbacks That Fire Many Times
This chapter assumes you know how to write and pass callbacks, and that you understand asynchronous callbacks and the event loop from earlier chapters. You should also be able to run scripts with Node.js.
Most callbacks you have seen so far run once. fs.readFile calls its callback a single time, with either an error or the file's contents. An event listener is a callback that you register for a named event. It runs every time that event happens, until you remove it. Clicks, incoming network data, and timer ticks all work this way.
The Working Model
An event source keeps a list of listeners for each event name. Registering a listener adds your function to that list. When the source emits the event, it walks the list and calls each function with the event's data. Removing a listener takes your function back out of the list.
In Node.js, the EventEmitter class from node:events provides this behavior. In browsers, DOM elements provide it through addEventListener and removeEventListener.
Registering and Removing a Listener
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
function onTick(n) {
console.log('tick', n);
}
emitter.on('tick', onTick);
emitter.emit('tick', 1); // tick 1
emitter.off('tick', onTick);
emitter.emit('tick', 2); // nothing is loggedoff finds the listener by identity. It looks for the exact function object you registered. That is why onTick is a named function stored in a variable.
Common Errors
Removing an anonymous function
This code looks reasonable but removes nothing:
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
emitter.on('tick', (n) => console.log('tick', n));
emitter.off('tick', (n) => console.log('tick', n)); // a different function object
emitter.emit('tick', 1); // tick 1, the listener is still registeredTwo arrow functions with identical source code are still two separate objects. If you plan to remove a listener, keep a reference to it. The same rule applies to bind, because each call to bind returns a new function. Store the bound function once and pass that stored reference to both on and off.
Forgetting to remove listeners
A registered listener keeps its closure alive, along with every variable it captured. If you register a listener each time some object is created and never remove it, the listener list grows and memory is never freed. Node.js prints a MaxListenersExceededWarning when more than 10 listeners are attached to one event. Treat that warning as a sign of a leak, not as a limit you should raise.
Assuming emit is asynchronous
emitter.emit calls its listeners synchronously, in the order they were registered, before emit returns. The listeners do not wait in the task queue.
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
emitter.on('ready', () => console.log('listener'));
console.log('before');
emitter.emit('ready');
console.log('after');
// before, listener, afterThe asynchronous part is the trigger. A socket emits 'data' from an event loop callback when bytes arrive. The emit itself runs straight through.
Listening Once
For an event you only care about the first time, use once. The emitter removes the listener before calling it.
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
emitter.once('connect', () => console.log('connected'));
emitter.emit('connect'); // connected
emitter.emit('connect'); // nothing is loggedBrowsers offer the same behavior with element.addEventListener('click', handler, { once: true }).
The Special 'error' Event
EventEmitter treats the 'error' event differently from all other events. If you emit 'error' and no listener is registered for it, the emitter throws the error, and an uncaught throw crashes the Node.js process. Any emitter that can fail, such as a stream or a server, should have an 'error' listener attached.
const { EventEmitter } = require('node:events');
const emitter = new EventEmitter();
emitter.on('error', (err) => console.error('Handled:', err.message));
emitter.emit('error', new Error('disk full')); // Handled: disk full| Method | Runs the callback | Removal |
|---|---|---|
| `on` / `addListener` | Every emit | Call `off` with the same function reference |
| `once` | First emit only | Removed automatically |
| `off` / `removeListener` | Not applicable | Removes one registration |
Exercise
A class registers emitter.on('data', this.handle.bind(this)) in its constructor and later calls emitter.off('data', this.handle.bind(this)) in a close() method. The handler keeps running after close(). Why, and how do you fix it?
Show answer
Each call to bind creates a new function object, so off receives a function that was never registered and removes nothing. Bind once and store the result, for example this.onData = this.handle.bind(this) in the constructor. Then call emitter.on('data', this.onData) and later emitter.off('data', this.onData).
Exercise
What does this print? emitter.on('x', () => console.log(1)); emitter.on('x', () => console.log(2)); console.log(0); emitter.emit('x'); console.log(3);
Show answer
It prints 0, 1, 2, 3. emit calls the listeners synchronously, in the order they were registered, before it returns.