Thursday, June 5, 2008

Memorise the index for click event in FOR loop

It always course trouble when come to deal with click event in for loop. Let say you got few dom element and you store it in array and you want to traverse all of them and add event listener to it. You wont be able to know which dom you click when it come to use for loop to traverse them.

Here is the solution, we use closure here to solve this problem

//User activities -- switching contents
for (var i = 0; i < tabs.length; i++) {
(function() {
var j = i;
eventObj.addDomListener(
self._tabContainerDoms[j],
'click',
function() {
self._tabContainerDoms[j].style.height = parseInt(self._tabContainerDoms[j].style.height) + 1 + "px";
}
);

})();
}

No comments: