Component events vs Application events (component.getEvent vs $A.get)

I am new to lightning experience and components. I have been through some blogs and code that guide through the basics, but other than that I haven’t had much hands-on experience.

My question is:

When to use component events vs application events? If I have nested components (parent & child) and if the events are of type Component, will the parent be able to handle events fired from child, and vice versa?

Also, I’ve noticed there are two ways to get an instance of an event (say TestEvent) –

    component.getEvent("TestEvent");

and

    $A.get("e.c:TestEvent");

Is there any difference between the both? What do “$A” & “e” in the second form, represent?

Thanks in advance for your reply!

Answer

Component events: to talk to a parent using the capture and bubbling mechanism, like with DOM events. Usually, one component is interested by the event, like an event aggregator.

Application events: to broadcast to other components and not exclusively ancestors. Applications events can talk to many components that can be interested by the event. The broadcast can be boxed to an area of the DOM (everything below a DIV for example).

About $A.getEvt() & cmp.getEvent():

Events have been seriously revamped, and the distinction between Component and Application events has been reduced. However, this rework has not yet been translated into an updated API.

I need to remove references to the $A.getEvt() and cmp.getEvent() API because we are still working on a new version of the API. My apologies for the confusion.

About value providers:

Lightning has various value providers: “v” for attributes, “c” for controller, and “e” for events.

Application Event API:

Those are obtained from the global (hence $A.get()) event value provider:

var evt = $A.get("e.myNamespace:myEvent");

Component Event API:

Component must reference events by name, much like an aura:id, and retrieve them from its component (hence cmp.get()) value provider:

var evt = cmp.get("e.myEvent");

You would then declare myEvent on the component as:

<aura:registerEvent name="myEvent" type="namespace:eventName"/>

Why dow have this API? Declaring events on a component allows other components to call controller methods. You had to declare a handler:

<aura:handler name="myEvent" action="{!c.myEventHandler}"/>

That allowed you to call myEventHandler from another component and respect the interface:

cmp.get("e.myEvent").fire();

Attribution
Source : Link , Question Author : James , Answer Author : JF Paradis

Leave a Comment