Observer & Pub/Sub
Two of the most powerful event-driven patterns in JavaScript. Observer connects subjects directly to observers; Pub/Sub fully decouples publishers from subscribers through a broker. Together they power React state, event emitters, and message-driven architectures.
What is the observer pattern in JavaScript?
In the observer pattern, an object (the subject) keeps a list of subscriber functions and notifies them when something happens. Pub/Sub is similar but adds an event channel in between, so publishers and subscribers don't know about each other. DOM events, EventTarget, Node's EventEmitter and state-store subscriptions all use this idea.
function createEmitter() {
const listeners = new Map();
return {
on(evt, fn) { (listeners.get(evt) ?? listeners.set(evt, new Set()).get(evt)).add(fn);
return () => listeners.get(evt).delete(fn); }, // unsubscribe
emit(evt, data) { listeners.get(evt)?.forEach((fn) => fn(data)); },
};
}
const bus = createEmitter();
const off = bus.on("login", (user) => console.log(user));
bus.emit("login", { name: "Ada" });
off();Observer vs Pub/Sub
| Dimension | Observer Pattern | Pub/Sub Pattern |
|---|---|---|
| Coupling | Direct — subject holds refs to observers | Decoupled — via broker/channel |
| Subject knows observers? | Yes — calls them directly | No — publishes to a channel |
| Observer knows subject? | Yes — subscribes to specific subject | No — subscribes to a channel name |
| Communication | Subject → Observers (direct push) | Publisher → Broker → Subscribers |
| Typical JS usage | EventEmitter, DOM events, React | Message queues, analytics, microservices |
| Scalability | Good for local component trees | Excellent for large, distributed systems |
| Testing | Mock the subject directly | Mock the broker or publish test events |
Where You See These Patterns
Observer in the wild
- •DOM: element.addEventListener('click', fn)
- •Node.js: EventEmitter (stream, process, http)
- •React: useState setter notifies component
- •Vue: reactive() triggers re-render
- •MobX: observable.observe(reaction)
- •RxJS: Observable.subscribe()
- •WebSocket: ws.on('message', handler)
Pub/Sub in the wild
- •Redux: dispatch(action) → reducers
- •Zustand: store.subscribe() via set()
- •BroadcastChannel API (cross-tab messaging)
- •Service Workers: postMessage channel
- •Redis Pub/Sub (server-side)
- •AWS SNS / Google Cloud Pub/Sub
- •Angular: EventEmitter @Output()
Common Pitfalls
Interactive Demo
Code Editor
<button id="buy">Buy item</button>
<p>Cart badge: <b id="badge">0</b></p>
<p id="toast"></p>Preview
Observer and Pub/Sub: summary
Key points
- Always provide a way to unsubscribe, or listeners leak.
- The built-in
EventTargetandCustomEventgive you an emitter for free in browsers. - Overusing global event buses makes the data flow hard to trace.
Frequently asked questions
›What is the difference between observer and pub/sub?
In the observer pattern, subscribers register directly with the subject. In pub/sub, a broker or channel sits between publishers and subscribers, so they're fully decoupled.