I'm trying to pass some parameter to a function used as callback, how can I do that?
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}
function callbackTester (callback, param1, param2) {
callback (param1, param2);
}
callbackTester (tryMe, "hello", "goodbye");
This would also work:
Another Scenario :
Use curried function as in this simple example.
If you want something slightly more general, you can use the arguments variable like so:
But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)
Wrap the 'child' function(s) being passed as/with arguments within function wrappers to prevent them being evaluated when the 'parent' function is called.
When you have a callback that will be called by something other than your code with a specific number of params and you want to pass in additional params you can pass a wrapper function as the callback and inside the wrapper pass the additional param(s).
A new version for the scenario where the callback will be called by some other function, not your own code, and you want to add additional parameters.
For example, let's pretend that you have a lot of nested calls with success and error callbacks. I will use angular promises for this example but any javascript code with callbacks would be the same for the purpose.
Now you may want to unclutter your code by defining a function to log errors, keeping the origin of the error for debugging purposes. This is how you would proceed to refactor your code:
The calling function will still add the error parameter after your callback function parameters.