Tuesday, August 9, 2016

closure usage in javascript

This is bad source all nodes are show "nodes.length-1" when you click any node

var add_the_handler = function (nodes){
 var i;
 for(i=0; i<nodes.length; i+=1){
  nodes[i].onclick = function(e){
   alert(i);
  }
 }
}

this is a good pattern compared to above function

var add_the_handler = function (nodes){
 var i;
 for(i=0; i<nodes.length; i+=1){
  nodes[i].onclick = function(i){
   return function(e){
    alert(i)
   };
  }(i)
 }
}

No comments:

Post a Comment