JavaScript › Design Patterns in JavaScript
How do you implement the Observer pattern in JavaScript?
IntermediateAnswer
Maintain a list of subscriber callback functions; provide a subscribe() method to add them and a notify() (or emit()) method that loops through and calls each one when an event occurs — this decouples the event source from its consumers.
class EventEmitter {
#listeners = [];
subscribe(fn) { this.#listeners.push(fn); }
emit(data) { this.#listeners.forEach(fn => fn(data)); }
}Real-world example Powering a custom pub-sub system for decoupled communication between UI components.