Flow of code in Salesforce lightning event



Let’s say we have Component A and Component B and an event E. You want to move from A to B then,
The flow of Code in Lightning Event are:-
Component Event:-
1. Firstly you have to register an event in component A.
<aura:registerEvent name=”EventE” type=”c:EventE“/>
2. Fire the event by clicking any button, like onclick=”{!c.fireComponentEvent}”. Controller Code is here:-
{
  fireComponentEvent : function(cmp, event) {
  // Get the component event by using the
  // name value from aura:registerEvent
  var cmpEvent = cmp.getEvent(“EventE”);
  cmpEvent.setParams({
     “message” : “A component event fired me. ” +
     “It all happened so fast. Now, I’m here!” });
      cmpEvent.fire();
   }
}

3. In Event E we have to pass data message so it look like this
<aura:event type=”COMPONENT”>
<aura:attribute name=”message” type=”String”/>
</aura:event>
4. Handle the event in Component B.
<aura:handler name=”EventE” event=”EventE” action=”{!c.handleComponentEvent}”/>
5. Code for Component B controller:-
{
    handleComponentEvent : function(cmp, event) {
     var message = event.getParam(“message”);
     // set the handler attributes based on event data
     cmp.set(“v.messageFromEvent”, message);
    }
}
That’s all for Component Event. Let’s talk about Application Event.
Application Event:-
1. Firstly you have to register an event in component A. Well, in Application event, it is not mandatory to register event but here we are registering the event.
<aura:registerEvent name=”EventE” type=”c:EventE”/>
2. Fire the event by clicking any button, like onclick=”{!c.fireComponentEvent}”. Controller Code is here:-
{
  fireApplicationEvent : function(cmp, event) {
// Get the application event by using the
// e.. syntax
var appEvent = $A.get(“e.c:EventE”);
appEvent.setParams({
“message” : “An application event fired me. ” +
“It all happened so fast. Now, I’m everywhere!” });
appEvent.fire();
   }
}
3. In Event E we have to pass data message so it look like this
<aura:event type=”APPLICATION”>
<aura:attribute name=”message” type=”String”/>
</aura:event>
4. Handle the event in Component B.
<aura:handler name=”EventE” event=”EventE” action=”{!c.handleApplicationEvent}”/>
5. Code for Component B controller:-
{
    handleApplicationEvent : function(cmp, event) {
     var message = event.getParam(“message”);
     // set the handler attributes based on event data
     cmp.set(“v.messageFromEvent”, message);
    }
}
Thanks.

Next Post Previous Post
No Comment
Add Comment
comment url