Running a callback with all arguments
How can I run a callback function with all its arguments when I don't know how many arguments are provided.
Let's 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 trigger a callback from callbackTester()
within a function so that it automatically calls all of its arguments?
Fiddle: http://jsfiddle.net/qj1rs29q/
+3
source to share
2 answers
ECMAScript6 introduces the so-called rest option . It allows you to refer to all other arguments that are not explicitly specified. Together with your function it will look like .apply
function callbackTester (callback, ...args) {
callback.apply(null, args);
}
// callback = tryme | args = ["hello", "goodbye"]
callbackTester(tryMe, "hello", "goodbye");
Today you can use ES6 features with transpilers like 6to5 .
+1
source to share