views:

129

answers:

3

Hi, 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");
+1  A: 

If you want something slightly more general, you can use the arguments variable like so:

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

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

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

But otherwise, your example works fine (arguments[0] can be used in place of callback in the tester)

Simon Scarfe
So long as we're being in the spirit of being general, `callback.apply(arguments)` as the function body for `callbackTester` is extensible beyond the two argument scenario.
Steven Xu
sorry, it was a syntax error in the main code, I thought was this because this is the first time I use a callback in JavaScript, you've helped me to understand it wasn't the probelm, and to see a great example.
Vittorio Vittori
+1  A: 

Your question is unclear. If you're asking how you can do this in a simpler way, you should take a look at the ECMAScript 5th edition method .bind(), which is a member of Function.prototype. Using it, you can do something like this:

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

function callbackTester (callback) {
    callback();
}

callbackTester(tryMe.bind(null, "hello", "goodbye"));

You can also use the following code, which adds the method if it isn't available in the current browser:

// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
  Function.prototype.bind = function(){ 
    var fn = this, args = Array.prototype.slice.call(arguments),
        object = args.shift(); 
    return function(){ 
      return fn.apply(object, 
        args.concat(Array.prototype.slice.call(arguments))); 
    }; 
  };
}

Example

bind() - PrototypeJS Documentation

Andy E
Out of interest, what's the difference between `Array.prototype.slice.call(arguments)` and `arguments.slice()`?
sje397
@sje397: *arguments* isn't a \*real\* array, so it doesn't have a *slice()* method. However, the *slice()* method on the *Array.prototype* is intentionally generic, so you can pass any object that has numerical indexes and a *length* property and it will work.
Andy E
Aha. Cheers....
sje397
A: 

This would also work:

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

function callbackTester (callback) { 
    callback(); 
} 

callbackTester (function() {tryMe("hello", "goodbye"); }); 
Marimuthu Madasamy