How can the parent fire the custom event to notify its children/siblings?
For example:
<div id="div1">
<div id="div2"></div>
</div>
div2 had addEventListener('customEvent2', doSth), and then div1 will fire a custom event (customEvnet2), but this will never trigger div2’s doSth function.
Sample code: http://jsfiddle.net/r4tcT/2/
The "div 1 trigger customEvent 2" button never works
so when a parent fire a custom event (dispatchEvent[IE9]/fireEvent[IE9-]/trigger[jQuery]), the children can not capture the event.
Is there any workaround?
The difference you are talking about is either between the ‘Capturing’ event model or the ‘Bubbling’ event model. jQuery’s trigger operates on the Bubble model probably because this is the more supported event model — mainly thanks to Internet Explorer. The Bubble model only travels backwards up through an elements parents… this is the reason why your events don’t trigger on
div2when fired fromdiv1, as it is always bubbling up and not down.I’ve not tried custom events before with native functions but most modern browsers allow for you to decide which type of model you use when you set the event listener:
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
Basically if you use
trueas the final argument the event listener should trigger in the Capture phase (which is when the event is travelling down the dom tree). If set to false the event will trigger in the bubbling phase which occurs when travelling back up the dom tree.This has been discussed here:
Event Capturing vs Event Bubbling
As I’ve said whether this will work for bespoke events I’m not sure. I am pretty certain you can not do this with jQuery (as of yet) probably due to the lack of support in older browsers.
Correction
It appears what I guessed at above doesn’t work. I thought as much due to the term ‘Capturing’ kind of makes you think about capturing user input — and when bespoke events are involved there is no way to define a new kind of user input. So with that in mind I put together this quick jQuery plugin… it’s only been roughly tested, but the logic should be sound – hope it’s useful: