Possible Duplicate:
How to pass values to a callback function at the time of the request call?
I know this is a general problem and not only in node.js. I have to pass a variable from the for loop to a function which I want to generate. The functions are stored in an array and have to remember these variables.
Here is my example:
for(var i = 0; i < administratorIds.length; i ++){
adminCallbacks[adminCallbacks.length] = function(callback){
model_user.getById(administratorIds[i], function(user){
administrators[administrators.length] = {name: user.getName()};
callback(null, null);
});
};
}
You need to create a new variable scope for each iteration of the loop.
Only way to do that will be by invoking a function.
for(var i = 0; i < administratorIds.length; i++){
adminCallbacks[adminCallbacks.length] = createHandler(i); // pass i
}
// receive i as j-----v
function createHandler(j) {
// return a function...
return function(callback){
// ...that uses j-----------------v
model_user.getById(administratorIds[j], function(user){
administrators[administrators.length] = {name: user.getName()};
callback(null, null);
});
};
}
a closure perhaps?
for(var i = 0; i < administratorIds.length; i ++){
adminCallbacks.push(
(function(i){
return function(callback){
model_user.getById(
administratorIds[i],
function(user){
administrators[administrators.length] = {name: user.getName()};
callback(null, null);
}
);
};
})(i)
);
}
Yikes... look at that madness. Anyway, this part:
(function(i){
// stuff!
})(i);
captures the current value for i in a closure and thus ensures that it doesn't change once the callback is fired.
An example:
var i = 10;
var lockedI = (function(i){
return function(){ console.log('i is --> ' + i); };
})(i);
var unlockedI = function(){ console.log('i is --> ' + i); };
lockedI();
// i is --> 10
unlockedI();
// i is --> 10
var i = 666;
lockedI();
// i is --> 10;
unlockedI();
// i is --> 666
Victory?