Steven Lu
Steven Lu

Reputation: 43457

What stage of the capture/bubble cycle does a dispatched event start in?

Suppose I've got this layout

<body>
  <div class="A">
    <span class="B">span</span>
  </div>
<body>

I convert clicks everywhere to custom event and dispatch it on its original target, using a delegated non capturing handler:

document.addEventListener('click',function(e){ 
  e.target.dispatchEvent(new CustomEvent('custom'));
}, false);

I assign a capturing event listener to A:

div_class_A_element.addEventListener('custom',function(){ 
  console.log('captured custom on A'); 
}, true);

What happens when I click B? I need a play-by-play. Also please don't tell me to just jsfiddle it, I know I can do that, but what I want to know is what does the spec say it is supposed to do?

Here's my guess:

the document's delegated handler runs on B once the click event has gone all the way down from the document to B then returns all the way back to document. What happens now I don't know: It dispatches custom event on B: does the custom event start at B and start bubbling? If so, then A's capturing handler won't run (because capturing handlers don't catch during bubbling phase). Or will dispatched events operate exactly like others and do the entire capture phase by starting out at document?

Upvotes: 1

Views: 693

Answers (2)

MikeM
MikeM

Reputation: 27405

if there were events for each element in your scenario this demo shows the order of operations.

  1. .B click
  2. .A click
  3. body click
  4. document listener
  5. captured custom on A
  6. window click

the document listener does trigger the A div dispatch right away then bubbling continues (to window)

Upvotes: 0

bokonic
bokonic

Reputation: 1771

Dispatched events also go through a capture phase. According to the w3c dom level 3 spec:

Applications may dispatch event objects using the EventTarget.dispatchEvent() method, and implementations must dispatch event objects as if through this method. - source

That quote itself isn't much help, but the spec goes on to explain the event flow that dispatchEvent (and internal implementations) must follow:

  1. The capture phase
  2. The target phase
  3. The bubble phase

W3C: Event Flow

Capturing must take place (unless it is stopped by stopPropagation(). Bubbling can be skipped by setting Event.bubbles to false.

The chain of EventTargets from the top of the tree to the event's target is determined before the initial dispatch of the event. If modifications occur to the tree during event processing, event flow will proceed based on the initial state of the tree. - source

So in your example, the custom event handler on A would be called when you dispatch the event from B.

From the MDN (on dispatchEvent):

Dispatches an event into the event system. The event is subject to the same capturing and bubbling behavior as directly dispatched events. - source

Upvotes: 3

Related Questions