I was trying to implement event bubbling based on what the documentation says. For the scenario, where we mark bubbles as true and dispatch events to the element for the template where the event occurred( child component in our scenario).
As per documentation:
// myComponent.js
this.template.querySelector('div')
.dispatchEvent(
new CustomEvent('notify', { bubbles: true })
);
It says: The event must be handled in myComponent.js. Handlers in the containing component don’t execute because the event doesn’t cross the shadow boundary.
Now, below is my code :
Child Component: HTML:
<template>
<div class="whiteBg" onpress={outerHandler}>
<h1>Child Component</h1>
<button class="slds-button slds-button_brand" onclick={handleClick}>Click Me!! </button>
</div>
</template>
JS:
import { LightningElement } from 'lwc';
export default class BubblesTrue extends LightningElement {
handleClick(){
// eslint-disable-next-line no-console
console.log('handleClick');
const evt = new CustomEvent('press',{bubbles : true});
this.template.querySelector('div').dispatchEvent(evt);
}
outerHandler(){
// eslint-disable-next-line no-console
console.log('outerHandler Child');
}
}
Parent Component: HTML:
<template>
<lightning-card title="Parent Component - Bubbles!!">
<div >
<p>This is Parent Component's template</p>
</div>
<div onpress={outerHandler}>
<c-bubbles-true onpress={innerHandler}></c-bubbles-true>
</div>
</lightning-card>
</template>
JS:
import { LightningElement } from 'lwc';
export default class ParentBubblesTrue extends LightningElement {
innerHandler(){
// eslint-disable-next-line no-console
console.log('Inner Handler');
}
outerHandler(){
// eslint-disable-next-line no-console
console.log('Outer Handler')
}
}
Output:
Now, that I'm using this.template and not this.dispatchEvent, I'm not sure why the parent's handler is getting called? Documentation says that if we use it this way - the shadow boundary won't be passed. Can someone please help me understand this?