If we remember the Aura framework, to communicate between two unknown components we used the Application event. There is no such event in lwc instead an alternate is pubsub module.
copy the pubsub code from the below link and create a lwc service component with the name lwc.
https://github.com/trailheadapps/lwc-recipes/blob/master/force-app/main/default/lwc/pubsub/pubsub.js
From the above module, keep a special eye on registerListener,fireEvent and unregisterListener functions.
In the publisher component we use fireEvent and from the subscriber component, we use registerListener and unregisterListener. Both publisher and subscriber share these functions and hence we are calling it as pubsub module.
Below is the simple and easy code to understand this concept.
publishercmp.html
publishercmp.js
subscriber.html
subscriber.js
Here is the output after clicking the button in the publisher component.
Thanks.
copy the pubsub code from the below link and create a lwc service component with the name lwc.
https://github.com/trailheadapps/lwc-recipes/blob/master/force-app/main/default/lwc/pubsub/pubsub.js
From the above module, keep a special eye on registerListener,fireEvent and unregisterListener functions.
export {
registerListener,
unregisterListener,
unregisterAllListeners,
fireEvent
};
In the publisher component we use fireEvent and from the subscriber component, we use registerListener and unregisterListener. Both publisher and subscriber share these functions and hence we are calling it as pubsub module.
Below is the simple and easy code to understand this concept.
publishercmp.html
<template>
<lightning-card title="I'm a publisher">
<lightning-layout>
<lightning-layout-item padding="around-small">
<lightning-button label="Publisher" onclick={fireevent}></lightning-button>
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>
publishercmp.js
import { LightningElement, wire } from 'lwc';
import {fireEvent} from 'c/pubsub';
import { CurrentPageReference } from 'lightning/navigation';
export default class MyPublisher extends LightningElement {
@wire(CurrentPageReference) pageRef;
fireevent(){
fireEvent(this.pageRef, "supplyme","from publisher");
}
}
subscriber.html
<template>
<lightning-card title="I'm a Subscriber">
<lightning-layout>
<lightning-layout-item>
{datafrompub}
</lightning-layout-item>
</lightning-layout>
</lightning-card>
</template>
subscriber.js
import { LightningElement, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
import {registerListener,unregisterAllListeners} from 'c/pubsub';
export default class MySubscriber extends LightningElement {
@wire(CurrentPageReference) pageRef;
datafrompub;
connectedCallback(){ registerListener("details",this.getdata,this);}
disconnectedCallback(){ unregisterAllListeners(this);}
getdata(pubdata){
this.datafrompub=pubdata;
}
}
Here is the output after clicking the button in the publisher component.
Thanks.