Is there a way to call child handlers?

Given the code:

var event = new Event('build');

// Listen for the event.
elem.children[0].addEventListener('build', function (e) { ... }, false);

// Dispatch the event.
elem.dispatchEvent(event);

      

The child handler is not called. See https://jsfiddle.net/mvjh7700/

Is there a way to call the handler without dispatching the event directly to the child (or its descendants)? In my real use case, all sorts of elements (descendants, not direct children) are listening on the event build

and I don't know exactly what (and don't want to classify them).

Alternatively, for my use case, it would be nice if I can find all the elements that have handlers in 'build', then I can fire an event for each one. But still, I would like to know the answer to the original question

+3


source to share


2 answers


You will find a working example here. https://jsfiddle.net/mvjh7700/4/



<div id="target">
    <div id="child">hi</div>
</div>

var theParent = document.getElementById('target');
var childElement = theParent.children[0];

childElement.addEventListener('build', doSomething, false);

function doSomething(e) {
    var clickedItem = e.target.id;
    alert("Hello " + clickedItem);
}
var myEvent = new CustomEvent("build", {
    detail: {
        username: "stanimir"
    },
});

childElement.dispatchEvent(myEvent);

      

0


source


If you are using bubble

you can reverse your logic. Instead of adding eventListeners

in children

, you should send them and put the listener at the top of your DOM. This way you will have the same result, but with fewer listeners and more dispatchers. See an example, in case you want a common handler, just put the handler on the window and listen for all dispatch events:

var event = new Event('build', {bubbles: true});
var elem = document.getElementById('target')

window.addEventListener('build', function (e) { console.log(e.target) }, true);
elem.addEventListener('build', function (e) { console.log(e.target) }, true);

elem.children[0].dispatchEvent(event);

      



https://jsfiddle.net/4fnqby8s/4/

0


source







All Articles