Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run callback with all arguments

How can I run a callback function with all of its arguments when I don't know how many arguments are supplied.

Take the following example:

function tryMe (param1, param2) {
    alert(param1 + " and " + param2);
}

function callbackTester (callback) {
    callback (arguments[1], arguments[2]);
}

callbackTester (tryMe, "hello", "goodbye");

callbackTester (tryMe, "hello", "goodbye", "seeYouLater");

How can I run the callback from the callbackTester() function so that it will automatically call all of its arguments?

Fiddle : http://jsfiddle.net/qj1rs29q/

like image 535
user3143218 Avatar asked Feb 04 '26 05:02

user3143218


1 Answers

This one should suit your needs:

function callbackTester() {
    var args = Array.prototype.slice.call(arguments),
        callback = args.shift();
    callback.apply(this, args);
}

Fiddle

like image 80
sp00m Avatar answered Feb 06 '26 17:02

sp00m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!