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
