When to use publish subscribe model in LWC?

When to use publish subscribe model in LWC?

Publish-Subscribe (pubsub) Model in LWC is used to make communication between two independent components. Please note that the Publish-Subscribe Model only works for components that are on the same page.

How does publish subscribe model work in Lightning?

In a publish-subscribe pattern, one component publishes an event, while others subscribe to receive and handle the event. It’s more or less like an Application event in aura where any component that subscribes to the event receives the event. Let’s say there are two independent components named myPublisher and mySubscriber.

How to reference a message channel in LWC?

To reference a message channel in LWC, import it from the new @salesforce/messageChannel scoped module. To use the LMS APIs, import the functions we’re interested in — publish, subscribe, unsubscribe, etc — from lightning/messageService.

What is the purpose of createmessagecontext in LWC?

The createMessageContext and releaseMessageContext functions are unique to LWC. The context object provides contextual information about the Lightning Web Components using LMS. In disconnectedCallback, our recommendation is to call releaseMessageContext, which will unregister any subscriptions associated with the context.

How is pub sub model used in Lightning?

Pub-Sub Model is essentially used to transfer the information between the component which are not in the same DOM hierarchy – which means that the components are not connected/ related in any way with each other using the parent-child relationship.

How to create a publish subscriber component in Lightning?

To establish the communication between two components we use a JavaScript library called pubsub, which acts as a helper js. First things first, create an LWC component and add only .js file named pubsub.js. following that create myPublisher and mySubscriber components.

How is event handling handled in Lightning web component?

In above parent component tesla, event raised by child component is handled just like any other events in Javascript (bubble event). In onmodelclick function , Tesla is also raising new event with same name – modelclick. That concludes, how communication happens between Parent child Lightning Web Components.