Publisher Subscriber (pubsub) Pattern in Lightning Web Components

Updated: Jan 17, 2020

To communicate between components that aren’t in the same DOM tree, use a singleton library that follows the publish-subscribe pattern.

The Aura Component uses publisher subscriber (pubsub) method to communicate between components. This is also true for lightning web components, but LWC uses different mechanism to achieve this.

In LWC, we don't have separate event components. We fire and handle event programatically in lwc.

Let's see how pubsub method can be used to fire and handle event in totally unrelated lwc components.

1st Step :- Create a lwc in VScode

name - pubsub

You can remove html file from this, because it is not required.

Copy the code from github for pubsub.js and pubsub.js-meta.xml from below place

2nd Step - Create a component, that will fire event.