Event - Dispatch (Starts Propagation / Bubble)

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();
}
function eventCallback(e) {
     console.log('-------------------');
     console.log("Target: "+getNodeId(e.target));
     console.log("Current Target: "+getNodeId(e.currentTarget));
     console.log("Event Phase: "+e.eventPhase);
}
let eventName = "myEvent";
  • Add two listeners on document and body that executes the callback for this event
document.addEventListener(eventName , eventCallback, {capture: true})
document.body.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:

Documentation / Reference


Powered by ComboStrap