Newer Version Available

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

Dynamically Adding Event Handlers To a Component

You can dynamically add a handler for an event that a component fires.

The addEventHandler() method in the Component object replaces the deprecated addHandler() method.

To add an event handler to a component dynamically, use the addEventHandler() method.

event
The first argument is the name of the event that triggers the handler. You can’t force a component to start firing events that it doesn’t fire, so make sure that this argument corresponds to an event that the component fires. The <aura:registerEvent> tag in a component’s markup advertises an event that the component fires.
  • For a component event, set this argument to match the name attribute of the <aura:registerEvent> tag.
  • For an application event, set this argument to match the event descriptor in the format namespace:eventName.
handler
The second argument is the action that handles the event. The format is similar to the value you would put in the action attribute in the <aura:handler> tag if the handler was statically defined in the markup. There are two options for this argument.
  • To use a controller action, use the format: cmp.getReference("c.actionName").
  • To use an anonymous function, use the format:

For a description of the other arguments, see the JavaScript API in the Aura Reference app.

You can also add an event handler to a component that is created dynamically in the callback function of $A.createComponent(). For more information, see Dynamically Creating Components.

Example

This component has buttons to fire and handle a component event and an application event.

Here’s the client-side controller.

Notice the first parameter of the addEventHandler() calls. The syntax for a component event is:

The syntax for an application event is:

For either a component or application event, you can use an anonymous function as a handler instead of using cmp.getReference() for a controller action.

For example, the application event handler could be: