Custom JavaScript "Trickle-down" events

I am looking at custom events in JavaScript.

According to MDN, using the CustomEvent constructor it is possible to make a "bubble up" event (default false):

https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#CustomEventInit

Example:

// add an appropriate event listener
obj.addEventListener("cat", function(e) { process(e.detail) });

// create and dispatch the event
var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}});
obj.dispatchEvent(event);

      

I tested it on jsfiddle:

http://jsfiddle.net/ppx4gcxe/

And the bubble functionality seems to work. But I would like my custom event to "leak", that is, even trigger listeners on the child elements; the opposite of bubbles up.

I vaguely remember how some default browser events were "trickled". This is supposedly one of those moments in the early days of the browser.

Anyway, is there a way to get this functionality in my custom events? Of course, any relatively simple and straightforward way. I don't want to write a function to traverse all children and manually trigger any listeners on them. Hopefully there is another way.

+3


source to share


1 answer


The behavior you are looking for is called event capturing

(opposite event bubbling

). You can include event capturing

by passing true

in as the third argument addEventListener

.

See: http://jsfiddle.net/zs1a6ywo/



NOTE. event capturing

not supported in IE 8 or below.

For more information see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener

+1


source







All Articles