How can I get around closing javascript?
Consider this small piece 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 of the map.maps object (this is an assistant array). I set the index as button text and set it to warn the index. Obviously, one would expect all buttons to notify its own text when clicked, but instead, all buttons warn the text of the index index in the map.maps object when clicked.
I assume that this behavior is caused by a neat way of handling JavaScript handles, returning and executing functions from closures in which they were created.
The only way I can imagine is to set the index as data on the button object and use it from the click callback. I could also mimic the map.maps indexes in my buttons object and find the correct index when clicked with indexOf , but I prefer the old method.
What I'm looking for in the answers is confirmation that I am doing it right, or a suggestion on how to do it .
Declare closure, do not 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 your var i uses so that it falls into a separate closure, and the value is stored in the local var / param for that closure.
Using a separate function, for example in the case of a lonesomeday response, slightly obscures this closing behavior, but at the same time is much clearer.
for(var i in map.maps){ (function(i){ buttons.push($("<button>").html(i).click(function() { alert(i); })) })(i); } The reason the closure did not complete in your case is because the value is still updated even after the function is bound, which in this case is an event handler. This is because the closure only remembers the references to the variables, and not the actual value when they were connected.
When performing an anonymous function, you can provide the correct value, this is achieved by transferring an anonymous function to me, therefore, inside the anonymous function area, I am redefined.
This is the most elegant way to do what you are trying to do:
var buttons = myCharts.map(function(chart,i) { return $("<button>").html(chart).click(function(event){ alert(chart); }); } You need code closure for elegant coding in javascript and shouldn't work around them. Or you can't do things like nested for loops (without scary hacks). When you need to close, use closure. Do not be afraid to define new functions within functions.