0

I read that one can use closures for addEventListener in loops (addEventListener using for loop and passing values).

However, this method does not work with a more complex example:

function f(fevent) {
  var a = document.createElement('a');
  a.innerHTML = 'Test';
  a.href = '#';
  a.addEventListener('click', fevent);
  return a;
};

for (l = 0; l < 2; l += 1) {
  for (h = 0; h < 2; h += 1) {
    document.body.appendChild(
    f(function() {alert(l+','+h);})
    );
  }
}

https://jsfiddle.net/yasnujzq/

Edit: I want is that the click event on the anchors to alert different combinations (0,0), (1,0), (0,1), and (1,1). But it always alerts (2,2).

Here is what I tried with the closure method from above:

function f(fevent) {
  var a = document.createElement('a');
  a.innerHTML = 'Test';
  a.href = '#';
  a.addEventListener('click', fevent);
  return a;
};

for (l = 0; l < 2; l += 1) {
  for (h = 0; h < 2; h += 1) {
    (function() {
                document.body.appendChild(
                f(function() {alert(l+','+h);})
                );
    }());
  }

https://jsfiddle.net/72sg8d5n/

I also tried to add arguments to the closure:

function f(fevent) {
  var a = document.createElement('a');
  a.innerHTML = 'Test';
  a.href = '#';
  a.addEventListener('click', fevent);
  return a;
};

for (l = 0; l < 2; l += 1) {
  for (h = 0; h < 2; h += 1) {
    (function() {
                document.body.appendChild(
                f(function() {alert(l+','+h);})
                );
    }(l,h));
  }
}

https://jsfiddle.net/wxodr8p6/

Maybe someone can enlighten me on this.

Edit: Here is a working fiddle with the method from the accepted solution below:

https://jsfiddle.net/87zp4dkr/

Community
  • 1
  • 1
Daniel
  • 3,383
  • 4
  • 30
  • 61

1 Answers1

3
(function() {
            document.body.appendChild(
            f(function() {alert(l+','+h);})
            );
}(l,h));

On the last line of this code you are passing the function two arguments.

On the first line, you are not accepting any arguments.

You don't use the values you pass to that function, you are still using the ones from the loop (which change each time the loop goes around).

(function(my_l, my_h) {
            document.body.appendChild(
            f(function() {alert(my_l+','+my_h);})
            );
}(l,h));
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Great. I guess I got confused from the closure solution I quoted above since it does not take any variables. I'll add a bit more story to my question. – Daniel Jan 18 '16 at 10:25