3

I needed to pass a parameter to a callback function in Javascript, so I did the following which creates an anonymous function as a string and then passes it:

var f = "var r = function(result) {do_render(" + i + ",result.name,result.data);}"
eval(f)
$.getJSON("analysis?file=" + getParameterByName('file') + "&step=" + i,r);

This doesn't seem like a great idea however. Is there a better way?

new299
  • 804
  • 1
  • 7
  • 17

3 Answers3

1

There's several techniques that you can use to do this. One of which is to create a new function which "seals off" one of the variables:

function myCallback(i, result) { ... }

function createCurriedFunction(i, func, context) {
  return function (result) { func.call(context, i, result); }
}

for (i = 0; i < 5; i += 1) {
  var curriedFunc = createCurriedFuncion(i, myCallback, this);
  $.getJSON(url, curriedFunc);
}

Context is the object for which the "this" will refer to in the callback function. This may or may not be needed for what you're doing; if not you can just pass in null.

There's actually a function that does exactly that called bind, and is used like

var curriedFunc = myCallback.bind(this, i), which will seal off the first variable.
Jim Pedid
  • 2,730
  • 3
  • 23
  • 27
0

It looks like you are having issues closing over i and to solve it used eval. Instead of that, simply close over it using an immediately invoked function expression (IIFE) like this:

(function(i){
    //create a closure of the value of i
    //so that it takes the immediate value of it instead of the end value
    //based on the assumption i is from a loop iterator
    $.getJSON("analysis?file=" + getParameterByName('file') + "&step=" + i,
        function(result){
            do_render(i, result.name, result.data); 
        }
    );
})(i);//pass i into the IIFE in order to save its immediate value
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

You can simply do

var url = "myurl";
$.getJSON(url, function(result){
    //callback function
});
Ashish Bhagat
  • 409
  • 3
  • 16