Friday, May 7, 2010

Javascript for loop + closure

This for loop uses closure to get the value of i for every iteration.
Without closure, every element in divvar will get the last value of x(length-1) from iteration.

for( var i=0;i<divvar.length;i++ ) {
(
function(x) { // -> capture looping variable
divvar[x].onclick = function() {
console.debug("clicked:", x);
}
}
)(i); // -> pass in looping variable
}

Compare this to the standar loop without closure

for( var i=0;i<divvar.length;i++ ) {
divvar[i].onclick = function() {
console.debug("clicked:", i);
};
}

Or we can use dojo.forEach to fix this

No comments:

Post a Comment