addEventHandler()

Dynamically adds an event handler for a component or application event.

Signature

addEventHandler(String event, function handler, String phase, Boolean includeFacets)

Parameters

event
Type: String
The name of the event to handle. 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, namespace:eventName.
handler
Type: function
The handler for the event. There are two format options for this argument.
  • To use a controller action, use the format: cmp.getReference("c.actionName").
  • To use an anonymous function, use the format: function(auraEvent) { // handling logic here }
phase
Type: String
Optional. The event bubbling phase for which to add the handler. The default value is "bubble".
includeFacets
Type: Boolean
If true, attempts to catch events generated by components transcluded by facets; for example v.body.

Sample Code

1// For component event, first param matches name attribute in <aura:registerEvent> tag
2cmp.addEventHandler("compEvent", cmp.getReference("c.handleEvent"));
3
4// For application event, first param is event descriptor, "c:appEvent"
5cmp.addEventHandler("c:appEvent", cmp.getReference("c.handleAppEvent"));
6
7// Anonymous function handler for component event
8cmp.addEventHandler("compEvent", function(auraEvent) {
9    // add handler logic here
10    console.log("Handled the component event in anonymous function");
11});