Pattern 03/22 · Behavioral
Observer
Let many parties subscribe to "listen" to an event source; when the source changes state, it notifies all of them without knowing who is listening or how many there are.
01 — It starts with code that is breaking
Problem
Your page has a CartBadge, a MiniCart, an analytics track() function, and a socket that syncs the cart across tabs. All four need to know "someone just added an item". You put it all in addToCart(): call updateBadge(), then track(), then toast(), then socket.emit(). Four lines. Done in 5 minutes, every reviewer nods.
What happens next follows the natural order of things. A "buy again" feature ships; another dev writes reorder() and doesn't call track. Analytics under-counts orders by 7%, no error is ever thrown, and three weeks later someone asks why the conversion rate dropped. Then you need a toast, push notifications, an audit log: every new consumer means editing the producer, and the producer now lives in four places: addToCart, reorder, applyCoupon, and a server hook.
This kind of coupling also breaks SSR. addToCart imports useToast to show "Added to cart", and useToast touches document. On the client, everything's fine. Until someone imports addToCart into a server route or a server/api handler: Nuxt renders on the server, and you get document is not defined from a file nobody thought had anything to do with UI. The producer doesn't just know about the consumer, it imports it, and that dependency spreads through the whole module graph.
The opposite direction has an equally familiar smell: a child component holds a ref to its parent and calls parent.refresh(), or you pass onChanged down four levels of props just so a grandchild can tell its grandparent something. "Who's listening" gets encoded into the app's tree structure, so every time you add a wrapper component you have to fix the props chain that goes with it.
The problem, stated precisely: the number of consumers isn't fixed and doesn't belong to the producer, yet the producer's code assumes the opposite. Any design where "adding a listener" requires editing "the emitter" will break, literally: you will forget to edit one place, and the price is wrong data in silence, not a crash.
02 — The idea, before touching code
Solution
Observer: the subject keeps a list of handlers. A consumer subscribes itself when it comes to life and unsubscribes itself when it dies. emit() does exactly one thing: walk the list. From then on the producer knows exactly one fact, "someone might be listening", and doesn't change a single line when you add a fifth consumer.
That's why this is the pattern you meet most in web development, not because it's the prettiest but because it's the default mechanism behind everything you use daily: DOM events, Vue 3 reactivity, Node EventEmitter, RxJS, WebSocket clients, VueUse useEventBus. Learning Observer is mostly learning to use it correctly and not break it.
The real substance is in three things tutorials tend to skip. Unsubscribing: forget it and you get a memory leak and the "listener runs twice after hot reload" bug. Timing and order: emitting mid-transaction makes observers read uncommitted data; listeners run in registration order, and registration order depends on mount order. Heavy work inside observers: emit() runs synchronously on the main thread, and 8 listeners × 40ms means a frozen UI. Plus a fourth: a global bus with no types, no owner and no central list of event names will degrade into the place nobody dares touch.
03 — Doing it for real, one code fragment per step
Step by step
The "bad smell" version: the producer calls each consumer directly
Write this version first so you can see clearly which part will get edited again. The producer knows the consumers' names, the modules they live in, even the order they have to run in.
import { updateBadge } from '~/composables/useBadge' // UI
import { track } from '~/utils/analytics' // tracking
import { toast } from '~/composables/useToast' // UI, touches document
import { socket } from '~/plugins/socket' // network
export async function addToCart(sku: string, qty = 1) {
const item = await api.cart.add(sku, qty)
updateBadge()
track('cart_add', { sku, qty })
toast('Added to cart')
socket.emit('cart:sync', item)
return item
}
// reorder.ts - 3 months later, a different file, a different dev
export async function reorder(orderId: string) {
const items = await api.order.items(orderId)
for (const it of items) await api.cart.add(it.sku, it.qty)
updateBadge() // badge only. Forgot track, toast, socket. Nobody notices.
}reorder is missing one line and the numbers are wrong for three weeks.Minimal subject: one Map and one loop
The whole mechanism is 18 lines. Write it by hand once so event systems stop feeling like magic, and so you see that emit is nothing more than a for loop. That explains every pitfall in steps 5 and 6.
Use Map<event, Set<handler>>: a Set blocks duplicate subscriptions and gives you O(1) delete. And type the event names from day one; free-form strings are how a bus starts turning into a dumpster.
type Handler<T> = (payload: T) => void
export class Emitter<Events extends Record<string, unknown>> {
private handlers = new Map<keyof Events, Set<Handler<any>>>()
on<K extends keyof Events>(event: K, fn: Handler<Events[K]>) {
const set = this.handlers.get(event) ?? new Set()
set.add(fn as Handler<any>)
this.handlers.set(event, set)
}
emit<K extends keyof Events>(event: K, payload: Events[K]) {
const set = this.handlers.get(event)
if (!set) return
for (const fn of set) (fn as Handler<Events[K]>)(payload) // SYNCHRONOUS, in registration order
}
}
type CartEvents = { 'cart:add': { sku: string, qty: number }, 'cart:clear': undefined }
const bus = new Emitter<CartEvents>()
bus.on('cart:add', ({ sku }) => console.log('badge <-', sku))
bus.emit('cart:add', { sku: 'AO-1', qty: 1 }) // badge <- AO-1
bus.emit('cart:clear', undefined) // nobody listening: silent, no errorfor loop: synchronous, ordered, and the whole loop stops if one handler throws.Mandatory: `on()` must return an unsubscribe function
In a SPA, consumers die (components unmount, routes change, modals close). If the bus API only has on, a subscriber has no way to back out, and you end up having to remember every handler by name. Make on() return the cancel function: subscribing and unsubscribing go together, in the same place, with no naming needed.
The more modern option for standard DOM events: AbortController. One signal turns off a whole group of listeners, including the ones you forgot you attached.
on<K extends keyof Events>(event: K, fn: Handler<Events[K]>): () => void {
const set = this.handlers.get(event) ?? new Set()
set.add(fn as Handler<any>)
this.handlers.set(event, set)
return () => { set.delete(fn as Handler<any>) } // <- the real product of on()
}
// Option 1: keep the function that was returned
const off = bus.on('cart:add', refreshBadge)
off()
// Option 2: AbortController - clean up a batch, no references to remember
const ac = new AbortController()
btn.addEventListener('click', refreshBadge, { signal: ac.signal })
window.addEventListener('resize', refreshBadge, { signal: ac.signal })
ac.abort() // removes BOTH listeners
// Option 3: off by "owner", useful when the handler is an anonymous closure
on('cart:add', () => refreshBadge(), { owner: 'CartBadge' })
offBy('CartBadge') // clean sweep when the component unmountsaddEventListener returns void, and that's a historical mistake in the DOM. Don't repeat it in your own bus: an on that doesn't return off is an incomplete design.Tie it to the lifecycle: unmount means off
Vue has no idea what you've subscribed to on your own bus. The gap between onMounted and onBeforeUnmount is where memory leaks live. The least error-prone fix: don't rely on devs remembering; wrap the subscription in a composable that cleans up after itself.
Vue 3 already has this concept for its own reactivity: effect() returns a stop function, and watch/watchEffect stop automatically when the component's scope is disposed (that's what onScopeDispose is for). Applying the same mechanism to your own bus is all it takes.
import { getCurrentScope, onScopeDispose } from 'vue'
export function useBusEvent<K extends keyof CartEvents>(event: K, fn: Handler<CartEvents[K]>) {
const off = useCartBus().on(event, fn)
if (getCurrentScope()) onScopeDispose(off) // setup() always runs inside a scope
else console.warn('useBusEvent called outside a scope: nobody will call off for this')
return off
}
// CartBadge.vue - no more stray onMounted/onBeforeUnmount
<script setup lang="ts">
useBusEvent('cart:add', refreshBadge) // auto-off when the component is destroyed
useBusEvent('cart:clear', resetBadge)
</script>
// Critical condition: useCartBus() must return EXACTLY ONE instance (module scope or pinia).
// If each component calling useCartBus() gets a different Map, nobody hears anybody, and nobody owns the leak.Emit after commit, never mid-transaction
Observers run immediately, on the same stack. That means if you emit before the DB write finishes, an observer that reads the DB will see stale data: the "email sent for an order that doesn't exist yet" bug. Conversely, an observer that throws will fail the whole transaction just because a toast broke.
Two rules you can apply right now: (1) emit after the commit, (2) observer errors get logged, not rolled back. The business operation is already done; don't let a dead analytics endpoint cancel an order.
// WRONG: the observer reads the DB while data is not yet committed
async function markPaid(orderId: string) {
bus.emit('order:paid', { orderId }) // the email sender reads the db right now -> sees nothing
await db.order.markPaid(orderId)
}
// RIGHT: commit first, notify after, a notify error must not kill the transaction
async function markPaid(orderId: string) {
await db.$transaction(async tx => {
await tx.order.update({ data: { status: 'paid' } })
await tx.audit.create({ data: { kind: 'paid', orderId } })
})
for (const handler of paidHandlers) {
try { await handler({ orderId }) }
catch (e) { logger.error({ e, handler: handler.name }, 'order:paid observer failed') }
}
}try/catch inside the loop isn't paranoia: one failing observer stops the loop, and the other 4 observers never run.emit is a for loop, not a queue. If someone throws mid-loop, the ones after them never get called.Don't do heavy synchronous work inside an observer
Because emit() is a synchronous for loop, the total time of all observers sits on the path of the click. Recomputing a price table, rebuilding a 5,000-row list, calling report(): all of it freezes the UI, and the profiler will point at emit as a 300ms hole.
An observer should mark and return ("something changed"), with the heavy work collected in one place that runs later, batched with a debounce or a microtask. Also watch out for re-entrancy: an observer emits an event whose other observer emits back → infinite loop, stack overflow, and a stack trace that's very hard to read.
bus.on('cart:add', () => recomputeEverything()) // 40ms x 8 listeners = UI frozen for 320ms
// The observer only MARKS; the heavy work runs ONCE after things go quiet
let queued = false
bus.on('cart:add', () => {
if (queued) return
queued = true
queueMicrotask(() => { queued = false; recomputeEverything() })
})
// 20 add-to-carts in a row -> recomputeEverything() runs EXACTLY once
// Re-entrancy: two observers "calling each other" -> crash
bus.on('cart:add', () => bus.emit('cart:sync'))
bus.on('cart:sync', () => bus.emit('cart:add', { sku: 'AO-1', qty: 1 })) // infinite
// Guard: an "emitting" flag + depth limit, or split event names into two clear directions.Spot Observer everywhere: same pattern, different API
When you meet a new event system, don't learn it from scratch. Just ask three questions: what does on return so I can unsubscribe? is emit synchronous or queued? if one handler throws, do the others still run?
// 1. DOM EventTarget: off needs the EXACT reference (inline arrow in render = can't be removed)
const onScroll = () => {}
window.addEventListener('scroll', onScroll, { passive: true })
window.removeEventListener('scroll', onScroll) // one missing line = one leak
// 2. AbortController: unsubscribe without remembering references
const ac = new AbortController()
btn.addEventListener('click', refresh, { signal: ac.signal })
ac.abort() // Node.js also supports signal since 15.4
// 3. Vue 3 reactivity: effect() returns a stop handle; watch stops with its scope
const stop = effect(() => console.log(cart.value.total))
stop() // no stop = the effect lives forever
// 4. RxJS: subscribe() returns a Subscription
const sub = interval(1000).subscribe(tick)
sub.unsubscribe() // forget it: a timer lives for the app's whole lifetime
// 5. BroadcastChannel: observers in ANOTHER TAB, no server needed
const ch = new BroadcastChannel('cart')
ch.onmessage = () => refresh()
ch.close() // forget close = channel lives until reloadEventTarget, EventEmitter, effect(), Subscription: the same pattern. The APIs differ only in whether unsubscribe is a return value, a parameter, or a token.Wrap-up: when to use Observer, when to call directly
Observer buys you one thing: the producer doesn't need to know the consumers. It costs you three: you can't grep "who calls this function" (you have to debug at runtime), nothing guarantees anyone is listening, and event names are strings the compiler can't check.
Call directly when: there's one consumer, the consumer belongs to the producer, and you want a missing call to be caught at compile time. Use Observer when: consumers belong to other features, the number of consumers grows over time, or you need the producer to not import consumer code (the toast/document and SSR case in paragraph 3 is a real example).
// A bus survives when: events are a TYPE, payloads are strict, and leaks surface early.
type AppEvents = {
'cart:add': { sku: string, qty: number }
'cart:clear': undefined
'auth:logout': { reason: 'manual' | 'expired' }
}
// The bus holds NO state. A bus with state = a store with no name and no devtools.
function emit<K extends keyof AppEvents>(event: K, payload: AppEvents[K]) {
const set = handlers.get(event)
if (!set?.size) return
console.debug('[bus]', event, set.size) // shows you who's listening, in dev
for (const fn of [...set]) fn(payload)
}
function watchLeaks(event: keyof AppEvents, set: Set<unknown>) {
if (set.size > 10) console.warn('[bus]', event, set.size, 'listeners - forgot to unsubscribe?')
}MaxListenersExceededWarning: a leak should show up in minute 5, not minute 500.04 — Who talks to whom
Structure
- SubjectThe event source. Holds a `Map<event, Set<handler>>` and fires `emit(event, payload)`. Doesn't know the name of any observer.
- ObserverA handler that receives the payload. Subscribes while alive, unsubscribes when it dies.
- Event / PayloadA notification **that** something happened, with minimal data. Not "the entire state".
- ConcreteSubjectWhere the actual mutation happens (store, service, socket handler), and where the decision of *when* to emit is made: after commit.
- ClientThe user doing something; or a third feature (analytics, a plugin) that subscribes without the producer ever knowing.
Client (adds an item to the cart)
| await api.cart.add(sku) -> emit only after commit
v
+---------------------------------------------------------+
| Subject (cartBus - module scope, EXACTLY one instance) |
| handlers: Map<event, Set<handler>> |
| on(event, fn) -> off <- mandatory |
| emit(event, payload) -> for (fn of [...set]) fn(p) |
+----|-----------|-----------|-----------|-----------|----+
v v v v v
+---------+ +---------+ +---------+ +---------+ +---------+
| Badge | | MiniCart| |analytics| | socket | | plugin |
+---------+ +---------+ +---------+ +---------+ +---------+
on() on OFF()! on() on on() on on() on
mount unmount mount mount mount
-> off()
Set empty
Dependency direction: Subject <-- Observer (one way only)
Subject neither knows nor imports Observer. New consumer = new on(),
producer doesn't change a line. Missing off() = memory leak.05 — Edit freely, run it right here
Try it: an emitter with unsubscribe, a listener removing itself mid-loop
type Handler = (payload: string) => void
class Emitter {
private handlers = new Map<string, Set<Handler>>()
/** Returns the unsubscribe fn. Call it on unmount or leak. */
on(event: string, fn: Handler): () => void {
if (!this.handlers.has(event)) this.handlers.set(event, new Set())
const set = this.handlers.get(event)!
set.add(fn)
return () => { set.delete(fn) }
}
emit(event: string, payload: string) {
const set = this.handlers.get(event)
if (!set || set.size === 0) return console.log('emit ' + event + ' -> nobody listening')
console.log('emit ' + event + ' -> ' + set.size + ' listener(s)')
for (const fn of [...set]) fn(payload) // copy: a listener may remove itself mid-loop
}
}
const bus = new Emitter()
const log = (who: string): Handler => p => console.log(' ' + who + ' got ' + p)
const offBadge = bus.on('cart:add', log('ui-badge'))
const offOneShot = bus.on('cart:add', () => {
console.log(' one-shot ran, detaching itself')
offOneShot()
})
bus.on('cart:add', log('analytics'))
bus.emit('cart:add', 'sku-42')
console.log('--- component unmounted, badge unsubscribed ---')
offBadge()
bus.emit('cart:add', 'sku-99')
bus.emit('order:paid', 'x')emit cart:add -> 3 listener(s)
ui-badge got sku-42
one-shot ran, detaching itself
analytics got sku-42
--- component unmounted, badge unsubscribed ---
emit cart:add -> 1 listener(s)
analytics got sku-99
emit order:paid -> nobody listeningThe same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.
06 — Honest about the cost
When to use it, when not to
Use it when
- More than one consumer for the same change, and you're confident that number will keep growing: UI badge + tracking + cache invalidation + cross-tab sync.
- Consumers belong to a feature with no parent-child relationship to the producer: toasts, analytics, audit logs, plugins. The producer shouldn't import them (and in Nuxt, it mustn't).
- Plugin/integration systems: third parties register hooks without being allowed to edit the core. This is how VS Code, Vite, Nuxt hooks and Vitest reporters all work.
- DOM/browser events, WebSocket,
BroadcastChannel, postMessage: places where "who's listening" changes at runtime, not at build time. - Server-side domain events:
order.paid→ email, invoice, stock deduction. Three consumers in three modules; the module written later doesn't edit the one written earlier. - Reactivity: when state changes, many views must update. That's exactly what Vue/Signals do. Use them instead of writing your own.
Don't use it when
- Forgetting to unsubscribe. The component unmounts but the bus still holds its handler, the handler holds the component's closure → the component and its data are never GC'd. Symptoms: listeners run twice after hot reload, and memory only goes up. Node's
EventEmitterwarns at the 11th listener; that's a leak detector, so don't callsetMaxListeners()to silence it. - The bus becomes a magic-string dumpster:
emit("cart:add")in one file,on("cartAdd")in another, and the compiler catches nothing. The cure: events live in a single type, payloads are strictly typed per event, and the bus holds no state (a bus with state is a store with no name and no devtools). - Emitting mid-transaction: observers read an uncommitted DB/cache and see old data; or an observer
throws and rolls back a business operation that had succeeded. Emit after commit, and try/catch each observer. - Assuming notification order. Observers run in registration order, and registration order depends on mount order, which means it depends on timing. Any contract like "the badge must update before analytics reads it" is a bug waiting to happen.
- Losing
thiswhen passing a method:bus.on("x", this.fetch)→ the handler runs withthis === undefined. The bug only fires when the event fires, i.e. in production. Always arrow-bind or wrap it:() => this.fetch(). - Over-engineering: exactly one consumer, the producer always knows it, and the rules never change? Call it directly. Observer is only worth it when you genuinely need the producer to not know the consumer; the price is losing navigate-to-definition from the emitter to the receiver.
07 — You have met it already, just not by name
In real code
Node.js EventEmitter
on/once/emit/removeListener is Observer in its original form, running all through HTTP servers, streams and child_process. Two details worth knowing: once() is an Observer that unsubscribes itself, and MaxListenersExceededWarning (by default at 11 listeners for one event) exists precisely because leaks are this pattern's most common bug.
DOM EventTarget + AbortController
removeEventListener requires the exact reference to the handler, so an arrow function recreated on every render can never be removed: the number one source of frontend leaks. addEventListener(type, fn, { signal }) (modern browsers and Node 15.4+) solves it by letting one AbortController turn off a whole group of listeners.
Vue 3 reactivity: effect, watchEffect, effect scope
Inside Vue, every ref is a Subject and every effect is a Subscriber: the getter subscribes, the setter notifies. effect() returns a stop function; watch/watchEffect declared in setup() unsubscribe automatically when the scope is disposed. That's exactly onScopeDispose, and it's why Vue code leaks less than a hand-rolled bus.
RxJS and BroadcastChannel
RxJS packages Observer as Observable + Subscription, with unsubscribe(), and its own docs call forgetting to unsubscribe the number one mistake. BroadcastChannel takes Observer beyond the tab: each tab both publishes and subscribes, close() is unsubscribe, no server needed.
08 — Try it yourself
Exercise
Write an app-wide `useCartBus()` (module scope): **typed** events, `on()` returns an unsubscribe function, emit **copies the list** before looping, and `console.warn` fires when an event has more than 10 listeners. Then use it in `CartBadge.vue` so that **you don't need to write `onBeforeUnmount`**, and verify it with `bus.size("cart:add")` before/after mounting and unmounting 3 times.
Hints, open them one at a time:
- The Map must live at module scope (or in a Pinia store). If each component calling
useCartBus()gets a new Map, nobody hears anybody. on()returns() => { set.delete(fn) }. To auto-unsubscribe in a component:getCurrentScope()+onScopeDispose(off).- In
emit, loop over[...set]instead ofset; otherwise a handler that unsubscribes itself mid-loop will make the next handler get skipped.
The bus is a module-scope Map; on adds to the Set and returns a delete closure; emit copies the Set and then loops; it warns when set.size > 10. The useBusEvent composable attaches onScopeDispose(off), so components don't need lifecycle hooks. bus.size("cart:add") must return to its previous value after every mount/unmount cycle; that's the test that proves there's no leak.
// composables/cartBus.ts — ONE bus for the whole app
type Handler<T> = (payload: T) => void
export type CartEvents = { 'cart:add': { sku: string, qty: number }, 'cart:clear': undefined }
const handlers = new Map<keyof CartEvents, Set<Handler<any>>>()
function on<K extends keyof CartEvents>(event: K, fn: Handler<CartEvents[K]>): () => void {
const set = handlers.get(event) ?? new Set()
set.add(fn as Handler<any>)
handlers.set(event, set)
if (set.size > 10) console.warn('[cartBus]', event, set.size, 'listeners - forgot to unsubscribe?')
return () => { set.delete(fn as Handler<any>) } // on() ALWAYS comes with off()
}
function emit<K extends keyof CartEvents>(event: K, payload: CartEvents[K]) {
const set = handlers.get(event)
if (!set?.size) return
for (const fn of [...set]) (fn as Handler<CartEvents[K]>)(payload) // copy: off mid-loop is still safe
}
export const cartBus = { on, emit, size: (e: keyof CartEvents) => handlers.get(e)?.size ?? 0 }
// composables/useBusEvent.ts
export function useBusEvent<K extends keyof CartEvents>(event: K, fn: Handler<CartEvents[K]>) {
const off = cartBus.on(event, fn)
if (getCurrentScope()) onScopeDispose(off)
return off
}
// CartBadge.vue
useBusEvent('cart:add', refreshBadge) // auto-off, no onBeforeUnmount needed
// Verify there's no leak
for (let i = 0; i < 3; i++) {
const off = cartBus.on('cart:add', () => {})
off()
}
console.log('listeners left:', cartBus.size('cart:add')) // 009 — Read them in pairs to see the essence
Related patterns
- MediatorMediator uses Observer internally (colleagues emit, the mediator notifies) but it **has** state and rules, and it owns the logic. Plain Observer only relays notifications; it doesn't make decisions.
- CommandObserver announces "something happened" after the fact; Command packages "do this thing" into an object you can queue, retry, undo. Observer can't do undo; Command can.
- Chain of ResponsibilityA listener list looks like a chain, but a chain **stops** at the first handler that takes responsibility, while Observer calls **every** handler. Mixing them up is the source of the "only one observer wins" bug.
- MementoAfter `restore(memento)`, you need to emit an event so the UI and caches catch up with the new state; otherwise the data is right but the screen is still wrong.