Communication between unrelated components using LMS in salesforce
LMS is a publish and subscribe service that facilitates communication between Lightning web components, Aura components, and Visualforce pages.
<?xml version="1.0" encoding="UTF-8" ?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>CountUpdated</masterLabel>
<isExposed>true</isExposed>
<description>Message Channel to pass Count updates</description>
<lightningMessageFields>
<fieldName>operator</fieldName>
<description>This is the operator type of the manipulation</description>
</lightningMessageFields>
<lightningMessageFields>
<fieldName>constant</fieldName>
<description>This is the number for the manipulation</description>
</lightningMessageFields>
</LightningMessageChannel>
Step2: Create the Publisher Component
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import COUNT_UPDATED_CHANNEL from '@salesforce/messageChannel/Count_Updated__c';
export default class RemoteControl extends LightningElement {
@wire(MessageContext)
messageContext;
handleIncrement() {
// this.counter++;
const payload = {
operator: 'add',
constant: 1
};
publish(this.messageContext, COUNT_UPDATED_CHANNEL, payload);
}
}
Step3: Create the Subscriber Component
import { LightningElement, wire } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import COUNT_UPDATED_CHANNEL from '@salesforce/messageChannel/Count_Updated__c';
export default class Counts extends LightningElement {
subscription = null;
priorCount = 0;
counter = 0;
@wire(MessageContext)
messageContext;
subscribeToMessageChannel() {
this.subscription = subscribe(
this.messageContext,
COUNT_UPDATED_CHANNEL,
(message) => this.handleMessage(message)
);
}
handleMessage(message) {
this.priorCount = this.counter;
if(message.operator == 'add') {
this.counter += message.constant;
}else if(message.operator == 'subtract') {
this.counter -= message.constant;
} else {
this.counter *= message.constant;
}
}
connectedCallback() {
this.subscribeToMessageChannel();
}
}
Comments
Post a Comment