Observer Pattern — Design Patterns

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…

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

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:

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

⚠️ Doubled notifications, or none at all

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.

What you will learn