0

I'm trying to find the best practice of implementing the following:
I have 3 functions: manager, httpGet and onsuccess:

  1. manager calls the httpGet function and passes the onsuccess function to be called upon success.

  2. httpGet makes a request and invokes onsuccesss

  3. onsuccess uses needs params from manager

What is the best way to pass and argument from manager to onsuccess without involving httGet?
I was thinking about passing a params object to httpGet which in turn will be passed to onsuccess but I really don't like the idea of passing params to a function that doesn't use them at all.

1

3 Answers 3

1

You mean something like this:

function manager()
{
   var managerParam =0;
   //the anonymous function below is in the scope of manager() so has
   //access to all of managers parameters
   httpGet(function() {
      //this function can use managerParam
      managerParam ++;
   });

  console.log(managerParam === 1); //true
}

function httpGet(onsuccess)
{
   onsuccess();
}

Fiddle

1

Use a closure:

data = { cool: true };
var yourCallbackFunction = function(httpData, notHttpData){};

var bakedCallback = (function() {
    var _data = data;
    return function(httpResp) {
        yourCallbackFunction(httpResp, _data);
    }
})();
httpGet.onSuccess(bakedCallback);

data is the extra data you want to pass to the function.

In your callback: httpData is the data received from request. NOThttpData is the extra data.

1
  1. Define onsuccess as local function in manager, it may use its arguments and local variables.
  2. Pass onsuccess to httpGet.

Not the answer you're looking for? Browse other questions tagged or ask your own question.