I’m sure this has to do with scope, but I always seem to struggle with javascript scope.
Anyway here is the code …
var beaches = [
['Surf Spot One', xxxxxx, xxxxxx, 2],
['Surf Spot Two', xxxxxx, xxxxxx, 1],
['Surf Spot Three', xxxxxx, xxxxxx, 3 ]
];
var marker = [];
for (var i = 0; i < beaches.length; i++) {
var pos = new google.maps.LatLng(beaches[i][1], beaches[i][2]);
marker[i] = new google.maps.Marker({
setClickable: 1,
position: pos,
map: map,
icon: surferDude,
title:beaches[i][0]
});
google.maps.event.addListener(marker[i], 'mouseover', function() {
// do something here on mouseover
console.log(i);
});
}
The output in the console on mouseover is always 3? Why is this? I need it to be 1 or 2 or 3 depending on which icon I’m mouseing over.
Yes, it is about scope. When the callback gets called, it will be using the last value of
irather than the value ofiwhen you add the listener. The anonymous function that you’re building is a closure that captures theivariable without evaluating it,iwon’t be evaluated until the callback is called and by that time,iwill be 3.The usual closure busting solution should work:
You could also use a self-executing function instead of a separate
create_listenerbut that might be too noisy.