On 31.03.2011 17:58, Socrates Vidros wrote:
>
> for( item in queue)
> {
> geocode(item, /function(result,status) { doSomethingWithResults;
> *doSomethingWithItem*;});/
> delay;
> }
>
> The callbackFunction uses results and the item that was geocoded.
>
> But there is a problem with the geocoder's callback function (marked
> with blue) and the closure that is created between the for loop and
> this function. The item in the callback function is always the last
> item of the queue.
>
This is because the item variable is not referenced by value but by
name, i.e. the closure always accesses the same variable in the outer
scope. As the closure is called asynchronously, the item variable might
have changed its value already. You could unbind the scope like so:
function makeCallback(item)
{
return function(result, status)
{
// do something with item etc. here
}
}
for(item in queue) geocode(item, makeCallback(item))
Don't know if this is the best way in JavaScript, but that's how I do
it. JavaScript only knows global and function scopes, no { } scopes!
--
You received this message because you are subscribed to the Google Groups
"Google Maps JavaScript API v3" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/google-maps-js-api-v3?hl=en.