Event Communication between Lightning Web Components

Lightning Web Component Event Handling – Pub Sub

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 !!!

Posted

in

by


Related Posts

Comments

One response to “Lightning Web Component Event Handling – Pub Sub”

  1. sourabh lakhera Avatar
    sourabh lakhera

    Got the error

    === Deploy Errors
    PROJECT PATH ERRORS
    ─────────────────────────────────────── ─────────────────────────────────────────────
    force-app\main\default\lwc\main\main.js [Line: 5, Col: 7] LWC1517: Invalid LWC import

Leave a Reply

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

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading