Lightning Application Events
Introduction
In this blog post, I am going to explain how to use the application events.Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All
components that provide a handler for the event are notified.But its good practice to use the component eventsĀ whenever possibleĀ insteadĀ of application events.Create an application eventĀ contains there steps
Step 1: Create an Application event
Create a new application event with below code as shown below. appEvent.evt
<aura:event type="APPLICATION"> <aura:attribute name="message" type="String"/> </aura:event>
Step 2: Register an Event
A component registers that it may fire an application event by using <aura:registerEvent> in its markup. The name attribute is required but not used for application events. The name attribute is only relevant for component events. This example uses name=”</aura:appEvent” but the value isnāt used anywhere.
<aura:registerEvent name="appEvent" type="c:appEvent"/>
Step 3 : Fire an Event
Use $A.get(“e.myNamespace:myAppEvent”) in JavaScript to get an instance of the myAppEvent event in the myNamespace namespace.
var appEvent = $A.get("e.c:appEvent"); appEvent.setParams({ "myParam" : myValue }); appEvent.fire();
Put All together
Now lets put all togetherĀ to understandĀ the application events.Here below is the component which will trigger the application events.
AppNotifier.cmp
<aura:component> <b> Notifer Component</b> <p> Please Enter the text and then Click here to fire button </p> <ui:inputText aura:id="inpId" value="This is Really cool ..!" required="true"/> <aura:registerEvent name="appEvent" type="c:appEvent"/> <p><lightning:button label="Click here to fire an application event" onclick="{!c.fireApplicationEvent}" /> </p> </aura:component>
({ fireApplicationEvent : function(cmp, event) { var appEvent = $A.get("e.c:appEvent"); var inpText = cmp.find("inpId").get("v.value"); appEvent.setParams({ "message" :inpText }); appEvent.fire(); } })
.THIS{ color: #2f5687; font-size:20px; }
AppHandler.cmp
AppHandler is component that will handle the event notification which is fired from the AppNotifer component and handle them
<aura:component > <hr/> <b> Handler Component</b> <aura:attribute name="messageFromEvent" type="String"/> <aura:handler event="c:appEvent" action="{!c.handleApplicationEvent}"/> <p>{!v.messageFromEvent}</p> </aura:component>
({ handleApplicationEvent : function(cmp, event) { var message = event.getParam("message"); cmp.set("v.messageFromEvent", message); }, })
.THIS{ color: #FF5733; font-size:20px; }
AppContainer.cmp
<aura:component > <c:AppNotifier/> <c:AppHandler/> </aura:component>