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?

2 Answers 2

8

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.

1
  • Thanks! Using container handler is very useful, didn't know about that. Could you suggest some blog post of best practices for Lightning Development? Commented Mar 25, 2017 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.

1
  • Thank you so much! You rock! I need to read more about difference between application/component events. Commented Mar 25, 2017 at 14:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .