Just when I was starting to become really confident in my abilities as a Javascript programmer, I realize that I have misunderstood one of the fundamentals of the language this whole time.
Here’s a snippet of my broken code:
for (var i = 0; i < developments.length; i++) {
var development = developments[i];
...
GEvent.addListener(marker, 'click', function() {
map.openInfoWindowHtml(point, window.developments.infoHTML(development));
});
}
Can you tell I used to live in C++?
The idea is that I have a list of stuff, each of which gets a marker on a Google Map. Click on a marker and get an info window about the corresponding element in the list.
Instead, I would get an info window for the last element in the list.
This is because Javascript, unlike many programming languages, has no concept of block scope. In the browser, there is basically window (global) scope, and function scope. Declaring “var development = ...” defines that variable the first time it is run, later iterations through the loop simply assign to it.
The fixed code (a la Prototype):
developments.each(function(development) {
...
GEvent.addListener(marker, 'click', function() {
map.openInfoWindowHtml(point, window.developments.infoHTML(development));
});
});

