AlexC
AlexC

Reputation: 9661

Functions with Variable Arguments in javascript/jQuery

I need and advice.

This is my issue, I have "N" functions.

 var FirstOne  = function(){
    return $.ajax({
        type: "POST",
        url: hrefUrl,
        data: JSON2.stringify(option),
        contentType: "application/json; charset=utf-8",
        dataType: "json",           
        error: function(status){
        },
        success: function(data){    
        }
    });
};

var SecondOne  = function(){

    return $.ajax({
        type: "POST",
        url: hrefUrl,
        data: JSON2.stringify(option2),
        contentType: "application/json; charset=utf-8",
        dataType: "json",           
        error: function(status){
        },
        success: function(data){    
        }
    });
};


.............


var NOne  = function(){

    return $.ajax({
        type: "POST",
        url: hrefUrl,
        data: JSON2.stringify(optionn),
        contentType: "application/json; charset=utf-8",
        dataType: "json",           
        error: function(status){
        },
        success: function(data){    
        }
    });
};

all these function arr pushed in an object which is this .

var funcObject= [FirstOne(), SecondOne(), ....... NOne() ];

after I am waiting when all Ajax functions are done with and and after I am fine.

    $.when.apply($, funcObject).done(function (a1, a2, ...an) {
 //        ..... here already doesn't matter

    });

my issue is here:

function (a1, a2, ...an)

I want to have instead function arguments an object because I do not know how many function is going to be.

So i can edit function object, which is cool $.when.apply($, fucArr), problem is to use variable numbers of arguments .

PS: Maybe I can use "apply" or "call" for these arguments as well?

Can someone give me an idea here. Thanks A lot guys!!!

Upvotes: 5

Views: 4751

Answers (1)

Rich O'Kelly
Rich O'Kelly

Reputation: 41767

You can access all arguments passed to a method using the arguments keyword eg:

function () {
  Console.log(arguments); //arguments is an array
}

The apply method can be used to use these arguments in another function call:

function () {
  someFunction.apply(this, arguments);
}

Upvotes: 11

Related Questions