I am looking to be able to create two functions, BaseFunction and CallbackFunction where BaseFunction takes in a variable set of parameters as such:
BaseFunction(arg1, arg2, ....)
{
//Call the Callback function here
}
and callback function receives the same parameters back:
CallbackFunction(value, arg1, arg2, ...)
{
}
How can I pass the parameters from the base function to the callback function?
I am looking to be able to create two functions, BaseFunction and CallbackFunction where BaseFunction takes in a variable set of parameters as such:
BaseFunction(arg1, arg2, ....)
{
//Call the Callback function here
}
and callback function receives the same parameters back:
CallbackFunction(value, arg1, arg2, ...)
{
}
How can I pass the parameters from the base function to the callback function?
Share asked Apr 4, 2012 at 19:01 mrKmrK 2,2904 gold badges32 silver badges48 bronze badges3 Answers
Reset to default 7Use apply
to call a function with an array of parameters.
BaseFunction(arg1, arg2, ....)
{
// converts arguments to real array
var args = Array.prototype.slice.call(arguments);
var value = 2; // the "value" param of callback
args.unshift(value); // add value to the array with the others
CallbackFunction.apply(null, args); // call the function
}
DEMO: http://jsfiddle/pYUfG/
For more info on the arguments
value, look at mozilla's docs.
to pass arbitrary number of arguments:
function BaseFunction() {
CallbackFunction.apply( {}, Array.prototype.slice.call( arguments ) );
}
This kind of does the trick:
BaseFunction(arg1, arg2, ....)
{
CallbackFunction(value, arguments);
}
However CallbackFunction
needs to accept array:
CallbackFunction(value, argsArray)
{
//...
}