Lightning Events – What? Why?

max-bender-iF5odYWB_nQ-unsplash

Communication between components

So you started off by building individual components which would be self-sufficient and won’t depend on any other component for its data or information. Lets say you created a simple form which would allow you to save data or when editing, retrieve data. That’s all good but more often that not, in real world scenarios, you would be required to build components which talk to each other. Say one of your components received a user input and you need to notify all the components which deal with the same record so that they won’t show stale data. As discussed in my post about lightning data services, if you’re using lds then you don’t need to worry about this because LDS takes care of notifying the dependent components automatically. But there are times when you won’t be using lds (LDS is yet to work for bulk records). How do you let your components talk to each other in such a situation? Enter lightning events!

If you want your components to talk to each other and share information, a lightning event is your go to option. Lightning events are quite similar to DOM events in JavaScript and i am pretty sure if you are coming from a web development background you would be well aware of them. Think of lightning events as data packets which contain certain piece of information and are passed from one component to another. This piece of information is usually an attribute and supports a variety of types starting from integer, string to object and almost everything in between. But how does it actually work? Can any component randomly talk to any other component without a protocol in place? Not really.

Publisher-Subscriber Model

Lightning components follow a Publisher-Subscriber model in order to communicate with each other via events. A publisher is a component that fires an event and a subscriber is a component that handles that event. Now both the publisher and subscriber need to let the framework know that they are gonna use this particular event for communicating. So the publisher needs to register the event in its markup before it can fire that event and a subscriber needs to register a handler to handle that particular event. This way the system knows who is gonna talk to whom and via which event. As is obvious, a publisher needs at least one subscriber and vice versa.

Leave a reply