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

1

25

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 ?

Perzan answered 13/4, 2014 at 20:52 Comment(2)
Create a CustomEvent instead of Event and pass it true as the second parameter (the canBubble parameter)Determined
the property seems to not called 'canBubble', it is 'bubbles'.Perzan
L
45

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

Lahey answered 13/4, 2014 at 21:12 Comment(3)
Thank you for your brief response :)Perzan
But one question: why bubbling is by default disabled in Event Object.Perzan
It defaults to false as per dom.spec.whatwg.org/#interface-event (or, if you prefer, developer.mozilla.org/en-US/docs/Web/API/Event/Event ). I would guess this is to provide the option with the least potential side effects by default.Saeger

© 2022 - 2024 — McMap. All rights reserved.