Newer Version Available
Handle Component Event of Instantiated Component
Let’s a look at an example. c:child registers that it may fire a sampleComponentEvent event by using <aura:registerEvent> in its markup.
1<!-- c:child -->
2<aura:component>
3 <aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>
4</aura:component>c:parent sets a handler for this event when it instantiates c:child in its markup.
1<!-- parent.cmp -->
2<aura:component>
3 <c:child sampleComponentEvent="{!c.handleChildEvent}"/>
4</aura:component>Note how c:parent uses the following syntax to set a handler for the sampleComponentEvent event fired by c:child.
1<c:child sampleComponentEvent="{!c.handleChildEvent}"/>The syntax looks similar to how you set an attribute called sampleComponentEvent. However, in this case, sampleComponentEvent isn’t an attribute. sampleComponentEvent matches the event name declared in c:child.
1<aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>The preceding syntax is a convenient shortcut for the normal way that a component declares a handler for an event. The parent component can only use this syntax to handle events from a direct descendent. If you want to be more explicit in c:parent that you’re handling an event, or if the event might be fired by a component further down the component hierarchy, use an <aura:handler> tag instead of declaring the handler within the <c:child> tag.
1<!-- parent.cmp -->
2<aura:component>
3 <aura:handler name="sampleComponentEvent" event="c:compEvent"
4 action="{!c.handleSampleEvent}"/>
5 <c:child />
6</aura:component>The two versions of c:parent markup behave the same. However, using <aura:handler> makes it more obvious that you’re handling a sampleComponentEvent event.