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 docsample:sampleComponent.

1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17addNewHandler : function(cmp, event) {
18    var cmpArr = cmp.find({ instancesOf : "docsample:sampleComponent" });
19    for (var i = 0; i < cmpArr.length; i++) {
20        var outputCmpArr = cmpArr[i];
21        outputCmpArr.addHandler("someAction", cmp, "c.someAction");
22    }
23}

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.

addHandler() adds an event handler to a component.

Note that you can’t force a component to start firing events that it doesn't fire. c.someAction can be an action in a controller in the component's hierarchy. someAction and cmp refers to the event name and value provider respectively. someAction must match the name attribute value in the aura:registerEvent or aura:handler tag. Refer to the JavaScript API reference for a full list of methods and arguments.