Skip to content Skip to sidebar Skip to footer

Calling Event Listeners - One Of Two Ways Works, What's The Differnce?

This way does not work (elements are pulled in from with in the function ). function styleTwitter1( pair_array ) { var i; var input; var label;

Solution 1:

You have a closure problem. The handlers make a closure on the variable label. However, by the time the loop has finished, label will be the last element - All your handlers will treat label as the last element when they fire.

Solution 2:

I call it freezing a closure variable, basically by using a self calling function which creates a new closure that is not shared.

var divs = [...];
for (var i=0; i < 10; i++) {
  // Here's the self calling function
  div.onclick = (function(i){
    returnfunction() {
      console.log("Clicked div with index" + i);
    }
  })(i);// Passing the variable to the self calling function creating a new closure 
}

My preferred way, however, is to use https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

var divs = [...];
for (var i=0; i < 10; i++) {
  div.onclick = (function(i) {
      console.log("Clicked div with index" + i + "and id" + this.id );
    }
  }).bind(div, i);
}

Post a Comment for "Calling Event Listeners - One Of Two Ways Works, What's The Differnce?"