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
