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.")
}
);
}
UPDATE:
Both apply and spread operator worked in other situations. But I'm trying to solve this for this specific situation. I tried using $.when().apply(null, ajaxes), but then it throws Uncaught TypeError: $.when(...).apply is not a function
How to overcome this? Moreover, I need to support ES5 too.