0

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.

Grainier
  • 1,634
  • 2
  • 17
  • 30
  • 1
    Possible duplicate of [Passing an array as a function parameter in JavaScript](http://stackoverflow.com/questions/2856059/passing-an-array-as-a-function-parameter-in-javascript) – nikjohn Aug 26 '16 at 05:09

2 Answers2

4

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).

dotnetom
  • 24,551
  • 9
  • 51
  • 54
2

If you're using ES6, there's a perfect way to handle this: the Spread operator

functionName(...args);

Example: it is common to use Function.prototype.apply in cases where you want to use an array as arguments to a function.

function myFunction(x, y, z) { } var args = [0, 1, 2]; myFunction.apply(null, args);

With ES6 spread you can now write the above as:

function myFunction(x, y, z) { } var args = [0, 1, 2]; myFunction(...args);

Any argument in the argument list can use the spread syntax and it can be used multiple times.

function myFunction(v, w, x, y, z) { } var args = [0, 1]; myFunction(-1, ...args, 2, ...[3]);

Please refer here for more details

Working fiddle here

nikjohn
  • 20,026
  • 14
  • 50
  • 86
  • Added a working fiddle with `Array.prototype.apply`. This should work for you: https://jsfiddle.net/arj7x4gb/1/ – nikjohn Aug 26 '16 at 06:25