Skip to content Skip to sidebar Skip to footer

Addeventlistener Pass Caller As Argument

I have the following code. And my problem is that when clicking, the event is firing but the argument passed is not the correct one. It is passing the last dynamically created row

Solution 1:

i in the function(){handleRowClick(i);} is the loop variable i. When the function gets called, the loop is long-finished and i holds the last value it did at the end of the loop, not the value it held when you created the function(){}.

This is the closure loop problem. See this question for solutions using either closures or Function#bind:

row.addEventListener('click', handleRowClick.bind(window, i), false);

However, you're not really using that i at the moment. It would be easier to say:

row.addEventListener('click', handleRowClick, false);

and then use this to retrieve the row:

functionhandleRowClick(){
    window.open(this.cells[1].innerHTML);
}

(Side note: unfortunately if you add attachEvent backup in order to support IE<=8, it doesn't get this right, so you'd still be looking at closures/bind to get the object you want.)

also:

for(i =0; i<dataStructure.length; i++){

Missing var: i is an accidental global.

        row.setAttribute('id', i);

Avoid getAttribute/setAttribute in HTML documents. They don't do what they should in IE. Use the DOM Level 2 HTML properties instead, they're more reliable and more readable: row.id= i.

Post a Comment for "Addeventlistener Pass Caller As Argument"