Observer
The observer pattern lets objects subscribe to notifications. When the subject changes, it calls every observer. DOM events, EventTarget, and Rx-style streams are this idea.
Detailed Explanation
A subject holds a list of listeners. subscribe(fn) adds one. unsubscribe(fn) removes it. notify(data) calls each fn(data). Observers do not poll. They are told.
JavaScript's DOM is the built-in subject: element.addEventListener("click", fn) / removeEventListener. EventTarget is the same API you can extend for your own types. Node's EventEmitter (on / off / emit) is the server-side spelling. A tiny custom bus is a Set of functions.
The pattern decouples publishers from subscribers. A Cart does not import a Analytics class; analytics subscribes to "item-added". The cost is implicit flow: a bug is "who subscribed?" not a call stack you wrote in one place.
Unsubscribe is mandatory for long-lived subjects. A component that ons a global store and never offs leaks the component (closure + detached DOM). Store the same function reference. AbortSignal on addEventListener ({ signal }) is the modern way to batch-remove.
Synchronous notify means a listener can re-enter subscribe or mutate the list while you iterate. Snapshot the list ([...listeners]) before calling. A thrown listener should not skip the rest unless you want that; wrap calls in try/catch.
What it costs you: hidden coupling and leaky subscriptions. Too many global events become a bag of string names. Prefer typed events or a small set of named subjects.
Reach for observer when many independent features must react to one change. Reach for a direct call when there is one consumer you own. Reach for pub/sub when publishers and subscribers should not even share the subject object, only a channel name.
Code Examples
function createSubject() {
const listeners = new Set();
return {
subscribe(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
},
notify(data) {
for (const fn of [...listeners]) fn(data);
},
};
}
const cart = createSubject();
const stop = cart.subscribe((item) => console.log("added", item.id));
cart.notify({ id: "book" }); // => added book
stop();const { EventEmitter } = require("node:events");
const bus = new EventEmitter();
bus.on("ready", (name) => console.log(name));
bus.emit("ready", "ok"); // => okCommon Gotchas
You cannot remove an inline arrow you did not store
keep the function or use `{ signal: ac.signal }` and `ac.abort()`.
Notifying while mutating the listener set skips or double-calls
iterate a copy.
A global emitter plus a forgotten `off` is a leak
unsubscribe on teardown.
Sync listeners see half-updated state if you notify mid-mutation
finish the change, then notify.