Inline function and global variable issue in Javascript
I have some code here : http://bitbucket.org/natim/lo53_tp1/src/tip/part3/camions/medias/js/tracking.js
That I use to draw some information about trucks direction.
The problem come from a function defined in a for loop like this one :
...
for(i = 0; i < nb_trucks; i++)
{
...
contentString = '<div id="content">'+ trucks[i]['name'] + '</div>';
current_window = new google.maps.InfoWindow({
content: contentString
});
infosWindow.push(current_window);
current_marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(trucks[i]['end']['lat'], trucks[i]['end']['lon']),
draggable: false,
title: trucks[i]['name']
});
markers.push(c开发者_如何学Gourrent_marker);
google.maps.event.addListener(current_marker, 'click', function() {
current_window.open(map, current_marker);
});
}
In this code, you can see the last block
google.maps.event.addListener(current_marker, 'click', function() {
current_window.open(map, current_marker);
});
And my problem is that current_marker in the addListener parameters is different from the one inside the function.
The current_window and the current_marker inside the function is overide at each loop turn.
How can I get it right ?
Thanks
Wrap it in a closure (just this little section, no other changes) so you get the variable you want, like this:
(function(marker) { //a copy is passed, accessible as marker inside this function
google.maps.event.addListener(marker, 'click', function() {
current_window.open(map, marker);
});
})(current_marker); //pass in the current value
This doesn't reference the same variable that's changing every loop, a copy of it is passed into the closure, so each time you run this it gets a copy of what current_marker
is that that time passed in. If you're more curious about this, there are some great answers explaining closures in this question.
精彩评论