Newer Version Available

This content describes an older version of this product. View Latest

Component Events

A component event can be handled by a component itself or by a component that instantiates or contains the component.

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 component event with one message attribute.

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:

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:

Component Handling Its Own Event

A component can handle its own event by using the aura:handler tag in its markup.

The action attribute of <aura:handler> sets the client-side controller action to handle the event. For example:

The name attributes in <aura:registerEvent> and <aura:handler> must match, since each event is defined by its name.

Note

Handle Component Event of Instantiated Component

The component that registers an event declares the name attribute of the event. For example, an <auradocs:eventsNotifier> component contains a <aura:registerEvent> tag.

When you instantiate <auradocs:eventsNotifier> in another component, use the value of the name attribute from the <aura:registerEvent> tag to register the handler. For example, if an <auradocs:eventsHandler> component includes <auradocs:eventsNotifier> in its markup, eventsHandler instantiates eventsNotifier and can handle any events thrown by eventsNotifier. Here’s how <auradocs:eventsHandler> instantiates <auradocs:eventsNotifier>:

Note how sampleComponentEvent matches the value of the name attribute in the <aura:registerEvent> tag in <auradocs:eventsNotifier>.

Handle Component Event Dynamically

A component can have its handler bound dynamically via JavaScript. This is useful if a component is created in JavaScript on the client-side. See Dynamically Adding Event Handlers.

Get the Source of a Component Event

Use evt.getSource() in JavaScript to find out which component fired the component event, where evt is a reference to the event.