Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closures in a for loop

Closures in a loop are causing me problems. I think I have to make another function that returns a function to solve the problem, but I can't get it to work with my jQuery code.

Here is the basic problem in a simplified form:

function foo(val) {
  alert(val);
}

for (var i = 0; i < 3; i++) {
  $('#button'+i).click(function(){
    foo(i);
  });
}

Naturally clicking on any of the three buttons will give an alert saying 3. The functionality I want is that clicking on button 1 will give an alert saying 1, button 2 will say 2 etc.

How can I make it do that?

like image 977
Rob Avatar asked Feb 03 '10 13:02

Rob


1 Answers

See the bind method.

$('#button'+i).bind('click', {button: i}, function(event) {
  foo(event.data.button);
});

From the docs:

The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures

like image 199
Andy E Avatar answered Nov 11 '22 07:11

Andy E