Parcel KCL-0001 switches to transit. Who needs to know? The tracking page has to refresh, the customer has to get an SMS, and next month there may be someone else too. If updateStatus calls them one by one, that function has to change every time a new party shows up.
The Observer pattern is for problems like this: one object needs to tell many other objects that something changed. The object that changes (called the subject) keeps a list of functions that asked to be told (called observers or listeners), then calls them all when something happens. It's like a travelling vegetable seller with a WhatsApp list of customers. The moment fresh vegetables arrive, he sends one message to every number on the list. He doesn't need to know who will cook soup and who will make a salad. Anyone who wants in asks to be added to the list, and anyone who's had enough asks to be removed.
The problem: updateStatus knows every party
In the first version of Kancil Courier, updateStatus calls every party that needs to know by itself:
function updateStatus(parcel, status) {
parcel.status = status
sendSms(parcel)
refreshTracking(parcel)
}
Every new party (WhatsApp, the daily report, the courier app) means changing the body of updateStatus. The status code ends up depending on the SMS module, and in a test you can't change a status without sending an SMS too.
Subject, listener, on, emit
Observer turns the direction around: updateStatus only announces "the status changed", and whoever wants to know signs up by themselves.
class EventEmitter {
constructor() {
this.listeners = {} // { status: [fn, fn], ... }
}
on(event, callback) {
if (!this.listeners[event]) this.listeners[event] = []
this.listeners[event].push(callback)
}
emit(event, data) {
(this.listeners[event] || []).forEach((cb) => cb(data))
}
}
const tracker = new EventEmitter()
tracker.on("status", (p) => console.log("SMS: " + p.trackingNo + " " + p.status))
tracker.on("status", (p) => console.log("Tracking page: " + p.status))
function updateStatus(parcel, status) {
parcel.status = status
tracker.emit("status", parcel) // doesn't know who is listening
}
updateStatus({ trackingNo: "KCL-0001" }, "in transit")
// SMS: KCL-0001 in transit
// Tracking page: in transit
this.listenersis an object whose keys are event names ("status"), each holding an array of callbacks for that event.onfirst makes an empty array if that event has never been registered, then adds the callback to its end.emitcalls each callback with thedatait was given, one at a time, in the order of the list. They all finish beforeemitreturns.|| []is the fallback for an event with no listeners yet. Without it,emit("scroll")fails withTypeError: Cannot read properties of undefined (reading 'forEach'). The same fallback helps when counting listeners: an event that was never registered has 0 listeners, and the array's size is read with.length.
Adding WhatsApp now takes one line, tracker.on("status", sendWhatsApp). The body of updateStatus doesn't change.
Remove a listener with off
A listener that's no longer needed has to be removed. off drops the exact same callback from the list:
off(event, callback) {
this.listeners[event] = (this.listeners[event] || []).filter((cb) => cb !== callback)
}
function refresh(p) { console.log("Tracking page: " + p.status) }
tracker.on("status", refresh)
tracker.off("status", refresh) // the same function, so it's removed
off compares functions with !==, so you have to pass the same function, not another one that looks alike. That's why a callback you plan to remove is written as a named function or kept in a variable. Many libraries make on return its own remover, Redux's store.subscribe for one: const stop = tracker.on(...), then stop() when the page closes.
Before going on, take a guess: a customer opens the tracking page three times, and each time the page registers a new listener without ever calling off. The parcel status then changes once. How many times does the tracking page refresh?
Three times, because there are three listeners on the list. Worse, all three old pages stay in memory because the listener list still holds them. This is called a memory leak. Node.js prints a MaxListenersExceededWarning as soon as one event has more than 10 listeners, because that usually means someone forgot to remove them.
Observers built into the platform
You use this pattern all the time already:
- Browser:
button.addEventListener("click", fn)andremoveEventListener. Any object can be a subject throughEventTarget:target.dispatchEvent(new CustomEvent("status", { detail: parcel })). - Node.js:
EventEmitterfrom thenode:eventsmodule, withon,off,emit,once(listen once, then remove) andlistenerCount(event).
One difference: when a listener throws an error. In our class and in Node's EventEmitter, forEach stops right there, the listeners after it don't run, and the error flies out of emit into updateStatus. In the browser, EventTarget reports the error in the console and still calls the next listener.
The browser (and Node.js) also has two ways to remove a listener without keeping the function: { once: true } removes it after it runs once, and { signal } from an AbortController removes many listeners with one abort(). Both close the memory leak from the section above:
const tracker = new EventTarget()
const page = new AbortController()
tracker.addEventListener("status", (e) => console.log("Tracking page: " + e.detail), { signal: page.signal })
tracker.addEventListener("status", (e) => console.log("Courier map: " + e.detail), { signal: page.signal })
tracker.addEventListener("status", (e) => console.log("Only once: " + e.detail), { once: true })
tracker.dispatchEvent(new CustomEvent("status", { detail: "in transit" }))
page.abort() // the tracking page closes: the first two listeners are removed together
tracker.dispatchEvent(new CustomEvent("status", { detail: "out for delivery" })) // nothing prints
The output is Tracking page: in transit, Courier map: in transit and Only once: in transit. The second event prints nothing.
When a direct call is enough
- One receiver that has to answer. Address validation must return true or false.
emitdoesn't hand back anything from its listeners, so just call the function. - A few parties that never change. With Observer,
updateStatusdoesn't show who is listening. If there's one fixed receiver, a direct call is easier to follow.
⚠️ Doubled notifications, or none at all
- Forgetting
off. Listeners pile up every time a page opens: double notifications, and memory that's never freed. offwith a new arrow function.tracker.off("status", (p) => refresh(p))removes nothing, because that's a new function that was never registered.- One listener fails, the rest go quiet. In a home-made emitter and in Node, the listeners after the failing one don't run. Catch errors inside a risky listener, such as the SMS sender.
- Forgetting the
|| []fallback.emitor a listener count for an event that was never registered has to be safe: the count is 0, not a TypeError.
TL;DR: The Observer pattern is used when one object needs to tell many other objects about a change. The subject keeps this.listeners = {}, one array of callbacks per event. on(event, callback) signs up (making the array first if it isn't there), emit(event, data) calls every callback of that event with data, in list order, and off(event, callback) drops the exact same function. An event with no listeners is handled with || [], so its count is 0. Forgetting off makes listeners pile up (a memory leak), and an error in one listener stops the rest, except in the browser's EventTarget. On the platform: addEventListener in the browser, EventEmitter in Node.
⚡ The subject announces, listeners sign up
Write:
const tracker = new EventEmitter()
tracker.on("status", (p) => console.log("SMS: " + p.trackingNo + " " + p.status))
tracker.on("status", (p) => console.log("Tracking page: " + p.status))
function updateStatus(parcel, status) {
parcel.status = status
tracker.emit("status", parcel) // doesn't know who is listening
}
Meaning: Observer is used when one object needs to tell many other objects that something changed. Adding WhatsApp takes one line, tracker.on("status", sendWhatsApp), and the body of updateStatus doesn't change.
⚡ on stores, emit calls
Write:
on(event, callback) {
if (!this.listeners[event]) this.listeners[event] = []
this.listeners[event].push(callback)
}
emit(event, data) {
(this.listeners[event] || []).forEach((cb) => cb(data))
}
Meaning: this.listeners keeps one array of callbacks per event, and emit calls them all in list order. || [] makes an event with no listeners safe: its count is 0, not a TypeError.
⚡ Remove with off
Write:
off(event, callback) {
this.listeners[event] = (this.listeners[event] || []).filter((cb) => cb !== callback)
}
Guess first: the tracking page is opened three times, and each time registers a new listener without off. The status changes once. How many times does the page refresh?
Three times, because there are three listeners on the list. All three old pages also stay in memory. This is called a memory leak.
Meaning: off drops the exact same function. tracker.off("status", (p) => refresh(p)) removes nothing, because that's a new function that was never registered.