Arian
Arian

Reputation: 7719

Passing parameter to a callback which is passed as parameter

In the following code:

makeComponent: function(componentBuilder, myLib) {
  componentBuilder.build(function(cmpDefinition, status){
    if (status === 'OK') {
      myLib.doSomething(cmpDefinition);
    }
  });
}

I want to put the inner callback function in a separate function:

callBackFunc: function(myLib) {
   return function(cmpDefinition, status) {
        if (status === 'OK') {
          myLib.doSomething(cmpDefinition);
        }
   }
}

makeComponent: function(componentBuilder, myLib) {
  var callBackFuncVar = callBackFunc(myLib);
  componentBuilder.build(callBackFuncVar(cmpDefinition, status));
}

This code doesn't work, I need to change makeComponent function to the following:

makeComponent: function(componentBuilder, myLib) {
  var callBackFuncVar = callBackFunc(myLib);
  componentBuilder.build(function(cmpDefinition, status) {
       callBackFuncVar(cmpDefinition, status)      
  });
}

Why directly calling callBackFuncVar and passing parameter to it, as mentioned, doesn't work ?

Edited

What if I do this:

callBackFunc: function(cmpDefinition, status) {
        var myLib = this.myLib;
        if (status === 'OK') {
          myLib.doSomething(cmpDefinition);
        }
   }

makeComponent: function(componentBuilder, myLib) {
  componentBuilder.build(callBackFunc.bind(this));
}

Upvotes: 1

Views: 38

Answers (1)

lilezek
lilezek

Reputation: 7344

You should be doing this:

callBackFunc: function(myLib) {
   return function(cmpDefinition, status) {
        if (status === 'OK') {
          myLib.doSomething(cmpDefinition);
        }
   }
}

makeComponent: function(componentBuilder, myLib) {
  var callBackFuncVar = callBackFunc(myLib);
  componentBuilder.build(callBackFuncVar);
}

The reasoning behind this is that componentBuilder.build was receiving a function in the first example and the result of callBackFuncVar in the second one, instead of the callBackFuncVar function.

Upvotes: 1

Related Questions