The main concept included in this recipe is how a grandson component fire events with data that are listened by a grandparent component, inside the same shadow root.
This is accomplished by using the event bubbling parameter bubbles = true.
<aside> đź’ˇ To understand how the event traverse his limits to arrive to the grandparent component, please review this section Event propagation.
</aside>
<aside>
đź“‚ Find the parent LWC in this folder: C:\\code\\lwc-recipes-force-app\\main\\default\\lwc\\eventBubbling\\eventBubbling.html
and the child nested component in this one: force-app\\main\\default\\lwc\\contactListItemBubbling\\contactListItemBubbling.js
</aside>
This LWC uses two main components, a parent and a child:
Id
of the contact and shows the contact details (as shown in the green rectangle).The c-contact-list-item-bubbling
 component dispatches a custom event called contactselect
 with bubbles: true
Also the default setting for composed
is false
.
handleSelect(event) {
// 1. Prevent default behavior of anchor tag click which is to navigate to the href url
event.preventDefault();
// 2. Create a custom event that bubbles. Read about event best practices at <http://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.events_best_practices>
const selectEvent = new CustomEvent('contactselect', {
bubbles: true
});
// 3. Fire the custom event
this.dispatchEvent(selectEvent);
}
When setting bubbles=true
and composed=false
the event bubbles up through the DOM, but doesn’t cross the shadow boundary, meaning it can be listened by family components inside the same shadow root.
The component hierarchy from child to grandparent is c-contact-list-item-bubbling -> lightning-layout-item -> c-event-bubbling
.
The event listener oncontactselect
 is declared in the parent lightning-layout-item
, and then handled in its grandparent, c-event-bubbling
.
<lightning-layout-item
class="wide"
oncontactselect={handleContactSelect}
>
handleContactSelect(event) {
this.selectedContact = event.target.contact;
}