[SalesForce] Trying to use addHandler to a dynamically created component

I have a component that dynamically generates a field using $A.createComponent. I want to add a change handler to the created component, and it fires as expected. However, I get an error saying that the controller action is not found.

Here's my component's controller:

doInit : function(component, event, helper) {
    // make the field component.
    $A.createComponent(component.get('v.fieldDefinition'), component.get('v.fieldAttributes'),function(cmp,status,error){
        if(component.get('v.fieldDefinition').startsWith('ui:')){
            // need to add a handler for standard ui: components.  
            // custom components register them on their own.
            cmp.addHandler('change',cmp, 'c.handleFieldUpdated');
        }
        component.set('v.cmp',cmp);
    });
},
handleFieldUpdated : function(component,event,helper){
    console.log('field updated');
}

The above init block generates a component, such as "ui:inputText". Then I use "cmp.addHandler" so I can tell it to call my "handleFieldUpdated" controller action when the value changes.

The change event fires, however the error message I receive is "Uncaught Unknown controller action 'handleFieldUpdated'"

I've tried using the following syntax in my addHandler to assign the controller action, and none have worked:

"c.handleFieldUpdated"
"component.get('c.handleFieldUpdated')"
"handleFieldUpdated"

All with the same error message. Is there another way to assign the correct controller action to the generated UI component?

EDIT:: I tried the following using "addEventHandler" as suggested in the comments.

doInit : function(component, event, helper) {
    // make the field component.
    $A.createComponent(component.get('v.fieldDefinition'), component.get('v.fieldAttributes'),function(cmp,status,error){
        if(component.get('v.fieldDefinition').startsWith('ui:')){
            // need to add a handler for standard ui: components.  
            // custom components register them on their own.
            cmp.addEventHandler('change', component.getReference("c.handleFieldUpdated"));
        }
        component.set('v.cmp',cmp);
    });
},
handleFieldUpdated : function(component,event,helper){
    console.log('field updated');
}

This gives me the following error: "Action failed: c:FieldComponent$controller$doInit [cmp.addEventHandler is not a function]"

Best Answer

Solved it. The addHandler call needs to reference the parent component, not the child that was generated. So it needs to change from this:

cmp.addHandler('change',cmp, 'c.handleFieldUpdated');

to this:

cmp.addHandler('change',component, 'c.handleFieldUpdated');
Related Topic