Skip to curriculum
Jump to the editor

17.11. Dispatch and listen for a custom event

Easy
Topics
15–25 min

On a shop page, the product cards, the cart badge in the header and an analytics script all care when something is added to the cart. If the card calls the badge and the analytics directly, every part has to know about every other. A custom event decouples them: the card announces cart:add from its button, the event bubbles up the page, and anything that cares listens for it, and can even veto it, for example when an item is sold out.

Write three functions in cart.js.

Signature

JAVASCRIPT
announceAddToCart(source, item)  // returns true, or false when a listener cancelled the event
onAddToCart(target, handler)     // returns a stop function
cartCounter(root, output)        // returns a stop function
  • item: a plain object such as { sku: "nb-1", quantity: 2 }.
  • handler(detail, event): called for each cart:add event that reaches target.

Requirements

  1. announceAddToCart dispatches a CustomEvent named "cart:add" from source, so event.target is source.
  2. Its detail has the item's fields, but is a frozen copy: not the caller's object, and no listener can change it.
  3. The event bubbles (a listener on document hears it), crosses shadow DOM boundaries (a listener outside a shadow root hears it), and can be cancelled.
  4. Listeners run during the call, before announceAddToCart returns. It returns false when a listener called preventDefault, and true otherwise.
  5. A listener that throws does not stop the other listeners or the call.
  6. onAddToCart calls handler(detail, event) for every cart:add that reaches target, and for nothing else. Its stop function removes only that handler (calling it twice is harmless).
  7. cartCounter sets output's text to "0", then to the running total of quantities of the cart:add events reaching root. An item without quantity counts as 1. Events already cancelled when they reach root are not counted.
  8. Each counter keeps its own total; after its stop function is called, it no longer changes.

Examples

JAVASCRIPT
cartCounter(document, badge);                      // badge shows "0"

onAddToCart(shop, (detail, event) => {
  if (soldOut.has(detail.sku)) event.preventDefault();
});

announceAddToCart(button, { sku: "nb-1", quantity: 2 }); // true;  badge shows "2"
announceAddToCart(button, { sku: "gone-1" });            // false; badge still "2"
JAVASCRIPT
onAddToCart(document, (detail) => {
  detail.quantity = 100; // no effect: detail is frozen (a TypeError in strict mode)
});

Environment

  • Plain JavaScript in a browser page; the tests call the three global functions on elements they build, and also dispatch cart:add events themselves.
  • CustomEvent, dispatchEvent and addEventListener are all you need. Deep freezing nested objects in item is out of scope.

Hints

  1. Custom events are created with options that are all off by default. Which three does this event need?
  2. What does dispatchEvent return?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…