[Greasemonkey] Re: addEventListener inside loop

(David *)Frenkiel dfl.proxy at gmail.com
Sun Feb 5 20:31:07 EST 2006


Daniel Hood wrote:
===
From: Daniel Hood <danhood at gmail.com>
Subject: [Greasemonkey] addEventListener inside loop

unction do_stuff() {
   for(i = 1; i <= 3; i++) {
       document.getElementById("button" +
i).addEventListener("click", function() { alert(i); }, false);
   }
}
===

The problem with this, as pointed out earlier, is that the value of i in all
the listener functions is 3, because this is its state in the closure.

Arvid Jakobsson wrote:
===
This is how i would do it, but i can't say if it's a good way or not:

function foo(i) {
   return function () {
      alert(i);
   }
}

function do_stuff() {
   for(i = 1; i <= 3; i++) {
       var button = document.getElementById("button" + i);
       button.addEventListener("click", foo(i), false);
   }
}
====

I don't see how this can work, since (afaik) event listeners have a fixed
interface, so you can't just stuff parameters into their calls. When foo
will be called as an event callback, it will receive an event structure as
the first parameter.

The I handle such situations, is to stick the required value right into the
function.

for (var i = 0; i < x; i++) {
// sorry, no indentation
var f = function() {
// obtain the value of i:
var caller_i = arguments.callee.param_i;
// do stuff
}
f.param_i = i;
// button = something
button.addEventListener('click', f, false);
}


More information about the Greasemonkey mailing list