Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I work around the Javascript closures?

Consider this small snippet of JavaScript:

for(var i in map.maps)
{
    buttons.push($("<button>").html(i).click(function() { alert(i); }));
}

It creates one button for each of the fields in the map.maps object (It's an assoc array). I set the index as the button's text and set it to alert the index as well. Obviously one would expect all the buttons to alert it's own text when clicked, but instead all the buttons alert the text of the final index in the map.maps object when clicked.

I assume this behavior is caused by the neat way JavaScript handles closures, going back and executing functions from the closures in which they were created.

The only way I can imagine getting around this is setting the index as data on the button object and using it from the click callback. I could also mimic the map.maps indices in my buttons object and find the correct index on click using indexOf, but I prefer the former method.

What I'm looking for in answers is confirmation that I'm doing it the right way, or a suggestion as to how I should do it.

like image 679
Hubro Avatar asked Jun 06 '11 09:06

Hubro


3 Answers

Embrace the closures, don't work around them.

for(var i in map.maps)
{
    (function(i){
        buttons.push($("<button>").html(i).click(function() { alert(i); }));
    })(i);
}

You need to wrap the code that uses your var i so that it ends up in a separate closure and the value is kept in a local var/param for that closure.

Using a separate function like in lonesomeday's answer hides this closure behaviour a little, but is at the same time much clearer.

like image 76
Mario Menger Avatar answered Oct 30 '22 04:10

Mario Menger


for(var i in map.maps){
    (function(i){
         buttons.push($("<button>").html(i).click(function() { alert(i); }))
    })(i);
}

The cause why the closure failed in your case is that it's value still updated even after the function is bound, which is in this case is the event handler. This due to the fact that closure only remember references to variables and not the actual value when they were bound.

With executed anonymous function you can enforce the correct value, this achieved by passing i to the anonymous function, so then inside the scope of anonymous function i is defined anew.

like image 40
Habib Rosyad Avatar answered Oct 30 '22 02:10

Habib Rosyad


If you pass the changing value to another function as a parameter, the value will be locked in:

function createButton(name) {
    return $("<button>").html(name).click(function() { alert(name); });
}

for (var i in map.maps) {
    buttons.push(createButton(i));
}
like image 22
lonesomeday Avatar answered Oct 30 '22 03:10

lonesomeday