Conditionally propagate events in LWC

Let's look at how to conditionally propagate event in LWC when bubbles is true and composed is true.

Conditionally propagate events in LWC

There might be a scenario where we have to conditionally propagate (allow/stop) events from crossing the shadow dom (when bubbling is true and composed is true)

This is how the typical syntax looks like when we want to propagate the event out of the shadow dom using composed is true.

this.template.querySelector('.pDiv')
    .dispatchEvent(
    	new CustomEvent(
            "senddata", 
            {bubbles: true, composed: true}
        )
);

What if we want to conditionally control the event propagation out of shadow dom?

Something like this ...

These are the sequence of steps in which they will get executed.

  1. User clicks on the button
  2. We are getting the div count that's wrapping lightning-button.
  3. we are bubbling the events and also composed is true, meaning, the events are capable of crossing the shadow boundary.
  4. In `child.html` we have event handlers on all the div tags wrapping the `lightning-button` and Step3 is going to invoke the event listener `onsenddata`.
  5. The method `handleSendData` gets invoked.
  6. For every iteration we are reducing the div count(fetched in Step2) by 1.
  7. When this.allDivs === 1, it means it reached the top most div and we are stopping the event propagation.

Here is the code demonstrating the whole thing.

Also, I have blogged everything I know about Events in LWC. Give it a look if you are curious.