[SalesForce] Helper Method undefined when called from dynamically created component

Using examples from the developer documentation Dynamically Creating Components, I am attempting to create a button dynamically (which I should be able to select in order to create a new component dynamically).

<aura:component implements="forceCommunity:availableForAllPageTypes" access="global" >

    <lightning:button variant="brand" label="Submit" onclick="{! c.handleClick }" />

    <div>{!v.body}</div>
</aura:component>

Controller.js

({
    handleClick : function(cmp) {
        $A.createComponent(
            "lightning:button",
            {
                "aura:id": "findableAuraId",
                "label": "Press Me",
                "onclick": cmp.getReference("c.handlePress")
            },
            function(newButton, status, errorMessage){
                //Add the new button to the body array
                if (status === "SUCCESS") {
                    var body = cmp.get("v.body");
                    body.push(newButton);
                    cmp.set("v.body", body);
                }
                else if (status === "INCOMPLETE") {
                    console.log("No response from server or client is offline.")
                    // Show offline error
                }
                else if (status === "ERROR") {
                    console.log("Error: " + errorMessage);
                    // Show error message
                }
            }
        );
    },
    handlePress : function(cmp) {
        console.log('pressed');
        helper.helperMethod(cmp);
    }
})

helper.js

({
    helperMethod : function(cmp) {
        console.log('helper triggered');
    }
})

when I call the hendlePress method from the dynamically created component, it is able to corretly call the controller, however, the helper method is 'undefined':

message : "Cannot read property 'helperMethod' of undefined" stack :
"TypeError: Cannot read property 'helperMethod' of undefined…

Why is the dynamically created component able to call the controller method, but the controller method unable to call it's helper?

enter image description here

Best Answer

Aura framework calls the controller method with three arguments in exact order:

handlePress : function(component, event, helper) {
    console.log('pressed');
    helper.helperMethod(cmp);
}

And you just missed last two arguments event and helper:

handlePress : function(cmp) {
    console.log('pressed');
    helper.helperMethod(cmp);
}
Related Topic