liveBook · Manning

CustomEvent

As explained in Vanilla Web

A script-created DOM event that can carry application-specific data and participate in event propagation.

When one part of an interface needs to announce a change without depending directly on its listeners, dispatch a CustomEvent from a DOM node. Choose an event name, put application-specific data in detail, and document both as a small contract. Listeners use addEventListener and receive an event with familiar properties such as type and target, alongside detail. section 6.2.13

const bus = document.body;

bus.addEventListener("cart:add", (e) => {
  console.log("Add to cart:", e.detail);
});

bus.dispatchEvent(new CustomEvent("cart:add", {
  detail: { id: "SKU-123", qty: 1 },
  bubbles: true,
  composed: true
}));

A shared DOM node carries a cart:add event. Its listener reads the item data from detail; bubbles and composed are explicitly enabled. section 6.2.13

A custom element can dispatch an event when its internal state changes. Consumers listen on the element rather than reaching into its implementation. Set bubbles: true when the event should travel up the DOM tree, and composed: true when it should cross a shadow boundary. Custom events participate in the DOM event model; they are not React-style onValueChanged attributes on a custom tag. section 7.11 section 7.13

Editable rating

An editable rating element handles a star click, updates its value, and dispatches a change event with detail: { value: newValue }. A consumer attaches addEventListener("change", …) to the element and reads e.detail.value. Keyboard selection is a further accessibility consideration. section 7.11

A common ancestor or dedicated element can serve as a simple event bus, but avoid scattering too many custom events across global DOM objects: the resulting contracts become harder to manage. Keep event names and detail shapes explicit. Custom events also provide component-to-host communication when custom elements are used from frameworks. section 6.2.13 section 9.8.1

How Vanilla Web covers it

How deep it goes
Shows construction, dispatch, payload access, bubbling, and shadow-boundary configuration; does not descend into event-system internals.
Examples
Uses a cart:add payload on a shared node and an editable rating element that emits its new value.
What it assumes
Assumes basic familiarity with DOM nodes and event listeners while demonstrating how to create and consume a custom event.
What you can do after
Build it from scratch: dispatch a named event with detail and let consumers listen without coupling to the producer.
How it connects
Connects DOM event propagation, event delegation, shadow DOM, custom elements, and the event bus pattern.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.