Florin
Florin

Reputation: 21

How to pass function parameter inside named callback

Having the following code:

 var test1 = function(param){
    verify(callback);
}

var callback = function(){
    console.log(param);
}

var verify = function(inside){
   inside();
}

test1('I am the param');

how can I make available value of param inside the callback, so the console output would be 'I am the param';

If, instead of using callback I use an anonymous function, it works:

var test1 = function(param){
    verify(function(){
        console.log(param);
    });
}

var verify = function(inside){
   inside();
}

test1('I am the param');

Upvotes: 0

Views: 37

Answers (2)

Rahul Desai
Rahul Desai

Reputation: 15501

The problem is that the callback function does not know the value of param.

You can fix it by passing the param separately.

var test1 = function(param1){
  verify(callback, param1);
}

var callback = function(param3){
  console.log(param3);
}

var verify = function(inside, param2){
  inside(param2);
}

test1('I am the param');

Upvotes: 2

adrianj98
adrianj98

Reputation: 573

I would do a decorator for the callback that returns a function. It is a bit hard to find a solution out of context. But I will try an example

var test1 = function(param){
   verify(callback(param));
}

var callback = function(param){
    return function(){
         console.log(param);
     }
}

var verify = function(inside){
   inside();
}

test1('I am the param');

Upvotes: 1

Related Questions