0

I am attempting to create a closure in a loop in order to set an event listener with my iterator value. However, the value in setCookie is not properly being set. What am I doing wrong here?

obj = document.getElementsByClassName("class");
l = obj.length;
i = 0;

function addEv() { 
    while (i < l) {
        obj[i].addEventListener("click", listener.bind(null, i));
        function listener(index) { 
            setCookie("item", index, 24) 
        }
        i++;
    }
}
Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
theOldMan
  • 19
  • 3

1 Answers1

-1

UPDATED ANSWER

On way to capture iterating values is by using immediately invoked functions to capture the value in a closure.

while (i < l) {
  obj[i].addEventListener("click", (function(index) {
    return function(ev) {
      //setCookie("item", index, 24) 
      console.log(index)
    };
  }(i)));
  i++;
}

This example will wrap the iterating i as index.

bvx89
  • 868
  • 5
  • 12
  • Nothing is wrapped here. This only works because you're using the same name `i` for the two counter variables. – Bergi Feb 01 '16 at 23:43
  • Bergi, thanks, working, but dont understand how, hahaha ))) – theOldMan Feb 02 '16 at 01:09
  • @Bergi What do you mean? I only use the `i` for going through the `obj` array in the second loop. For each iteration in the second loop i call the functions inside the `obj`, which has stored all indexes with different values. – bvx89 Feb 02 '16 at 08:46
  • No, the functions in `obj` *don't* have stored any indices. Try to use `for (var j = 0; j < 10; j++) console.log(obj[j]());` instead and see it fail. – Bergi Feb 02 '16 at 08:48
  • Sorry, you're completely correct! Will update answer. – bvx89 Feb 02 '16 at 09:39