Why firing a defined event with dispatchEvent doesn't obey the bubbling behavior of events?

核能气质少年 提交于 2020-01-01 08:06:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!