Lightning Web Component Event Handling – Pub Sub

Author posted by Jitendra on Posted on under category Categories Salesforce and tagged as Tags , with Leave a comment on Lightning Web Component Event Handling – Pub Sub

How to handle events in Lightning Web Components between nested and non nested Components

Event Communication between Lightning Web Components

It is very common to come across use case of communicating between Lightning Web Components.

If you are not interested on code explanation and directly want to jump on live demo , check this playground.

Communicate between Nested Lightning Web Components

This is one of most simplest and common use case, where parent LWC wants to react on event produced by child LWC.

In above image, Model 3 is child (nested component) of Tesla.

In above, Model 3 component, custom event modelclick is raised using class CustomEvent.

Lets, see how Parent Component Tesla is defined.

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.

Lightning Web Component Event handling – Pub Sub Library

In above image, if we want Tesla event to be handled by Honda Component, traditional bubble based event handling will not work.

You can either use Salesforce library of Pub Sub, or Simple Library produced by Vishnu.

I’m going to use library created by Vishnu. Below is Javascript code for pub-sub library

Now, we have added above javascript as part of LWC, lets create a Lightning Web Component named Vehicle which will fire pub-sub event.

Note, how pubsub js is imported on line 2 of Vehicle.js. On line 7, we are firing event using pub-sub library.

Lets create a Lightning Web Component which will handle event generated by pub sub library.

As seen in above code, register method is used to handle event. Also note, how unique event identifier is used to fire and register event.

Feel free to comment and share your feedback. Happy coding !!!

Related posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.