Tuesday, August 28, 2018

javascript - addEventListener, for(), index. how to use closure?




I have this code:



var items = this.llistat.getElementsByTagName('a');

for( var i = 0; i < items.length; i++ ){
items[i].addEventListener('click', function(event) {

alert( i );
}, items[i]);
}


where the event is listened, but there are 3 items and the alert allways print 3 on any of the elements (it doesn't respect the index),



Dosen't items[i] shouldn't do the job as closure?



thanks!



Answer



That's a classical closure issue : you must create a new function bound, not to the 'i' variable, but to its value at the time of binding :



var items = this.llistat.getElementsByTagName('a');

for( var i = 0; i < items.length; i++ ) {
items[i].addEventListener('click', listener.bind( null, i) );
}

function listener(index) {

alert(index);
}

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...