Passing a parameter to a callback function
I need 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);
However, that doesn't sound like a great idea. Is there a better way?
source to share
There are several methods you can use to do this. One of them is to create a new function that "seals" 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);
}
The context is the object for which "this" will be referenced in the callback function. This may or may not be needed for what you are doing; if not, you can just pass null.
There is actually a function that does exactly what is called bind and is used like
var curriedFunc = myCallback.bind(this, i), which will seal off the first variable.
source to share
It looks like you are having problems with closing i
, and eval is used to solve this problem. Instead, just close it using an Immediately Callable Function (IIFE) expression 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
source to share