Q. Different LWC Events. if a's child is b and b's child is c. how to communicate from c to a ? event communication from one application to other?
Events in Lightning web components are built on DOM Events, a collection of APIs and objects available in every browser.
EventTarget
interface, which allows them to dispatch events, listen for events, and handle events.- Use CustomEvent Constructor
- Pass any parameter/arguments in detail property.
- No uppercase letters
- No spaces
- Use underscores to separate words
2.1 To add an event listener to an element within the shadow boundary, use template.
this.template.addEventListener();
2.2 To add an event listener to an element that a template doesn’t own, call addEventListener directly. MarkUp from slot
this.addEventListener()
Now the Answer to the above question stands in Knowing how this event propagation takes place
- In LWC events propagate according to the same rules as DOM events.
- Uses only Bubble phase (Source - Parent - root),capture phase is not supported.
Event bubbles up through the DOM, crosses the shadow boundary, and continues bubbling up through the DOM to the document root.
Communication Across the DOM
The above part shows how events can be used to make child to parent communication, what if we want to make communication with the components not linked to each other in any way.
Two ways
1. Lightning Message Service
2. Using Pub Sub Model
Lightning Message Service
3 steps Process
- Create a Message Channel
- Publish from Component
- Subscribe from Component
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>CustomMessageChannel</masterLabel>
<isExposed>true</isExposed>
<description>Message Channel to pass a record Id</description>
<LightningMessageFields>import {publish, MessageContext } from 'lightning/messageService';
import Custom_Message_Channel_Channel from '@salesforce/messageChannel/Custom_Message_Channel__c';
handleContactSelect(event){
const payload = {recordId:event.target.contact.Id}
publish(this.messageContext,Custom_Message_Channel_Channel, payload)
}
//Pseudo code for subscriber
import {Subscribe, MessageContext } from 'lightning/messageService';
import Custom_Message_Channel_Channel from '@salesforce/messageChannel/Custom_Message_Channel__c';
subscription;
recordId
//will unscribe message channel during component destruction cycle
@wire(MessageContext)messagecontext;
//Encapsulate Logic for Subscribe
subscribeToMessageChannel(){
this.subscription = subscribe(
this.messageContext,
Custom_Message_Channel_Channel,
(message) => this.handleMessage(message)
);
}
handleMessage(message){
this.recordId =. message.recordId;
}
Pub Sub Model
PUBSUB was required before spring 20 , with the introduction of LMS
it is not required now , Although LMS is not supported in Communities
So we may require Pub Sub there only.
|
Comments
Post a Comment