Search code examples
javascriptjqueryajax.when

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.")
        }
    );
}

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.


Solution

  • 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