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

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

You can also add an event handler to a component that is created dynamically in the callback function of $A.services.component.newComponentAsync(). See Dynamically Creating Components for more information.

component.addHandler() adds an event handler to a component. Note that you cannot 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.