Reputation:
I would like to store multiple functions and their parameters in an array that I will later loop over and execute. When putting the parens around the parameters, the function executes immediately and its array value becomes undefined. I would like to prevent this from happening and call the function (with its parameter(s)) at a later time. Here is an example of what I am trying to accomplish...
function getTableAssignments(callbacks) {
$.ajax({
method: "POST",
datatype: "jsonp",
url: base_url + "users/getTableAssignments/" + event_id
}).done(function (data) {
tables = data;
if (callbacks.length > 0) {
$.each(callbacks, function (i, v) {
v();
});
}
});
}
getTableAssignments([func1(param1, param2), func2, func3(param3)]);
Upvotes: 5
Views: 3466
Reputation: 14313
I think arrow functions would be a slick way of doing this:
function func1 (param) {
console.log("func1 : " + param);
}
function func2 () {
console.log("func2");
}
function func3 (param1, param2) {
console.log("func3 : " + param1 + ", " + param2);
}
function executeFunctions(funcs) {
for (var i = 0, len = funcs.length; i < len; i++) {
funcs[i]();
}
}
favorateParam = "bob";
executeFunctions([
()=>func1("dad"),
()=>func2(),
()=>func3("jane",favorateParam)
]);
Upvotes: 1
Reputation: 1113
Storing the parameters is the problem. Here is how to store the function references:
getTableAssignments([func1, func2, func3]);
Here is how to bind the parameters to the functions prior to execution. This returns a new function. There are other ways to do it, but I think this would be the simplest.
var boundFunc1 = func1.bind(null, param1, param2);
var boundFunc3 = func3.bind(null, param3);
getTableAssignments([boundFunc2, func2, boundFunc3]);
You can also store your parameters in an object as arrays, and lookup those stored parameters with the function name, but that seems messy, so I won't expound on that method (and it would require you to change the calling to code the lookup the parameters).
If you haven't read up on bind, I'd recommend this video
Upvotes: 3
Reputation: 780724
You need to use function expressions:
getTableAssignments([
function() {func1(param1, param2); },
func2,
function() {func3(param3); }
]);
Upvotes: 1