views:

50

answers:

1

I need to pass extra variables to a jQuery, ajax callback function.

For example, given:

while (K--)
{
    $.get
    (
        "BaseURL" + K,
        function (zData, K) {ProcessData (zData, K); }
    );
}

function ProcessData (zData, K)
{
    console.log (K);
}

ProcessData() will report 0 every time (or whatever the last value of K was).

How do I ensure that ProcessData() fires with, or can get, the correct value of K?

Is there any way to do this without wrapping the $get() in a function?

+4  A: 

No. Because of the ways closures work, all the inner functions will close over the same K variable (which ends up equalling 0). You need an additional level of indirection somewhere to create separate scopes. E.g.:

while (K--)
{
    (function(K)
    {
      $.get
      (
          "BaseURL" + K,
          function (zData, status) {ProcessData (zData, K); }
      );
    })(K);
}

Also, the second parameter of the success function shouldn't be called K. That parameter will get the status, which would then shadow the desired K.

Matthew Flaschen
Thanks for jogging my memory about closures. But, is there another way, maybe a similar mechanism to `bind()`s `eventData` parameter?
Brock Adams