I don't quite understand why the following works but not its commented
out version:
http://pastebin.com/qTkevTYg
I'll attempt an explanation below, but first, you should realize that
on USENET, it's considered good form to post sample code in your
message and not just a link. Some people don't have access to the
linked site when they're reading. A link is fine for additional
details, but there should be a minimal example inline. To that end,
here's an abbreviated portion of the posted code:
This is not working as expected:
for (i in coords) {
// create latlng
var marker = new GMarker(latlng);
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(i);
});
map.addOverlay(marker);
}
This is working as expected:
function createMarker(latlng, number) {
var marker = new GMarker(latlng);
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(number);
});
return marker;
}
for (i in coords) {
// create latlng
map.addOverlay(createMarker(latlng, i));
}
You definitely made a step in the right direction when you used
"closures" in your title. Your issue is a common one with loop
variables and closures.
I won't try to describe closures in any detail. The first few links
in a Google search of "javascript closures" are usually quite good.
And the FAQ for this group contains Richard Cornford's excellent
reference page on closures [1], although it's not aimed at novices.
The main point of a closure is that an inner function allowed to
escape from an outer function has access to all the local variables,
parameters, and inner functions of the outer function, even after the
outer function has completed. They have access to the current state
of the local variables, not the state they had when the inner function
was created. So in your first example, when this line is eventually
called:
marker.openInfoWindowHtml(i);
it has access to the current state of the variable `i`, which would
presumably be the last element in the iteration over `coords`.
In your second example, the closure contains the local variables and
parameters of your call to `createMarker`. But that call was made
with a particular value for `i`, which was stored as `number` in the
closure. (The name is not important. The same would work if you
reused `i` instead of using `number`; it's that it is a parameter of
the function captured by the closure.)
A simple way to avoid these problems is not to use loop variables in
any inner functions that might escape the current function.
[1] FAQ closure article: <
http://jibbering.com/faq/notes/closures/>