• +91-8376990324
  • amitdsy@gmail.com
Home • • Play with Events in Salesforce Lightning Component

Play with Events in Salesforce Lightning Component

Application Event: – Whenever our component are not connected to each other and in that case we wanted to communicate between the components. Then we go for application event. We do not need to register the application event, handler is need to handle the application event.

Use Case: – When we want to communicate with the components that are not related to each other but need to reflect the data when there is any change in the other component. For example: – We have 2 components, 1st shows the List of All Contacts record and when we click on any contact we want to show the details of the contact then we will use Application Event.

In order to use Application event we need to follow the Four simple steps

  1. Create Application Event
  2. Fire the event from the child component
  3. handle the event into Parent Component
  4. Execute the action into Parent Component

Let’s start implementation:

Step 1 – Create Application Event

Open developer console and then File -> New -> Lightning Event -> name it applicationEvent and use below code.

<aura:event type=”APPLICATION” description=”Event template” >
<aura:attribute name=”testWord” type=”String” />

Step 2 – Register the event

Unlike the Component we do not need to register the Application Event.

Step 3 – Fire the component Event

Use below code in javascript to execute the event.

handleClick : function(component, event, helper) {
    var appEvent = $A.get(‘e.c:applicationEvent’);
            “testWord” : ‘Value From Application Event’

Explanation : –

  1. $A.get(‘e.c:applicationEvent’); – Finds the event with the name provided after c: and in our case it it applicationEvent.
  2. setParams : – is used to send the parameters to the parent component if we are using any attribute in the event. In our case we have used attribute testWord
  3. fire() :- Executes the event

Step 4: – Handle the Event in any Component

A single line of code to handle the event into the parent component

<aura:handler event=”c:applicationEvent” action=”{!c.doHandleCompEvent}” />

Explanation : –

  1. event: – Same as the type that we have provided at the time of registering the event
  2. action: – calls the java script controller method and there you can do rest of your stuffs

Step 5: – Do Action in JS controller

doHandleCompEvent : function(component, event, helper){

      var eventParam = event.getParam(‘testWord’);

     // getParams is used to get the parameters that we have passed from the child component


Note: – Both Application Event Handler and Application Event notifier component must be part of the same component. For example let call that component as aeContainer.cmp which will contain both the components.

<aura:component >
        <c:applicationEventComp1 />

Tags: ,
Apply For Trainer