Saturday 29 April 2017

jquery - How can I work around the Javascript closures?



Consider this small snippet of JavaScript:



for(var i in map.maps)
{
buttons.push($("



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.


Answer



Embrace the closures, don't work around them.




for(var i in map.maps)
{
(function(i){
buttons.push($("


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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...