Introduction

The main concept included in this recipe is creating a message channel, importing that channel and publishing a message in it.

<aside> 💡 If you are not familiar with Lightning Message Service, review this section: Introduction before digging into this LWC.

</aside>

<aside> 📂 Find the channel definition here: force-app\\main\\default\\messageChannels\\Record_Selected.messageChannel-meta.xml Find the channel publisher here: force-app\\main\\default\\lwc\\lmsPublisherWebComponent Find the child component here: force-app\\main\\default\\lwc\\contactListItemBubbling

</aside>

Publisher component

Defining a message channel

To create the structure of a channel, an XML in the force-app\\main\\default\\messageChannels\\ must be provided.

The key point is the name of the channel. The fields that will be part of the payload are informative, and no check will be enforced.

<?xml version="1.0" encoding="UTF-8" ?>
<LightningMessageChannel xmlns="<http://soap.sforce.com/2006/04/metadata>">
    <masterLabel>RecordSelected</masterLabel>
    <isExposed>true</isExposed>
    <description>Message Channel to pass a record Id</description>
    **<lightningMessageFields>
        <fieldName>recordId</fieldName>
        <description>This is the record Id that changed</description>
    </lightningMessageFields>
		<!-- Include as many lightningMessageFields as required, even
those will not be checked -->**
</LightningMessageChannel>

Importing the APIs and the message definition

In the publisher’s Javascript the features and the message definition itself must be imported:

...

// Import message service features required for publishing and the message channel
import { publish, MessageContext } from 'lightning/messageService';

//Import the message definition
import RECORD_SELECTED_CHANNEL from '@salesforce/messageChannel/Record_Selected__c';

Firing a Message

To fire a new message, 3 steps are required:

  1. Calling the @wire adapter to get the Message Context. This is required for the LWC to be aware of the message service engine.
  2. Create the payload with the values that we want to send in the event.
  3. Executing the publishfunction from the messageService module with the Message Context, the Message Channel identifier imported and the payload just created.
@wire(MessageContext)
messageContext;

// Respond to UI event by publishing message
handleContactSelect(event) {
    const payload = { recordId: event.target.contact.Id };

    publish(this.messageContext, RECORD_SELECTED_CHANNEL, payload);
}

Template file

In the template, there is almost no code referring to LMS. A handler named handleContactSelectis registered for the event contactselect that the child component fires.