I am sure this is a simple question but have not been able to figure this out. The below shows a function that is created and added to a google map marker on the mousedown event. This is created for each marker iterated through.
The part eluding me is on line 5 below the pickupVenue(data[i].id) the value submitted in this function call is always the last iterated value. I want to stick a static value there of what I am iterating through when creating each marker.
for (i in data) {
google.maps.event.addListener(marker, 'mousedown', function() {
state = PINCH;
map.setOptions({draggable: false});
timeoutId = setTimeout(function() { pickupVenue(data[i].id) }, 1000);
});
}
—- working result —-
google.maps.event.addListener(marker, 'mousedown', pickupMarker(data[i].Listing.id));
function pickupMarker(id) {
return function() {
state = PINCH;
map.setOptions({draggable: false});
timeoutId = setTimeout('pickupVenue('+id+')', 1000);
}
}
You need to make sure the function you pass as the event listener has a variable in its scope that references the value that
iheld in the loop without being modifiedibeing modified.Currently all the functions you’re creating in the loop are sharing the same
ivariable, so they’ll all end up getting whatever valueireferences when the handler is finally invoked.In JavaScript, the only way to create a new variable scope is to invoke a function, and create a local variable (or parameter) in that function that references the value you want.
Like this:
Here I created a
createListener()function, and passediinto it.Because your listener function is now being created inside the
createListener()function, that listener will reference theiin that variable scope, which will continue to retain whatever value it was given when you invokedcreateListener()(unless your function modifiesi).Then
createListener()returns that listener function, which is passed as the third argument toaddListener().