I don't know if there is a term for the thing i ask about, so i'll try to illustrate it:
I Got a function that takes an array of contacts, and loop them through to update their status on the website. The 'something.getStatus' function does not return anything, but upon successful completion, it gives the status (online/offline/etc.) of the user.
The problem here is, when the function inside is called, the variable user_id is the last one in the array for all the function calls, making it impossible to know how have what status.
function gotGroupContacts(contacts) {
for ( i = 0; i < contacts.length; i++) {
var user_id = contacts[i];
something.getStatus(user_id, function(resp) {
updateLinkStatus(user_id, resp.status, resp.statusMessage);
}, getStatusErrorHandler);
}
}
Is there any way i can 'lock' the variable, or otherwise pass it to the function within?
enclose your getStatus
method call in a closure, like so
for ( i = 0; i < contacts.length; i++) {
var user_id = contacts[i];
(function(uid) {
something.getStatus(uid, function(resp) {
updateLinkStatus(uid, resp.status, resp.statusMessage);
}, getStatusErrorHandler);
}(user_id))
}
user_id
is passed into the anonymous self-executed function, and this ensure to have the right value