What is the Observer pattern, and how does Node.js's EventEmitter class implement it natively?
Short answer
The Observer pattern lets an object (the subject) maintain a list of dependents (observers) and notify them automatically of state changes, without the subject needing to know any specifics about the observers -- Node.js's built-in EventEmitter class is a direct, first-class…
Advertisement
AModel answer
The Observer pattern lets an object (the subject) maintain a list of dependents (observers) and notify them automatically of state changes, without the subject needing to know any specifics about the observers -- Node.js's built-in EventEmitter class is a direct, first-class implementation of this pattern: any object can extend EventEmitter, emit named events, and any number of listeners can subscribe to those events independently.
const EventEmitter = require('node:events');
class OrderProcessor extends EventEmitter {
processOrder(order) {
// ... process order ...
this.emit('orderCompleted', order);
}
}
const processor = new OrderProcessor();
processor.on('orderCompleted', (order) => sendConfirmationEmail(order));
processor.on('orderCompleted', (order) => updateInventory(order));Real-world example
An order-processing service emits an 'orderCompleted' event rather than directly calling sendEmail() and updateInventory() from inside the processing function, letting new behaviors (like triggering a loyalty-points update) be added later by simply attaching a new listener, without modifying the core processing logic at all.
Likely follow-ups
- What happens if a listener attached to an EventEmitter throws an error -- how does that affect other listeners?
- How does the Observer pattern relate conceptually to the pub/sub pattern used with message queues?
Related topics