7

What is the best way to communicate between two child Lightning components using events?

For example if I have one parent CMP_MAIN and two child components CMP_1 and CMP_2. I want to send parameter from CMP_1 to CMP_2. What is best way to do that?

7

This is done through an application event, which means that every component involved needs to do something to coordinate their efforts.

Event

The event needs to be defined with whatever properties you want:

<aura:event type="APPLICATION">
    <!-- include aura:attribute elements here -->
</aura:event>

Source Component

The source component needs to register its ability to fire these events:

<aura:component>
    <aura:registerEvent name="localName" event="c:appEvent" />
</aura:component>

In the controller, you can fire these events:

fireEvent: function(component, event, helper) {
    var event = $A.get("e.c:appEvent");
    event.setParams( { } ); // Set your attributes
    event.fire();
}

Destination Component

The destination needs to register a handler to handle these events.

<aura:component>
    <aura:handler event="c:appEvent" action="{!c.handleAppEvent}" />

Container Component

The container should also handle the event. This prevents components outside your component hierarchy from getting the event (e.g. you have multiple copies of your components on a page).

<aura:component>
    <aura:handler event="c:appEvent" action="{!c.containEvent}" />
    <c:CMP_1 />
    <c:CMP_2 />
</aura:component>

The containEvent method should stop propagation:

containEvent: function(component, event, helper) {
    event.stopPropagation();
}

This can be a major performance boost if there are many copies of your component within an app, Lightning page, etc. If you have no container event, this allows the source to communicate with the destination even if they are not in the same component hierarchy at all.

  • Thanks! Using container handler is very useful, didn't know about that. Could you suggest some blog post of best practices for Lightning Development? – Eugene Vabishchevich Mar 25 '17 at 14:16
1

Since the two components CMP_1,CMP_2 belongs to the same level in the containment hierarchy, you need to use Application event for the inter component communication.

The link over here discusses the same usecase and I believe this will help you out.

  • Thank you so much! You rock! I need to read more about difference between application/component events. – Eugene Vabishchevich Mar 25 '17 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.