Back to results for “Classes & Class Syntax”
JavaScript › Design Patterns in JavaScript

How do you implement the Observer pattern in JavaScript?

Intermediate

Answer

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.

Common follow-ups: How does Node's built-in EventEmitter class relate to this pattern?