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.

Liam
  • 27,717
  • 28
  • 128
  • 190
Pavel Tarno
  • 1,324
  • 1
  • 12
  • 29
  • I found an answer here http://stackoverflow.com/questions/13199231/scope-in-an-ajax-callback-function , basically, you can pass the arguments just as the scope of the manager is passed to the onsuccess function. – Krystian Laskowski Jul 20 '15 at 08:20

3 Answers3

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

Liam
  • 27,717
  • 28
  • 128
  • 190
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.

xyz
  • 3,349
  • 1
  • 23
  • 29
1
  1. Define onsuccess as local function in manager, it may use its arguments and local variables.
  2. Pass onsuccess to httpGet.
Pavel Gatnar
  • 3,987
  • 2
  • 19
  • 29