Lightning Message Service(LMS) in LWC

LWC introduced pubsub pattern for event communication between lwc components which are unrelated but on same lightning page. But now pubsub pattern are obsolete and a new mechanism has been introduced which is LMS (Lightning Message Service). This message service allows you to communicate between Visualforce page and Lightning component including LWC and Aura component.

In LMS we create a messageChannel, where we define variable or fields. These variable can be used to store data/information during event communication.

Follow below steps to enable lwc component to communicate to other lwc component.

Step 1 : Create a folder "messageChannels" under force-app\main\default and create a file

"messagingChannel.messageChannel-meta.xml". I have given name "messagingChannel", you can give any other name of this file.

Step 2 : now fire the event as below. For this you need to import publish and MessageContext element from lightning message service and import messagingChannel we have created. in sampleFunction(), we have publish 'sampleEventFired' to the lightning message service.

Step 3 : After publishing we need to capture this event in different lightning web component. for this import subscribe and MessageContext from lightning message service and import the messagingChannel we have created.

let me know if you are able to implement above steps.

©2019 by SFDC Blogs.