About
Dispatching an event means to follow the steps that propagate the event through the tree.
Firing an event is just starting the propagation (dispatch) process.
Demo: explicit dispatch with the dispatchEvent function
- The HTML code. We will execute an event against the world span.
<p>Hello <span id="world">world</span>!</p>
- Utility function to print the node id
function getNodeId(node){
let nodeId = node.nodeName;
if ("id" in node){
nodeId += "#"+node.id;
}
return nodeId.toLowerCase();
}
- A callback function that will give as listener parameter to be executed when the event is dispatched
function eventCallback(e) {
console.log('-------------------');
console.log("Target: "+getNodeId(e.target));
console.log("Current Target: "+getNodeId(e.currentTarget));
console.log("Event Phase: "+e.eventPhase);
}
- The custom event type (ie event name)
let eventName = "myEvent";
- Add the listeners on document, body and element that executes the callback for this event
document.addEventListener(eventName , eventCallback, {capture: true});
document.body.addEventListener(eventName , eventCallback);
document.getElementById("world").addEventListener(eventName , eventCallback);
- Create the event and dispatch it against the span world element
var myEvent = new Event(eventName, {bubbles:true});
document.getElementById("world").dispatchEvent(myEvent);
- Result: