Hello friends, In this post we are going to learn about lightning application event. We used application event in lightning component to communicate between components. so let's understand this using example.
Application event in lightning component
In Salesforce, lightning is based on event-driven architecture which used to communicate between different events. Application events are the handle by any component no matter what relationship between them but they should belongs to single application.
Implementation:
For application event implementation, we have to create two components. i.e. a) Child b) Parent and also a lightning event.
To create lightning event, Navigate to Developer Console | File | New | Lightning Event and create a lightning event named "SampleApplicationEvent" and replace the following markup.
SampleApplicationEvent.evt
<aura:event type="Application" description="Application Event">Child.cmp
<aura:attribute name="empName" type="String"/>
</aura:event>
<aura:component implements="flexipage:availableForAllPageTypes" access="global">ChildController.js
<aura:registerEvent name="SampleAppEvent" type="c:SampleApplicationEvent"/>
<div class="slds-m-around_xx-large">
<lightning:button label="Click to fire the event" variant="brand" onclick="{!c.FireEvent}"/>
</div>
</aura:component>
({Parent.cmp
FireEvent : function(component, event, helper) {
var appEvent = $A.get("e.c:SampleApplicationEvent");
//Set event attribute value
appEvent.setParams({
"empName" : "Employee 1"
});
appEvent.fire();
},
})
<aura:component implements="flexipage:availableForAllPageTypes" access="global">ParentController.js
<aura:handler event="c:SampleApplicationEvent" action="{!c.ApplicationEventHandler}"/>
<aura:attribute name="message" type="String"/>
<div class="slds-m-around_xx-large">
<p>{!v.message}</p>
</div>
</aura:component>
({
ApplicationEventHandler : function(component, event, helper) {
//Get the event message attribute
var message = event.getParam("empName");
component.set("v.message", "Hi! "+message);
}
})
Preview: To see the output you have to include the both components in a single lightning application.
Preview.app
<aura:application extends="force:slds">
<c:Parent/>
<c:Child/>
</aura:application>
Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.
0 Comments
Post a Comment