Sub topic 1
Lightning Message Service for Components That Are Not Related
Prerequisites
Assume you know basic Lightning Web Components, JavaScript classes, @wire, lifecycle hooks, Salesforce DX project structure, and Lightning page placement.
The Problem: Components With No Shared Parent
LWC communication normally follows the component hierarchy. A child dispatches a custom event, and a parent handles it. A parent can also pass data to a child through a public property.
These patterns fail when two components have no shared parent. For example, a record list and a record detail component might appear in separate regions of a Lightning page. Neither component can directly dispatch an event to the other, and neither owns a property on the other.
What Lightning Message Service Is and Where It Works
Lightning Message Service (LMS) provides publish-subscribe communication. A publisher sends a message to a named channel. Subscribers on that channel receive the message without needing a parent-child relationship.
LMS works between Lightning Web Components, Aura components, and Visualforce pages on the same Lightning Experience page. The message channel defines the shared contract, while the publisher and subscribers decide what to do with each message.
Message Channels as the Shared Contract
A message channel is Salesforce metadata that names the channel and documents its fields. Treat it as an API contract: use stable field names and small, serializable values such as record IDs, strings, numbers, and booleans.
For example, recordId identifies the selected record:
<?xml version="1.0" encoding="UTF-8"?>
<LightningMessageChannel xmlns="http://soap.sforce.com/2006/04/metadata" fqn="RecordSelected">
<description>Published when a user selects a record.</description>
<isExposed>true</isExposed>
<lightningMessageFields>
<description>Id of the selected record</description>
<fieldName>recordId</fieldName>
</lightningMessageFields>
<masterLabel>Record Selected</masterLabel>
</LightningMessageChannel>Creating and Deploying a Message Channel
Save the file as force-app/main/default/messageChannels/RecordSelected.messageChannel-meta.xml. Deploy it with Salesforce CLI:
sf project deploy start \
--source-dir force-app/main/default/messageChannels/RecordSelected.messageChannel-meta.xmlAfter deployment, LWC code imports the channel by its metadata API name, RecordSelected__c. A common error is using the label instead of this API name.
Exercise
Why can’t a record list notify an unrelated record detail component with a normal custom event?
Show answer
Custom events move through the component hierarchy. Unrelated components need a shared service such as LMS.