[LWC] Publish-Subscribe Model in Lightning Web Components using PubSub Library | Communicate Between Two Components in LWC

 

Salesforce's Publish-Subscribe Model (Pub-Sub) is a communication pattern that enables seamless interaction between components without requiring a direct parent-child relationship. 

This model is implemented using the Lightning Message Service (LMS), which provides a standard way to exchange data between LWCs, Aura components, and even Visualforce pages. It allows for updates, communication across different trees in the DOM, and data sharing between components. 

The benefits of using Pub-Sub with LMS include decoupled components, cross-domain communication, and scalability. Best practices include using the Lightning Message Service, keeping message payload minimal, and unsubscribing from disconnected channels.

The easiest way to communicate between components that aren’t in the same DOM tree is to use Lightning message service (lightning/messageService). Consider using the publish-subscribe mechanism with the pubsub module only if you're working in containers that don't support Lightning Message Service. The pubsub module is no longer officially supported or actively maintained.

To implement Publish-Subscribe model in lwc using PubSub Library follow the below steps: 

Step 1: Download PubSub Library From here : Download Link 

Step 2: Deploy the library files: pubsub.js and pubsub.js-meta.xml.

Now, 

Create Two Components, pubSubA and pubSubB

 

In pubSubA,

import { CurrentPageReference } from 'lightning/navigation';

import { fireEvent } from 'c/pubsub';


Use Wire to get the current page reference

 @wire(CurrentPageReference)
 pageRef;

//on button click or some action use fireEvent to send the data

 handleClick(){
        fireEvent(this.pageRef, 'showMessage', {message: 'Hello World'});
 }

In pubSubB,

import { CurrentPageReference } from 'lightning/navigation';
import { registerListener, unregisterAllListeners } from 'c/pubsub';

Use Wire to get the current page reference

@wire(CurrentPageReference)
    pageRef;

Register to listen for the showMessage event
    connectedCallback() {
        registerListener('showMessage', this.handleEvent, this);
    }

Disconnect after the component is removed from DOM
    disconnectedCallback() {
        unregisterAllListeners(this);
    }

Create a handler to handle the event when its listened
    handleEvent(event){
        this.message = event.message;
    }

Example: send a message from component A to B using pubsub library:

After button click:

 

pubSubA:



pubSubB:


pubSubParent:


 Github: @AbhishekSinha7/PubSubLWC/PubSubLib

Comments