LWC Publish Subscriber

Publish Subscriber model in LWC 

The publisher-subscriber model or Pub/Sub model will help us establish a communication between the components which are not in the same DOM hierarchy. 

Is it too technical?  I will try to explain simply. If the components are not related to one another in any way with each other using parent-child relationship then we can use the Pub / Sub model to establish a connection between two-components 

What is Pub - Sub Model?

We are seeing pub sub-model in our daily life. Nowadays everyone using Whatsapp. In one or another way you will be part of at least one of whats app group. If you are broadcasting any message in Whatsapp to a group you will be the publisher and people who listen to your messages are subscribers. 

The pub sub-model is similar to the application event in Aura. 




 








In the above diagram, the publisher publishes messages via Pub/Sub Channels and is consumed by the various subscribers.

How to user Pub- Submodel in LWC 

Step 1: 

Download the pub sub-file  from here

Step 2: create the publisher component

<template>
    <lightning-card>
        
        <lightning-input class="slds-p-around_medium" label="Enter Text to Send: "
 value={strText} 
            onchange={handleTextChange}></lightning-input>
        <br/>
        <lightning-button label="Broadcast Message" onclick={sendMessage}>
</lightning-button>
       
    </lightning-card>
</template>

import { LightningElement,wire } from 'lwc';

import { fireEvent  } from 'c/pubsub';
import{CurrentPageReferencefrom 'lightning/navigation';

export default class PublisherCmp extends LightningElement {

   
    @wire(CurrentPageReferencepageRef;

     txtInput;
     broadcastmessage;
    handleTextChange(event) {
        this.txtInput = event.target.value;
    }

    sendMessage(event) {
        
        fireEvent(this.pageRef"sendmessage"this.txtInput);
        
    }

   
}


If we closely look at the publisher component, you can see in the js file, imported the Pub/sub module.
Then override the fireEvent method from the pub submodule. This firevent publishes message to subscribers.

Step 3: Build Subscriber component or Components 

<template>
    <lightning-card> 
        <p> I am Subscriber 1</p>
       
        <p class="slds-p-around_medium" style="font-size:10px">
            Recieved Message from Broadcaster: {broadcastmessage}
        </p>

       
    </lightning-card>
</template>

import { LightningElement,wire } from 'lwc';
import { registerListenerunregisterAllListeners } from 'c/pubsub';
import { CurrentPageReference } from 'lightning/navigation';

export default class Subscriber1 extends LightningElement {

   broadcastmessage;
    @wire(CurrentPageReferencepageRef;
    connectedCallback(){
        registerListener('sendmessage'this.callBackMethodthis);
    }

    callBackMethod(payload){
        this.broadcastmessage = payload;
    }

    disconnectedCallback(){
        unregisterAllListeners(this);
    }

    
}


If you closely look at the above subscriber component js file, We need to register the listener in connectedCallback(). This method executed when the component is rendered on DOM.
We have to pass event name, callback method, and "this" reference to registerListener()

Callbackmethod sets the payload sent by the publisher.

We will un-register listener in disconnectedCallback() as it will run once the component is removed from the DOM. 


NOTE: Always keep in mind PUB SUB model will work only on those components which are kept on the same page.







Comments

Post a Comment

Popular posts from this blog

Vlocity Learning..