1

I have the following piece of code:

var i = 0;
for (var anchor in window.globals.html.anchors) {
     var value = window.globals.html.anchors[anchor];
     value.addEventListener('click', function(i) {
          var currData = window.globals.data[i],
              data_clientId = 0;
          if (currData.client_product_id !== undefined) {
              data_clientId = currData.getAttribute('data_clientId');
          } else if (currData.product_id !== undefined) {
              data_clientId = currData.product_id;
          }
          Statistics.send(data_clientId);
          window.open(window.globals.data[i].url, '_blank');
     }(i));
     i++;
}

Which means I want to access global array by interator inside the click event listener. If I don't pass no i to the click event I get the maximum number possible in each iteration, as i would be a global variable.

But right here it seems that all iterations of click events are invoke before clicking anything, onload.

Why is that so, what's wrong?

user99999
  • 1,994
  • 5
  • 24
  • 45
  • Possible duplicate of [Asynchronous Process inside a javascript for loop](http://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop) – Dan Prince Nov 19 '15 at 10:55
  • 1
    Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – James Thorpe Nov 19 '15 at 11:05

1 Answers1

0

Looks like you are calling the handler whilst trying to add it to addEventListener. You need to wrap it in a function thus creating a closure that encapsulates your i variable.

var i = 0;
for (var anchor in window.globals.html.anchors) {
   var value = window.globals.html.anchors[anchor];
   value.addEventListener('click', (function(i) {
     return function() {
        var currData = window.globals.data[i],
            data_clientId = 0;
        if (currData.client_product_id !== undefined) {
            data_clientId = currData.getAttribute('data_clientId');
        } else if (currData.product_id !== undefined) {
            data_clientId = currData.product_id;
        }
        Statistics.send(data_clientId);
        window.open(window.globals.data[i].url, '_blank');
     }
   }(i)));
   i++;
}

Notice now that the function you are passing to addEventListener is invoked immediately and returns a function itself where your variable i is scoped.

tomasbasham
  • 1,695
  • 2
  • 18
  • 37