liveBook · Manning

Event dispatch

As explained in Web Components in Action

Event dispatch is the DOM operation of delivering an event from a document or element to matching event listeners.

Event dispatch delivers an event from the document or an element to matching listeners. Create the listener first, then dispatch the event so the callback is ready. section 14.2

Dispatching a custom event

Create a CustomEvent with a name and detail data, then call document.dispatchEvent(event). A listener can read e.detail.message and e.detail.number. A timer can trigger dispatch and make the callback’s event-driven execution visible. section 14.2

Listing 14.4. Custom Event bubbling
<html>
<head>
   <title>Custom Event Bubbling</title>
   <script>
       document.addEventListener('myevent', function(e) {
           console.log('The message', e.detail.message, 'with number',
                        e.detail.number);
       });

       const event = new CustomEvent('myevent', {
           bubbles: true,                           #1
           detail: {
               message: 'hi',
               number: 5
           }
       });

       setTimeout( function() {
           document.getElementById('target')        #2
                       .dispatchEvent(event);
       }, 2000);
   </script>
</head>
<body>
   <div id="target"></div>                          #3
</body>
</html>

Compare dispatching from the document with dispatching from an element and enabling bubbles so ancestor listeners can receive the event. section 14.2

How Web Components in Action covers it

How deep it goes
Explains creation, listener ordering, detail data, timers, and bubbling, but stops short of broader event internals.
Examples
Demonstrates document dispatch, custom message and number data, delayed triggering, and element-based bubbling.
What you can do after
Apply it via DOM APIs to create, dispatch, listen for, and bubble custom events.
How it connects
Connects DOM events with event listeners, CustomEvent, event detail, and event bubbling.

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