Reputation: 5666
I want to push functions with params to an array without getting them executed. Here is what i have tried so far:
var load_helpers = require('../helpers/agentHelper/loadFunctions.js');
var load_functions = [];
load_functions.push(load_helpers.loadAgentListings(callback , agent_ids));
load_functions.push(load_helpers.loadAgentCount(callback , agent_data));
But in this way functions gets executed while pushing. This Question provides similar example but without params. How can I include params in this example?
Upvotes: 7
Views: 1409
Reputation:
Push functions which do what you want:
load_functions.push(
() => load_helpers.loadAgentListings(callback, agent_ids),
() => load_helpers.loadAgentCount (callback, agent_data)
);
Upvotes: 1
Reputation: 7438
You can wrap added elements with function like that, let's mock load_helpers
var load_helpers = {
loadAgentListings: function(fn, args) {
args.forEach(fn)
}
}
And try to use it in that way:
var a = []
a.push(function() {
return load_helpers.loadAgentListings(function(r) {
console.log(r)
}, ['a', 'b', 'c'])
})
a[0]() // just execution
All depends on what level you want to pass additional arguments, second proof of concept
var a = []
a.push(function(args) {
return load_helpers.loadAgentListings(function(r) {
console.log(r)
}, args)
})
a[0](['a', 'b', 'c']) // execution with arguments
With the bindings:
var a = []
a.push(load_helpers.loadAgentListings.bind(null, (function(r) {return r * 2})))
console.log(a[0]([1, 2, 3])) // execution with additional parameters
Upvotes: 1
Reputation: 444
You have to bind the parameters to the function. The first parameter is the 'thisArg'.
function MyFunction(param1, param2){
console.log('Param1:', param1, 'Param2:', param2)
}
var load_functions = [];
load_functions.push(MyFunction.bind(undefined, 1, 2));
load_functions[0](); // Param1: 1 Param2: 2
Upvotes: 3