I have 1 main component (Parent.cmp) which includes 2 components (Brother1.cmp and Brother2.cmp).
Brother1 fires an event which should cause an action in Brother2.
Documentation says that we should use APPLICATION events for that:
Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified.
I've created an APPLICATION event and fire it from Brother1. According to the documentation, I expect the event to be distributed to Brother2. It is handled by Parent.cmp, but it never gets to Brother2.
What I tried:
- as the Parent.cmp receives the Brother1 event, I tried to fire a new Parent_evt APPLICATION event hoping it will be dispatched to Brother2. No success.
- The expression
var brother1Event = $A.get("e.c:Brother1_evt");
doesn't work in my code, and even doesn't seem to be firing any event at all.
What am I missing ?
Thank you for your help.
Components code below:
TestEvents.app:
<aura:application extends="force:slds">
<c:Parent/>
</aura:application>
Parent.cmp
<aura:handler name="Brother1_evt" event="c:Brother1_evt" action="{!c.handleBrother1_evt}" />
<aura:attribute name="message" type="string" />
Parent message: <ui:outputtext value="{!v.message}" />
<div>
<c:Brother1/>
</div>
<div>
<c:Brother2/>
</div>
ParentController.js:
({
handleBrother1_evt : function(component, event, helper) {
component.set( "v.message", "Brother1 event Received");
}
})
Brother1.cmp
<aura:component >
<aura:registerEvent name="Brother1_evt" type="c:Brother1_evt" />
<aura:attribute name="message" type="string" />
<aura:handler name="Brother1_evt" event="c:Brother1_evt" action="{!c.handleBrother1_evt}" />
<lightning:button label="Click Me to fire an event from Brother 1!" variant="brand" onclick="{!c.handleBrother1Click}" />
<br/>
Brother 1 message: <ui:outputText value="{!v.message}" />
Brother1_evt.evt
<aura:event type="APPLICATION" description="Event template" />
Brother1Controller.js
({
handleBrother1Click : function(component, event, helper) {
var brother1Event = component.getEvent("Brother1_evt");
brother1Event.fire();
},
handleBrother1_evt : function(component, event, helper) {
component.set( "v.message", "Brother1 event Received");
}
Brother2.cmp
<aura:component >
<aura:handler name="Brother1_evt" event="c:Brother1_evt" action="{!c.handleBrother1_evt}" />
<aura:attribute name="message" type="string" />
Brother 2 message: <ui:outputText value="{!v.message}" />
Brother2Controller.js
({
handleBrother1_evt : function(component, event, helper) {
component.set( "v.message", "Brother1 event Received");
}
})
Output:
<aura:handler>
. Use the name attribute only when you’re handling component events.