Tuesday, July 17, 2018

Events in Salesforce Lightning - Introduction


What is an Event ? Generally an event is a thing that happens or takes place. When we talk about events in JavaScript, they are simply a thing that happen to HTML element. There can be various types of events when we talk about HTML. For example:-
  1. Web page loaded is an event
  2. Clicking of a button is an event
  3. Changing text in an input field is also an event

So, we can say that any kind of interaction that happen in a webpage either automatically or by human interaction is an event. Now talking about the Salesforce Events, basically there are 2 types of events in Salesforce:- 
  1. Component Events
  2. Application Events

Component Events

A component event is an event that is fired by a lightning component. A component event can either be handled by the component itself or it can be handled by any other component which is present in the hierarchy that receives the event.

Application Events

An application event is generally like a broadcast message. Like if you send a broadcast, then all the receivers that are configured to accept that broadcast message receive that message. Similarly, an application event is fired by a component and all the other components that have the handler defined to receive that event are notified when the event is fired. Application Events are not bound by any hierarchy or relationship.

Salesforce recommends to use component events whenever possible as they have a limited scope. Application Events are handled at the application level and can be used to communicate between different components that are not related to each other.

Usually, we deal with the events that are fired when the user interacts with the browser. Such events are known as browser events. There are another type of events that are called system events that automatically trigger during the component life cycle. If you remember the Salesforce Lightning Tutorial Series, in first video, we added an init handler in our lightning component as shown below:-

<aura:handler name="init" action="{!c.getContactsList}" value="{!this}" />
In the above code snippet, you can see that I made a handler which runs when the component is initialized and i.e why salesforce has defined it to give the name init and in the above case, it calls the getContactList function which is present in our lightning controller. As we wanted to fetch our contact list when the page is loaded in the previous tutorial, so we used an init handler to do the task. Such event which is fired automatically on component initialization is an example of system event.

No comments:

Post a Comment