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
