简体   繁体   中英

Propagation of custom events

I expect my CustomEvent to be propagated from document to all the DOM elements. For some reason, it does not happen. What am I doing wrong?

<html>
<script>
function onLoad() {
  var myDiv = document.getElementById("myDiv");
  myDiv.addEventListener("myEvent",function(){alert("Yes!");});
  document.dispatchEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>

You have to dispatchEvent the event on the element you want the event 'triggered' on. It will then propagate down and back up the DOM

<html>
<script>
function onLoad() {
  var myDiv = document.getElementById("myDiv");
  myDiv.addEventListener("myEvent",function(){alert("Yes!");});
  myDiv.dispatchEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>

Try this one. Use document.querySelector and specify the events you want to track. Click the button or type some text in the text box

Going with the extreme. Events propagate down to the element they are dispatched on and back up... So in order to trigger an event on any and essentially all elements (since it is unknown which elements need the event) you can find the "ends" of all of the "branches" of the DOM and dispatch events to them.

function onLoad() {
  var myDiv = document.getElementById("myDiv");
  myDiv.addEventListener("myEvent", function() {
    alert("Yes!");
  });
  $(':not(:has(*))').each(function(i, el){
    el.dispatchEvent(new CustomEvent("myEvent", {
      detail: null,
      bubbles: true
    }));
  });
}

I am posting some solution, not really an answer. This will propagate a custom event to all the elements in the DOM.

<html>
<script>
document.dispatchCustomEvent = function(event) {
  function visit(elem,event) {
    elem.dispatchEvent(event);
    var child = elem.firstChild;
    while(child) {
      if(child.nodeType==1) visit(child,event);
      child = child.nextSibling;
    }
  }
  visit(document.documentElement,event);
}

function onLoad() {
  var myDiv = document.getElementById("myDiv");
  myDiv.addEventListener("myEvent",function(){alert("Yes!");});
  document.dispatchCustomEvent(new CustomEvent("myEvent",{detail:null}));
}
</script>
<body onload="onLoad()">
<div id="myDiv"></div>
</body>
</html>

By default Custom Events are not bubbled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM