6

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 element's handler is not invoked. See https://jsfiddle.net/mvjh7700/

Is there a way to invoke the handler without dispatching the event directly on the child (or its descendants)? In my real use case, all sorts of elements (that are descendants, not direct children) listen to the build event, and I don't know exactly which (and don't wish to mark them with a class).

Alternatively, for my use case, it would be OK if I could find all the elements that have handlers on 'build', then I can invoke the event on each. But still, I would like to know the answer to the original question

IttayD
  • 28,271
  • 28
  • 124
  • 178

1 Answers1

-1

Here you go a working example. 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);
Stanimir Dimitrov
  • 1,872
  • 2
  • 20
  • 25
  • Fixed the code. Enjoy! The problem was that the custom event was still attached at the parent element. – Stanimir Dimitrov Jul 03 '15 at 16:29
  • 5
    This isn't what I asked. You dispatch the event on childElement, which means it is the target. Like I wrote, I have several children and it is hard to find which I need to trigger on. Besides, with your example, I can just call 'doSomething' on the child element directly. The point of events is to promote loose coupling. – IttayD Jul 03 '15 at 19:06