0

Possible Duplicate:
Javascript: closure of loop?

Pseudo javascript:

for (i, i<10, i++) {
  new element.addEvent('click', function(){ alert(i) }).inject(dom)
}

When the loop finishes all the onclick events will trigger alerts with the 'final' value of i. What is the 'correct' way of having them alert the value of i as it was when the onclick event was added?

When I say correct I mean that I'm aware there are several ways of achiving this behavior, but I want to know the standard (ie expected by people that may encounter the code) way. Thanks.

Community
  • 1
  • 1

1 Answers1

3

Use a closure to capture the value of i at each iteration:

for (i; i<10; i++) {
    (function(i) {
         new element.addEvent('click', function(){ alert(i) }).inject(dom);
    }(i));
}
James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 3
    Why the downvote? While it's not valid JavaScript it does answer the question in the same pseudocode-way the OP used. – ThiefMaster Jun 19 '12 at 07:45
  • 1
    I downvoted because he could have closed to vote instead of answering this. Avoiding SO pollution, etc. – Florian Margaine Jun 19 '12 at 07:46
  • @FlorianMargaine - Look at the list of people who closed. I am one of them. While it is a duplicate, I feel it can still be helpful to a new SO user to receive a direct answer. – James Allardice Jun 19 '12 at 07:47
  • 1
    Alright. Removed the downvote :) – Florian Margaine Jun 19 '12 at 07:48
  • While we're here, we might as well use the correct `for` syntax. (what are those commas doing?) – Asherah Jun 19 '12 at 08:37
  • @Len - As noted by ThiefMaster above, I've just reused the OPs semi-pseudo-code from the question. But what is wrong with the `for`? – James Allardice Jun 19 '12 at 08:38
  • So I note. (the issue with the `for is, uh, the lack of initialisation, use of commas instead of semicolons, etc) Anyway, just figured, if you were going to suggest something, might as well suggest the correct thing. – Asherah Jun 19 '12 at 11:13
  • @Len - Haha, yeah sorry, I somehow didn't notice the lack of semi-colons. And you make a good point. I'll edit the answer. But `i` could be declared elsewhere, so I'll leave that out. – James Allardice Jun 19 '12 at 11:25
  • @JamesAllardice: aha! :D This is equivalent to `for (; i<10; i++)`, then. (though you might be wanting to set it to `0` anyway) – Asherah Jun 19 '12 at 12:22