What you'll learn: By the end of this lesson you will be able to tell an event from a command and name events as facts, decide what an event should carry, explain the difference between nested (synchronous) and queued delivery, keep one failing listener from breaking the others, stop a loop of modules that answer each other, and survive a duplicate delivery.
Think of a restaurant kitchen. A waiter can walk to the grill, the salad station and the till and tell each one what to do: that is a command, and the waiter must know every station. Or the waiter can call out "table 4 ordered" and let each station decide what that means for it: that is an event. The second way scales when a new station opens, but it has a price. Nobody can read the whole flow from one place, and if two stations keep calling out events in response to each other, the kitchen never goes quiet.
A front end has the same shape. A cart, a header badge, a toast area, analytics and a stock banner are modules that must react to the same happenings without importing each other. This lesson is about doing that with events inside one page. The lab is a small in-process bus with a product page wired to it. It models only the rules listed in it and is not a library.
The core idea
- An event is a fact that already happened; a command is a request. Name events in the past tense and let the receivers decide what to do.
- The decoupling has a cost: the rules are now yours. Who runs first, what happens when a listener throws, how deep a chain may go and what a duplicate does are all decisions that a direct call made for you.
- The flow is no longer in the code. Follow it with an envelope: an id, a source, and the id of the event that caused this one.
Three illustrations run through the lesson: a minimal example (one event and two listeners, in two delivery orders), a realistic example (a product page where adding to the cart updates a badge, a toast, a stock banner and analytics) and a failure example (two modules that answer each other forever).
The observer, pub/sub and mediator patterns, covered in the prerequisite lesson, are the base. Across a network the same ideas gain a transport that can lose messages: see Presence and Pub/Sub and Real-Time Data in React State.
Events and commands
Martin Fowler's article on event-driven systems separates four patterns that people call by one name: event notification, event-carried state transfer, event sourcing and CQRS. Two of them matter here. Event notification is a module announcing a change in its domain, generally without needing a response. Event-carried state transfer puts the changed data in the event so that receivers need not ask the sender. Event sourcing, where the log of events is the source of truth, is the subject of the lesson on undo, redo and event sourcing in the UI.
He also warns about two traps. A flow that runs across several notifications can be hard to see, because it "is not explicit in any program text". And a notification can turn into a "passive-aggressive command" when the sender expects the receiver to act: if you expect something, send a command and say so.
The same advice appears in the Redux style guide, which recommends treating actions as "describing events that occurred" rather than as setters. Its example is a single food/orderAdded event instead of two setters that compute counts in the client, and it gives the reason: the event approach is more flexible, because the receiver may decide, for example, to ignore the order.
| Command | Event | |
|---|---|---|
| Tense | Imperative: show-toast |
Past: cart.item-added |
| Who decides what happens | The sender | Each receiver |
| Number of receivers | Usually one | Zero or more |
| If nobody handles it | A bug | Fine |
What an event carries
Figure 1. Modules talk through a bus instead of importing each other
How to read this: the cart imports only the bus. Adding a fifth module means subscribing it, not editing the cart.
Two choices decide how an event feels to use. Notification only carries the identity ({ sku }), and each listener reads the cart to learn the count. State transfer also carries the new count ({ sku, qty, count }), so the badge needs no read and cannot see a different value than the one that caused the event. The lab's cart.item-added carries the count. The cost is a bigger payload that becomes a contract.
The browser has a built-in shape for this: a CustomEvent carries its data in a read-only detail property. For a record about an occurrence, CloudEvents requires an id, a source and a type, says that source plus id must be unique for each distinct event, and defines optional time and subject. The lab's envelope borrows the idea, not the format:
| Field | Purpose |
|---|---|
id, source |
Identify the event; the pair is what a duplicate check uses |
type |
What happened, in the past tense |
time |
From an injected clock in the lab, so tests are deterministic |
correlationId |
The id of the first event in the chain |
causationId |
The id of the event whose listener emitted this one |
depth |
How far down a chain the event is |
Delivery order: nested or queued
When a listener emits another event while handling one, the bus can deliver the new event at once, inside the listener, or after the current event has reached all of its listeners. MDN says the DOM's dispatchEvent() is synchronous: it invokes all applicable handlers before returning, unlike native events, which the browser queues as tasks. So an event dispatched inside a listener runs to completion inside it. The lab has both modes.
Figure 2. The same three listeners in two orders
How to read this: in the nested case second sees a only after third has seen b. In the queued case b waits its turn.
Expected output, captured from a real run (Node 26.13.1; section 1):
=== 1. One event, two listeners; the first one emits a second event
queued first sees a | second sees a | third sees b
sync first sees a | third sees b | second sees a
Neither is wrong. Nested delivery keeps a cause close to its effect, but it breaks a rule such as "second always sees a before anything that a causes". Queued delivery keeps that rule at the price of delay: an emit has not been handled when it returns.
Failing listeners, and following the chain
MDN also says that exceptions thrown by event handlers are reported as uncaught exceptions: the handlers run on a nested call stack and block the caller, but their exceptions do not propagate to it, so a try/catch around dispatchEvent() will not catch them. A bus of your own must make the same decision: the lab catches the error, records it with the event and listener, and keeps delivering. MDN also says a listener added while an event is being processed does not receive that event; the lab follows that rule and, as its own rule, skips a listener removed before its turn.
The realistic example: adding 4 of sku-7, with a stock limit of 3 and a broken toast module (a bug set up for the demonstration).
Expected output, captured from a real run (Node 26.13.1; sections 2 and 2b):
=== 2. Product page: add 4 of sku-7 to the cart (the toast module is broken)
emit e1 cart.item-added from cart
e1 cart.item-added -> header-badge
e1 cart.item-added -> toast
e1 cart.item-added -> stock-watcher
emit e2 cart.stock-low from stock-watcher after e1
e1 cart.item-added -> analytics
e2 cart.stock-low -> toast
e2 toast threw: toast container is not mounted
e2 cart.stock-low -> stock-banner
e2 cart.stock-low -> analytics
badge 4; toasts ["added sku-7"]; low-stock banner ["sku-7"]
analytics saw: cart.item-added, cart.stock-low
errors: toast on e2: toast container is not mounted
=== 2b. The envelopes, so a chain can be followed
e3 cart.item-added source=demo correlation=e3 cause=none depth=0
e4 cart.stock-low source=stock-watcher correlation=e3 cause=e3 depth=1
Read it in order. The stock watcher emitted e2 while handling e1, but e1 still reached analytics first because delivery is queued. The toast threw on e2, and the stock banner and analytics still ran. The chain is visible in the envelopes: e4 has cause=e3 and the same correlation, which is how a support engineer would later reconstruct what led to a toast.
Loops and duplicates
Because nobody sees the whole flow, two modules can answer each other. In the lab, a pricing module emits price.changed after every cart.item-added, and a gift promotion answers price.changed by adding a free item, which is another cart.item-added. Each event is valid on its own; the cycle is the bug. A guard on depth stops it: an event deeper than maxDepth is dropped and recorded.
A second hazard is delivery of the same event twice, for example by a retry. CloudEvents says consumers may treat events with the same source and id as duplicates. An idempotent listener remembers what it has seen and ignores a repeat.
Figure 3. The life of an event on the bus
How to read this: the two ways an event can end early are the depth guard and a listener's own duplicate check. A thrown error never ends delivery.
Expected output, captured from a real run (Node 26.13.1; sections 3 to 5):
=== 3. Two modules that answer each other, with maxDepth 4
emit e1 cart.item-added from cart
emit e2 price.changed from pricing after e1
emit e3 cart.item-added from gift-promo after e2
emit e4 price.changed from pricing after e3
emit e5 cart.item-added from gift-promo after e4
drop e6 price.changed (depth 5 is over 4)
pricing ran 3 times; dropped 1 event: e6 price.changed depth 5
=== 4. The same envelope delivered twice (a retry), with and without an idempotent handler
plain handler points after one add of 2 items: 40
idempotent points after one add of 2 items: 20
=== 5. A listener added during a delivery, and one removed before its turn
first tick: a c
second tick: a c added-by-a
The guard contained the bug and did not fix it: the chain stopped at depth 5. The loyalty counter shows what a duplicate does without protection: 40 points for one add of 2 items instead of 20. In section 5, added-by-a missed the first tick, b was removed before its turn and never ran, and on the second tick the listener added earlier did run.
Choosing
Figure 4. Event, command or direct call?
How to read this: an event that expects a reaction is a command in disguise. Say so and call it.
| Choice | Gain | Cost |
|---|---|---|
| Events between modules | New listeners without editing the sender | The flow is implicit; add ids and traces |
| State in the event | Listeners need no read | The payload becomes a contract |
| Queued delivery | A stable order | A delayed effect |
| Nested delivery | Cause and effect are close | A listener can see half-updated state |
| Depth guard | Loops are contained | It hides the bug unless you log the drop |
| Idempotent listener | Duplicates are harmless | A memory of seen ids, bounded |
Build it: an in-process bus with a product page
Goal. Run the bus in both delivery modes, see a broken listener contained, follow a causal chain, stop a loop and survive a duplicate.
Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no DOM, no timers, no network.
cd examples/frontend
pnpm install
cd labs/ui-event-bus
pnpm test # 19 tests
node src/demo.ts
Steps.
- Run the tests, then the demo.
- In section 1, compare the two lines and say which listener saw
alast in each. - In section 2, find the line where the toast threw, and list what still ran afterwards.
- In section 2b, follow
causefrome4back to the first event. - In section 3, count how many times pricing ran before the drop.
What the lab does not show. It is not the DOM's EventTarget and it makes its own rules for order, for removal during delivery and for depth. It does not model a network, several tabs, priorities or back-pressure, and nothing in it claims to match a framework or a broker.
Break it. In src/bus.ts, in deliver, delete !subscription.active || from the if. A listener removed earlier in the same delivery is still called, and the test "skips a handler that was removed before its turn" fails. Put it back.
In practice: the add-to-cart that broke analytics
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
On a product page, the cart code calls the badge, the toast and the analytics client directly. A change to the analytics client makes it throw on one browser, and add-to-cart then stops updating the badge there (illustrative).
Starting architecture
Figure 5. Starting point: the cart calls every consumer itself
How to read this: the cart imports every consumer and calls them in sequence. An exception in the first call means the others never run.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
Wrap each call in try/catch |
The throw is contained | The cart still imports all consumers | Every new consumer needs the same wrapper |
| A bus with isolated listeners | Decoupling and containment | Implicit flow, rules to define | Loops and duplicates |
| A bus plus a depth guard and envelopes | Containment and traceability | A little code and discipline | Hidden bugs if drops are not logged |
The decision
| Field | Decision record |
|---|---|
| Context | One failing consumer breaks the others, and the cart knows too many modules. |
| Decision | The cart emits cart.item-added with the new count on a queued bus. Listeners are isolated, errors are recorded, a depth limit stops loops, and money or points listeners are idempotent. |
| Consequences, good | A new consumer does not touch the cart, and a failing one does not stop the rest. |
| Consequences, bad | The order of effects is now a property of the bus, and the flow must be read from logs. |
| Revisit when | Modules need replies, or the flow needs a guaranteed order across several event types. |
Rollout and verification
- Move one consumer at a time, starting with analytics, and keep the direct calls for the others.
- Log every recorded error and every drop to the page's error reporting.
- Test the three failures: a throwing listener, a loop and a duplicate delivery.
The 2 a.m. failure
A new "free gift" promotion adds an item when the price changes, and the price module recalculates when an item is added. On a promotion day the tab freezes for some shoppers (illustrative). First three checks: (1) look in the error log for dropped events and read the causation chain; (2) check the depth of the last events before the freeze; (3) find the two sources that alternate. Mitigation: switch the promotion off with its flag. Follow-up: compute the gift in the cart as a pure rule instead of an event loop, and add a test that no chain is longer than a few events. Exercise 3 asks for it.
Architect's notes
- Name events as facts in the past tense, and give them a stable
typethat is part of the module's public contract. - Decide the delivery order on purpose and write it down.
- Never let a listener's error reach the emitter without deciding that it should.
- Log drops and errors, or the guards hide bugs.
- Make listeners that move money, points or inventory idempotent.
Common mistakes
- Events that are commands in disguise, where the sender expects a reaction.
- Two modules that answer each other with no depth guard.
- Assuming a nested listener runs after the others.
- Putting the whole store in every event, so the payload becomes an undocumented contract.
- Subscribing in a component without unsubscribing, so listeners pile up on every mount.
Key takeaways
- An event is a fact about the past; a command asks for something. Do not disguise one as the other.
- Decide what the event carries: only an identity, or the new state as well.
- Queued delivery gives a stable order; nested delivery keeps cause and effect close. The DOM's
dispatchEvent()is nested. - Isolate listeners, record errors, bound the depth of chains and make important listeners idempotent.
- Because the flow is implicit, carry a correlation id and a cause on every event.
Practice exercises
Exercise 1 — Starter (45 min): List five events on a product page in the past tense, and for each say what it must carry so that no listener has to read another module.
Exercise 2 — Intermediate (2 hours): Add a wildcard prefix such as cart.* to the lab's on. Write the tests for the order in which a prefix listener and an exact listener run.
Exercise 3 — Advanced (half day): Replace the gift loop with a pure function in the cart. Write the test that fails on the loop first, then show that no chain is longer than two events.
Related reading
In this course:
- Presence and Pub/Sub, the same ideas across a network that can lose messages.
- Real-Time Data in React State, putting pushed events into component state.
- Local vs Global State in the Front End, where state lives instead of travelling in events.
- Debouncing and Throttling, timing tools for noisy events.
Official documentation
- Martin Fowler: What do you mean by Event-Driven?, the four patterns and the cost of implicit flows.
- MDN: EventTarget.dispatchEvent() and addEventListener().
- MDN: CustomEvent.
- CloudEvents specification, the attributes of an event record.
- Redux style guide: model actions as events, not setters.