Coder Perfect

Passing parameters to a callback function in JavaScript

Problem

I’m trying to provide an argument to a callback function, but I’m not sure how to accomplish so.

This is my attempt:

Asked by vitto

Solution #1

If you need something a little more generic, use the arguments variable as follows:

Your example, on the other hand, works perfectly (arguments[0] can be used in place of callback in the tester)

Answered by Simon Scarfe

Solution #2

This could also be used:

Another Scenario :

Answered by Marimuthu Madasamy

Solution #3

Your query is not clear. If you’re looking for a simpler way to accomplish this, check out the ECMAScript 5th edition technique. Function.prototype has a member called bind(). You can do things like this with it:

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

function callbackTester (callback) {
    callback();
}

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

If the method isn’t available in the current browser, you can use the following code to add it:

// 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

Documentation for bind() in PrototypeJS

Answered by Andy E

Solution #4

Use the apply function if you’re not sure how many parameters you’ll be passing into callback functions.

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

function callbackTester(callback,params){
    callback.apply(this,params);
}

callbackTester(tryMe,['hello','goodbye']);

Answered by Zeeman Chen

Solution #5

When you have a callback that will be called by something other than your code and you want to pass in additional params, you may pass a wrapper function as the callback and pass the additional params within the wrapper (s).

function login(accessedViaPopup) {
    //pass FB.login a call back function wrapper that will accept the
    //response param and then call my "real" callback with the additional param
    FB.login(function(response){
        fb_login_callback(response,accessedViaPopup);
    });
}

//handles respone from fb login call
function fb_login_callback(response, accessedViaPopup) {
    //do stuff
}

Answered by Blake Mills

Post is based on https://stackoverflow.com/questions/3458553/javascript-passing-parameters-to-a-callback-function