Newer Version Available

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

Dynamically Adding Event Handlers

You can dynamically add a handler for an event that a component fires. The component can be created dynamically on the client-side or fetched from the server at runtime.

This sample code adds an event handler to instances of c:sampleComponent.

1addNewHandler : function(cmp, event) {
2    var cmpArr = cmp.find({ instancesOf : "c:sampleComponent" });
3    for (var i = 0; i < cmpArr.length; i++) {
4        var outputCmpArr = cmpArr[i];
5        outputCmpArr.addHandler("cmpEvent", cmp, "c.someAction");
6    }
7}

Let’s look at the addHandler() method that adds an event handler to a component.

1outputCmpArr.addHandler("cmpEvent", cmp, "c.someAction");
  • cmpEvent—The first argument is the name of the event that triggers the handler. Note that 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. Set this argument to match the name attribute of one of the <aura:registerEvent> tags.
  • cmp—The second argument is the value provider for resolving the action expression, which is the next argument. In this example, the value provider is the component associated with the controller.
  • c.someAction—The third argument is the controller action that handles the event. This is equivalent to the value you would put in the action attribute in the <aura:handler> tag if the handler was statically defined in the markup.

For a full list of methods and arguments, refer to the JavaScript API in the doc 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.