Tuesday 6 December 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...