</div>
</div>
<div class="grid--cell mb0 mt8">Closed <span title="2012-11-26 03:09:50Z" class="relativetime">7 years ago</span>.</div>
</div>
</aside>
Possible Duplicate:
Javascript closure inside loops - simple practical example
Let's imagine you create some ajax requests in a for-loop like this:
$(function(){
for(var i=0;i<10;i++){
$.ajax({
url : '/',
success : function(){
console.log('callback '+i+' fired!');
}
});
}
});
Of course, the callback will log 'callback 10 fired' every time because the callbacks are executed asynchronous. The question is: how can you know which callback fired?
</div>
Anonymous self-invoked function will solve this closure issue:
$(function(){
for(var i=0;i<10;i++){
(function(i) {
$.ajax({
url : '/',
success : function(){
console.log('callback '+i+' fired!');
}
});
})(i);
}
});
By passing the current value of i
as part of a closure:
$(function(){
for(var i=0;i<10;i++){
$.ajax({
url : '/',
success : (function(i){
return function(){console.log('callback '+i+' fired!');}
})(i)
});
}
});
Here is a demo: http://jsfiddle.net/rRwgW/4/
Note: you don't actually need to wrap the entire ajax call in an IIFE, just the callback that needs to refer to the value of i
.
create a scope with an immediately invoked function expression:
$(function(){
for(var i=0;i<10;i++){
(function(i){
$.ajax({
url : '/',
success : function(){
console.log('callback '+i+' fired!');
}
});
})(i);
}
});