Skip to content
jshacks.dev
Patterns

The Observer Pattern in JavaScript, With Real Examples

The observer pattern lets one object notify many others when it changes. See subscribe and unsubscribe, EventTarget, stores and memory leak traps in JavaScript.

8 min read
Summarize in AI
Flat illustration of models joined by relationships, with the JavaScript, PostgreSQL, MariaDB, SQLite and MySQL logos.

The observer pattern lets one object, the subject, notify many others, the observers, whenever something changes, without the subject knowing who they are. It is everywhere in JavaScript: DOM events and addEventListener, Node.js EventEmitter, MutationObserver, IntersectionObserver, RxJS observables, signals in modern frameworks and the subscription model of every state store. The shape is always the same: a way to subscribe, a way to unsubscribe and a notification step. This post builds the pattern in JavaScript on Node.js 24 from a minimal subject, then a reusable store with selectors, then shows the built-in EventTarget and EventEmitter, and spends time on what goes wrong: memory leaks from forgotten subscriptions, errors in observers, re-entrancy and notification order. Every sample prints its output.

The smallest subject

A subject keeps a list of callbacks and calls each one when it changes.

subject.mjsJavaScript
class Thermostat {
  #temperature = 20;
  #observers = new Set();

  subscribe(observer) {
    this.#observers.add(observer);
    return () => this.#observers.delete(observer);
  }

  set(temperature) {
    if (temperature === this.#temperature) return;
    const previous = this.#temperature;
    this.#temperature = temperature;
    for (const observer of this.#observers) observer(temperature, previous);
  }

  get temperature() {
    return this.#temperature;
  }
}

const thermostat = new Thermostat();

const unsubscribeDisplay = thermostat.subscribe((now, before) => console.log(`display: ${before} -> ${now}`));
thermostat.subscribe((now) => {
  if (now > 25) console.log("alarm: too hot");
});

thermostat.set(22);
thermostat.set(22);
thermostat.set(27);
unsubscribeDisplay();
thermostat.set(18);
console.log(thermostat.temperature);
Text
display: 20 -> 22
display: 22 -> 27
alarm: too hot
18

Three details worth copying. subscribe returns an unsubscribe function, which is easier to use correctly than a separate unsubscribe(observer) that needs the same function reference. Observers are kept in a Set, so subscribing the same function twice does not call it twice. And set skips notification when the value did not change, which avoids pointless work and some infinite loops. After unsubscribeDisplay(), the display no longer fires, and the alarm observer stays silent for 18 since it is not above 25.

Push and pull

The subject above pushes the new value to observers. Some designs notify with no data and let each observer pull what it needs, which suits subjects with large or varied state.

pull.mjsJavaScript
class Cart {
  items = [];
  #observers = new Set();
  subscribe(fn) {
    this.#observers.add(fn);
    return () => this.#observers.delete(fn);
  }
  add(item) {
    this.items.push(item);
    for (const fn of this.#observers) fn(this);
  }
}

const cart = new Cart();
cart.subscribe((c) => console.log(`badge: ${c.items.length}`));
cart.subscribe((c) => console.log(`total: ${c.items.reduce((s, i) => s + i.price, 0)}`));

cart.add({ name: "Mug", price: 12 });
cart.add({ name: "Poster", price: 8 });
Text
badge: 1
total: 12
badge: 2
total: 20

Passing the subject itself lets each observer read what it cares about. The trade-off is coupling: observers must know the subject's shape. Pushing a small event object is looser and the more common default.

A store with selectors

State libraries are observers with a refinement: an observer wants to be told only when the part it uses changed. Here is a miniature store.

store.mjsJavaScript
export function createStore(initialState) {
  let state = initialState;
  const listeners = new Set();

  return {
    getState: () => state,
    setState(update) {
      const next = { ...state, ...update };
      if (Object.keys(update).every((k) => Object.is(state[k], next[k]))) return;
      state = next;
      for (const listener of [...listeners]) listener(state);
    },
    subscribe(selector, onChange) {
      let selected = selector(state);
      const listener = (nextState) => {
        const nextSelected = selector(nextState);
        if (!Object.is(nextSelected, selected)) {
          const previous = selected;
          selected = nextSelected;
          onChange(nextSelected, previous);
        }
      };
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
  };
}

const store = createStore({ user: "Ada", count: 0 });
store.subscribe((s) => s.count, (now, before) => console.log(`count ${before} -> ${now}`));
store.subscribe((s) => s.user, (now) => console.log(`user is now ${now}`));

store.setState({ count: 1 });
store.setState({ count: 1 });
store.setState({ user: "Grace" });
store.setState({ count: 2, user: "Grace" });
Text
count 0 -> 1
user is now Grace
count 1 -> 2

The user observer ignored both count updates, and the count observer ignored the user update. The second setState({ count: 1 }) did nothing since nothing changed, and the final call changed only count, because user was already Grace. Iterating over a copy of the listeners, [...listeners], protects the loop if a listener unsubscribes itself while being called. This is the core of Redux's subscribe, Zustand's selectors and the reasoning behind React's useSyncExternalStore.

Built-in observers in the platform

You rarely write a subject from scratch. The platform gives you several.

EventTarget is available in Node.js and browsers, with addEventListener, removeEventListener and dispatchEvent.

event-target.mjsJavaScript
class Feed extends EventTarget {
  publish(headline) {
    this.dispatchEvent(new CustomEvent("headline", { detail: headline }));
  }
}

const feed = new Feed();
const controller = new AbortController();

feed.addEventListener("headline", (e) => console.log(`reader 1: ${e.detail}`), { signal: controller.signal });
feed.addEventListener("headline", (e) => console.log(`reader 2: ${e.detail}`), { once: true });

feed.publish("Node.js release");
feed.publish("New TypeScript version");
controller.abort();
feed.publish("This one reaches nobody");
Text
reader 1: Node.js release
reader 2: Node.js release
reader 1: New TypeScript version

The signal option removes the listener when the controller aborts, which is the cleanest way to unsubscribe several listeners at once, and once: true removes a listener after its first call. CustomEvent is available globally in Node.js 19 and later.

EventEmitter from node:events is the Node.js original.

emitter.mjsJavaScript
import { EventEmitter, once } from "node:events";

const jobs = new EventEmitter();
jobs.on("done", (id) => console.log(`finished ${id}`));

setTimeout(() => jobs.emit("done", "job-1"), 5);
const [id] = await once(jobs, "done");
console.log(`awaited ${id}`);
Text
finished job-1
awaited job-1

events.once turns the next emission into a promise, which bridges the observer pattern and async and await. Listeners run in registration order, so the first on fires before the awaiting code resumes.

What goes wrong

Memory leaks from forgotten subscriptions

A subject holds a strong reference to every observer. An observer that is subscribed and never removed stays alive as long as the subject does, along with everything it captured. This is the most common leak in single-page apps and long-running servers.

leak.mjsJavaScript
import { EventEmitter } from "node:events";

const bus = new EventEmitter();

function handleRequest() {
  const bigBuffer = Buffer.alloc(1024 * 1024);
  bus.on("shutdown", () => console.log(bigBuffer.length)); // never removed
}

for (let i = 0; i < 12; i++) handleRequest();
console.log(bus.listenerCount("shutdown"));
Text
12

Each request leaves a listener and a one-megabyte buffer behind. Node.js also prints a MaxListenersExceededWarning once more than ten listeners are added for one event, which is a hint of this leak, not a limit. The fix is to unsubscribe when done: return the cleanup function and call it, use once, use an AbortSignal, or in React, return the unsubscribe from useEffect.

Errors in an observer

One throwing observer stops the loop and the rest never hear about the change.

errors.mjsJavaScript
const observers = [
  () => { throw new Error("observer 1 failed"); },
  () => console.log("observer 2 ran"),
];

try {
  for (const o of observers) o();
} catch (err) {
  console.log(err.message);
}

for (const o of observers) {
  try {
    o();
  } catch (err) {
    console.log(`isolated: ${err.message}`);
  }
}
Text
observer 1 failed
isolated: observer 1 failed
observer 2 ran

Wrap each call in try and catch so a bad observer cannot starve the others, and decide where the error goes, usually a logger.

Re-entrancy and ordering

An observer that changes the subject inside its callback triggers a nested notification before the first loop finishes, so later observers can see events out of order. Either queue changes made during notification and process them after, or forbid changing the subject from inside an observer. Also do not depend on the order observers fire, even though most implementations use insertion order, since that is rarely a documented guarantee.

Observers versus a simple callback

If a subject has exactly one consumer, a callback argument is simpler than a subscription list. The pattern is for one-to-many.

Observer, pub/sub and signals

Strictly, observers subscribe directly to a subject, so each knows the other. In publish-subscribe, a broker sits between publishers and subscribers who know only topic names, which is the mediator shape and what message queues provide. Signals, as in Solid, Preact Signals and Vue's refs, are observers with automatic dependency tracking: reading a signal inside a computation subscribes it, so you never write subscribe by hand.

Where the advice stops

The pattern makes control flow hard to follow, since the cause of an update is a call somewhere else that nobody wrote down. Use it where decoupling is the point: UI updates from state, plugins reacting to lifecycle events and cross-cutting reactions such as analytics. For a direct sequence of steps, call the functions. And always ask who unsubscribes, because that question prevents most of the bugs.

Testing observers

Observers are easy to test because the subject exposes a clear contract. Subscribe a function that records its calls, change the subject, and assert on the recorded values and their order. Then unsubscribe and change it again to prove no further calls arrive. Add a test where one observer throws and confirm the others still run, and one where an observer unsubscribes itself during notification, which is the case that breaks naive loops that iterate over a live collection. A test that counts listeners after a component is created and destroyed catches leaks before they reach production, and it is cheap to write with listenerCount on an EventEmitter or a counter in your own subject.

Observers and async work

Observers are called synchronously in the examples above, so a slow observer delays everyone after it and the code that triggered the change. When an observer does I/O, make the callback async but do not rely on the subject waiting for it, or collect the promises with Promise.allSettled if the subject should wait. Decide on a policy and document it: fire and forget, wait for all, or queue notifications for a later tick. Without one, a failed network call inside an observer becomes an unhandled promise rejection, which in Node.js 15 and later terminates the process by default.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.