I am new to Lightning and am going through the Lightning Components Basics module.
In the expensesHelper.js file would like to find out if it's possible to move the callback function definition inside the setCallback function's input parameters to its own function and pass this function's name in the arguments instead.
Instead of this:
({
createExpense: function(component, expense) {
var action = component.get("c.saveExpense");
action.setParams({
"expense": expense
});
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
var expenses = component.get("v.expenses");
expenses.push(response.getReturnValue());
component.set("v.expenses", expenses);
}
})
$A.enqueueAction(action);
},
})
I would like to move the callback function defintion out into its own function like this:
({
createExpense: function(component, expense) {
var action = component.get("c.saveExpense");
action.setParams({
"expense": expense
});
action.setCallback(this, this.cbackfunction);
$A.enqueueAction(action);
},
cbackfunction: function(response){
var state = response.getState();
if (state === "SUCCESS") {
var expenses = component.get("v.expenses");
expenses.push(response.getReturnValue());
component.set("v.expenses", expenses);
}
}
})
With the code above I am getting the run-time error: "Error in $A.getCallback() [component is not defined] Callback failed: apex://ExpensesController/ACTION$saveExpense Failing descriptor: {c:expenses}"
I added a console log to make sure that "this.cbackfunction" exists and it does:
console.log("this.cbackfunction: " + this.cbackFunction);
this.cbackfunction: function (response) {
var state = response.getState();
var expenses = component.get("v.expenses");
expenses.push(response.getReturnValue());
component.set("v.expenses", expenses);
}
So, the cbackfunction function is visible from within the createExpense function.
Any ideas on how to call setCallback with a callback function?