Grainier Grainier - 3 months ago 5
Javascript Question

Passing array of arguments for a function which expects N number of arguments

Basically what I'm trying to do is similar to this;

function methodX(arg1, arg2, ...) {}
methodX([arg1, arg2, arg3]);


In actual scenario I have an array (
cbInfo
), and I'm trying to use it with
jQuery.when()
as shown below and it doesn't seems to be working. So is there a way to pass array of arguments for a function which expects N number of arguments?

var cbInfo = [
{
templatePath: 'templates/level.html',
callback: renderLevels
},
{
templatePath: 'templates/alert.html',
callback: renderAlerts
}
];

function loadTemplates(cbInfo, cb) {
var ajaxes = [],
callbacks = [];

cbInfo.forEach(function (elem) {
ajaxes.push($.ajax({type: "GET", url: elem.templatePath}));
callbacks.push(elem.callback)
});

$.when(ajaxes).then(
function () {
var args = Array.prototype.slice.call(arguments);
callbacks.forEach(function (elem, index) {
elem(args[index]);
});
cb();
},
function () {
// failure
console.error("loadTemplates() : could not load UI templates.")
}
);
}

Answer

You can use function apply for that:

methodX.apply(null, [arg1, arg2, arg3]);

Like it says in the documentation:

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

Comments