bethesdaboys
bethesdaboys

Reputation: 1827

Passing parameter in callback

I would like to be able to pass a parameter in a callback, but from the original calling function, and with the stipulation below, e.g. given:

function foo() {
  var p = 5;
  getDataFromServer(callBackFunction);
}

function callBackFunction(data) {
  // I need value of 'p' here
  ...
}

function getDataFromServer(callback) {
  // gets data from server
  callback.call();
}

The catch is that I don't want to change the function getDataFromServer(), (i.e. allowing it to accept another parameter.)

Is this possible? Thanks.

Upvotes: 1

Views: 142

Answers (4)

neo
neo

Reputation: 11

So a simple anon function won't do?

function foo() 
{ 
   var p = 5;

   getDataFromServer( function() 
                      {
                          callBackFunction( p ); 
                      } );
}

Upvotes: 1

JohnnyK
JohnnyK

Reputation: 1102

It's Definitely possible and I would say good practice with functional programming languages. But you call the function like this:

function getDataFromServer(callback) {
  // gets data from server
  callback();
}

Upvotes: 0

airportyh
airportyh

Reputation: 22668

Yes, and this is good to know.

function foo() {
  var p = 5;
  getDataFromServer(function(){
     callBackFunction(p)
  });
}

Upvotes: 2

Matt Fenwick
Matt Fenwick

Reputation: 49085

Yes, you could use a closure to do this.

However, it's hard to give code for this because your example isn't clear.

My guess is that you want something like this:

function foo() {
  var p = 5;
  getDataFromServer(callBackFunction(p));
}

function callBackFunction(p) {
  var closureOverP = function(data) {... something with p ...};
  return closureOverP;
}

Upvotes: 2

Related Questions