How to use Application or Component Events in Lightning…
When you want to emit or broadcast some data between component hierarchy or different components on same App.
Create a Lightning Event and place the attributes you wish to transmit ( Can be any primitive type ) :
<!--c:compEvent--> <aura:event type="COMPONENT / APPLICATION"> <!-- Add aura:attribute tags to define event shape. One sample attribute here. --> <aura:attribute name="message" type="String"/> </aura:event>
On your component that will fire the event you must register it first by adding the following attribute.
Component or Application events will be registered the same :
<aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>
Then simply on your JS controller add the fire() method in your event function.
Component Event getEvent by Name :
var compEvent = component.getEvent("sampleComponentEvent"); // Optional: set some data for the event (also known as event shape) // A parameter’s name must match the name attribute // of one of the event’s <aura:attribute> tags // compEvent.setParams({ "message" : myValue }); compEvent.fire();
Application Event :
// Get the application event by using the // e.<namespace>.<event> syntax var appEvent = $A.get("e.c:compEvent"); appEvent.setParams({ "message" : "An application event fired me. " + "It all happened so fast. Now, I'm everywhere!" }); appEvent.fire();
On the Other component which supposed to listen to the event and do something with this piece of data that was sent from the firing component.
Add a listener handler :
Component Event :
<aura:handler name="sampleComponentEvent" event="c:compEvent" action="{!c.handleComponentEvent}"/>
Application Event (Will not reference the name attribute) :
<aura:handler event="c:aeEvent" action="!c.handleApplicationEvent}"/>
worth mentioning here that when event is being captured on our listener component it has few phases.
Component event handlers are associated with the bubble phase by default. To add a handler for the capture phase instead, use the phase attribute.
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_component_handling_intro.htm
On The JS Controller side :
/* ceHandlerController.js */ { handleApplicationOrComponentEvent : function(component, event) { var message = event.getParam("message"); // set the handler attributes based on event data component.set("v.messageFromEvent", message); var numEventsHandled = parseInt(component.get("v.numEvents")) + 1; component.set("v.numEvents", numEventsHandled); } }
Main obvious reason to use one over the other is that Application Event is more “expensive” as it will transmit the data across different components which are not part of the hierarchy.