Newer Version Available
Component Events
Create Custom Component Event
You can create custom component events using the <aura:event> tag in a .evt resource. Events can contain attributes that can be set before the event is fired and read when the event is handled.
Use type="COMPONENT" in the <aura:event> tag for a component event. For example, this is a c:compEvent component event with one message attribute.
1<!--c:compEvent-->
2<aura:event type="COMPONENT">
3 <!-- add aura:attribute tags to define event shape.
4 One sample attribute here -->
5 <aura:attribute name="message" type="String"/>
6</aura:event>The component that handles an event can retrieve the event data. To retrieve the attribute in this event, call event.getParam("message") in the handler’s client-side controller.
Register Component Event
A component registers that it may fire an event by using <aura:registerEvent> in its markup. For example:
1<aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>We’ll see how the value of the name attribute is used for firing and handling events.
Fire Component Event
To get a reference to a component event in JavaScript, use getEvent("evtName") where evtName matches the name attribute in <aura:registerEvent>. Use fire() to fire the event from an instance of a component. For example, in an action function in a client-side controller:
1var compEvent = cmp.getEvent("sampleComponentEvent");
2// Optional: set some data for the event (also known as event shape)
3// compEvent.setParams({"myParam" : myValue });
4compEvent.fire();Get the Source of a Component Event
In a handler component, use evt.getSource() in JavaScript to find out which component fired the component event, where evt is a reference to the event. To retrieve the source element, use evt.getSource().getElement().