5

I have the following code in my controller:

    doInit: function(component, event, helper) {
    // Create the action
    var action = component.get("c.getExpenses");
    // Add callback behavior for when response is received
    action.setCallback(this, 
         response => this.cbFunction(component, response));

    $A.enqueueAction(action);
},
cbFunction: function(component, response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            component.set("v.expenses", response.getReturnValue());
        }   
},

but I get the following error:

This page has an error. You might just need to refresh it. Error in $A.getCallback() [Cannot read property 'cbFunction' of undefined] Callback failed: apex://ExpensesController/ACTION$getExpenses Failing descriptor: {c:expenses}

If I go back to the original code of placing the cb inside doInit, it works just fine, so it's not anything in the code, but rather after I extracted the cb function.

6

The controller of a component has no this context, only the helper does.

There are ways of calling one method from another via something like:

let action = component.get("c.cbFunction"); 
$A.enqueueAction(action);

But you can't pass parameters, and the event parameter ends up being null, so overall, it doesn't work particularly well. Instead, whenever you need to call functions that used elsewhere, put them in your helper:

({
    doInit: function(component, event, helper) {
        helper.doInit(component);
    }
})

And for your helper, you then have "this":

({
    doInit: function(component) {
        let action = component.get("c.getExpenses");
        action.setCallback(this, this.cbFunction);
        $A.enqueueAction(action);
    },
    cbFunction: function(result) {
        // handle the results of the callback
    }
})
0

If you are referencing another function from within your controller, best practice (at least where I work) is to move the logic to a helper. Define that function in your helper and you can just change it to:

response => helper.cbFunction(component, response)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.