Application Events in Lightning

Application events in Lightning

If you are here, I assume you already seen Events in Lightning blog, because I had discussed about events and a demo on component event. So, even here I will follow the same architecture in this blog to refer to application events.

In application event, hierarchy of components is not required. Any event fired by a component can be listened by a component which has its listener. So it will be okay to say you component is exposed to other components in same namespace.

Let’s declare an event “DemoAppEvent“:- 

 

   

 

The attribute demoVal will be set in Component1 and its value will be carried to Component2. So Component2 will show this new value in its body.

Component1.cmp

 

   

   

   

 

        Component 1

   

   

 

 

The button click will call controller method fireEvent, and this method will further fire the event DemoAppEvent with its parameter.

Component1Controller.js

({

fireEvent : function(component, event, helper) {

         var appEvent = $A.get(“e.c:DemoAppEvent”); 

        //Set event attribute value 

        appEvent.setParams({“demoVal” : “Component1 button Clicked atleast once”});

        appEvent.fire();

        }

})

Now we will add some code to our Component2 which was already developed in Events in Lightning blog so that you do not have to rework. You can copy paste the below code in your Component2.

Component2.cmp

 

   

   

   

   

     

   

 

       

Component 2   
Number of clicks from Component1: {!v.count}    {!v.str}

        Welcome  {!v.handledval}

       

 

       

 

   

   

 

       

 

 

We have added a new attribute count, so that we will keep on increasing its value every time Component1 fires the DemoAppEvent . We have also defined the handler of DemoAppEvent which will call setFlag method to increase the value of count.

Component2Controller.js

 ({

setVal : function(component, event, helper) {

        var gotName=event.getParam(“carryFrwrd”);

        component.set(“v.handledval”,gotName);

},

 

    setFlag: function(component, event, helper) {

       component.set(“v.count”,component.get(“v.count”)+1);

            component.set(“v.str”,event.getParam(“demoVal”));

    }

})

Congratulations!!! You have completed events module in Lightning.

I have updated the code of the app so that it could fit in the design and looks better. You can copy and paste below code in your demo app:- 

 

 

 

   

 

         

   

 

   

 

   

   

 

   

 

</aura:application>

Below is the output of the code , we have just developed:-

Working on Application Event

The above app code was developed keeping in mind the below design:- 

event architecture in lightning

Hope these two blogs nurtures your understanding in lightning event. I will see you in the next blog, till then Happy Coding!!!

(Visited 146 times, 1 visits today)

Leave a Reply