Lightning events are one of the most interesting features provided by the lightning framework that will help you to couple the components that you build.
So, let’s say that you have built a plethora of components in your application. So how do you bring them all together. Of course, you are not going to nest them all together in one single component or application. You need a helping hand to help the components interact with each other. There might be a component who would do the processing based on certain input data and then there might be another component who would simply display the processed results. In this scenario, the component who would display the results can be re-used across the application, every time you decide to display something. The keyword to achieve this is through “Lightning events”.
Lightning events as the name says are events which are fired at one end and received at the other end. So, there are two aspects or rather two components involved here. One component fires an event and the other component handles the fired event.
In the illustration below, it can be seen that there is an event defined and when a defined event is fired by the Component1, it is being handled by the Component2. In this scenario, Component1 registers the event and Component2 handles the event. The beauty of using events lies in the fact that an event fired can be handled by any component as long as the component has the necessary event handlers. Thus an event fired by one component can be handled by n number of components present within the application. This helps two individual components which were not connected to each other shake hands with each other using events.
Below is the sample snippet of defining an event
<aura:event type="APPLICATION"> <aura:attribute name="result" type="String"/> </aura:event>
In the above snippet, the event has been defined an an application event. Please note that there two types of events i.e. Application events and Component events. We will discuss on the event types later. As of now let’s focus on understanding events. The above event also has an attribute defined to it of “String” type. You can have attributes of all types as you can have in components. When an event is fired, the attribute values can be passed by one component which can then be received by another component who wishes to handle/process the event.
In the next tutorial, we will look into navigating from one component to another component using events.