Development questions

What is Lightning Message Service (LMS) and how do you use it to communicate between components?

DevelopmentMedium

LMS lets components on the same Lightning page communicate regardless of DOM hierarchy, and works across LWC, Aura and Visualforce.

Steps:

  1. Create a Lightning Message Channel metadata file (MyChannel.messageChannel-meta.xml) defining fields.
  2. Publisher imports the channel and publish:
javascript
import { publish, MessageContext } from 'lightning/messageService';
import CHANNEL from '@salesforce/messageChannel/MyChannel__c';
@wire(MessageContext) messageContext;
publish(this.messageContext, CHANNEL, { recordId: this.id });
  1. Subscriber uses subscribe in connectedCallback and unsubscribe in disconnectedCallback.

It replaces the old pub-sub pattern and is the supported way to talk between unrelated components.

lwclmsmessaging