liveBook · Manning

dispatchEvent

As explained in Vanilla Web

dispatchEvent is a DOM API method that synchronously dispatches an event to an object and its event listeners.

Use dispatchEvent() to send an event from a DOM object to its listeners. For custom events, pair it with CustomEvent to provide a name and optional detail payload. The event can bubble through the DOM or cross a shadow boundary when configured to do so. section 7.11 section 6.2.13

This provides a small contract between a component and its consumers: the component dispatches an event when something changes, and consumers listen with addEventListener(). Document the event name and payload so integrations know what to expect. Avoid using global DOM objects as an event bus for too many events, which can become difficult to manage. section 7.11 section 6.2.13

<script type="module" src="star-rating.js"></script>

<p>Flight rating: <star-rating value="4"></star-rating></p> #1
<p>Hotel rating:  <star-rating value="2"></star-rating></p> #1
<p>Restaurant rating (editable):
    <star-rating editable id="restaurant-rating"></star-rating> #2
</p>

<script>
document.getElementById("restaurant-rating").addEventListener("change", e => {
    console.log(`New rating: ${e.detail.value}`);  #3

})
</script>

A consumer listens for a star-rating change and reads the new value from the event’s detail payload. section 7.11

How Vanilla Web covers it

How deep it goes
Explains custom event names, detail payloads, and propagation options, but does not detail dispatchEvent internals.
Examples
Uses an editable star rating to emit changes and a cart event to carry item details.
What you can do after
Apply CustomEvent and dispatchEvent to publish changes, then consume their payloads with addEventListener.
How it connects
Connects CustomEvent with addEventListener, event delegation, and shadow DOM propagation.

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.