Aura Application Events

Musarat Happiness
2 min readNov 30, 2020

Application Events in Aura framework are used to pass data between components that are not in same hierarchy or parent-child relation. This means they are part of Application but are not related to each other as parent child.

For eg: Lets say we have an Application which invokes two Components within it.

<aura:application extends=”force:slds” >
<! — Example of Application Events to Send Data/Message from Component One to Component Two →
<c:ComponentOne/>
<c:ComponentTwo/>

</aura:application>

If Our use case is to send data from Component One to Two where both are at same level i.e. none is parent or child of each other then we use application events.

There are 4 major Steps:

Step 1: Create Aura Application Event.

Step 2: Register Event in Source/Sending component.

Step 3: Fire Event from Source Component.

Step 4:Handle the Event in Receiving Component.

Step 1: Create Aura Application Event. Go to File →New →Lightning Event

AppEventTest.evt

<! — Step 1: Create Event →
<aura:event type=”APPLICATION” description=”Event template”>
<aura:attribute name=”messagefromAppEvent” type=”String”/>
</aura:event>

Step 2/3: Register Event in Source Component & Fire.

Component One here is Source , so lets do below:

ComponentOne.cmp

<aura:component >
<! — Step 2: Register Event in Source Component →
<aura:registerEvent name=”AppEvent” type=”c:AppEventTest”/>

<! — Step 3: Fire Event from Source Component on click of button →
<aura:attribute name=”greeting” type=”String”/>
<p>This is Component 1</p>
<lightning:input label=”Your Greeting: “ value=”{!v.greeting}”/>
<lightning:button label=”Send” onclick=”{!c.handleSend}”/>
</aura:component>

ComponentOneCOntroller.js

({
//Step 3: Continued:Fire Event from Source Component on click of button
handleSend : function(component, event, helper) {
var g = component.get(“v.greeting”);
console.log(‘COMP1: inside COMP1:Sending:g: ‘+g);
var appEvent = $A.get(“e.c:AppEventTest”);
appEvent.setParams({
“messagefromAppEvent”: g
});
appEvent.fire();
}
})

Step 4: Handle Event in Receiver Component Two.

ComponentTwo.cmp

<aura:component >
<! — Step 4: handle event in receiver component →
<aura:handler event=”c:AppEventTest” action=”{!c.handleAppEvent}”/>
<aura:attribute name=”CompTwoGreetingReceived” type=”String”/>
<lightning:card>
<p>This is Component 2</p>
<p>Showing you now value received in Comp 2 from Comp1: </p>
<ui:outputText value=”{!v.CompTwoGreetingReceived}”/>
</lightning:card>
</aura:component>

ComponentTwoController.js

({
handleAppEvent : function(component, event, helper) {
var tempGreeting = event.getParam(“messagefromAppEvent”);
console.log(‘COMP2: Inside HandleAppEvent :tempGreeting: ‘+tempGreeting);
component.set(“v.CompTwoGreetingReceived”,tempGreeting);
}
})

--

--