问题
I'm confused with the script below:
var event = new Event('shazam');
document.body.addEventListener('shazam',function(){
alert('body');
});
document.addEventListener('shazam',function(){
alert('document');
});
window.addEventListener('shazam',function(){
alert('window');
});
document.body.dispatchEvent(event);
When I run this script on my browser, I just get the alert('body'); event. but if i set the capturing parameter of addEventListener (the third optional parameter) to true, all the alerts captured in order they should.
Why the shazam event doesn't bubble up ?
回答1:
You need to set the bubbles
property to true, and you have to do this during the construction:
var event = new Event('shazam', { bubbles: true });
or the old way with initEvent
, passing true as the second argument to allow bubble:
event.initEvent('shazam', true);
MDN Doc
来源:https://stackoverflow.com/questions/23048322/why-firing-a-defined-event-with-dispatchevent-doesnt-obey-the-bubbling-behavior