2009-11-02 5 views
10

mio codiceparametro Passo di callback funzione

// fare richiesta AJAX e ottenere risposta JSON

for (var i = 0; i < data.results.length; i++) { 
    result = data.results[i]; 
    // do stuff and create google maps marker  
    marker = new google.maps.Marker({ 
     position: new google.maps.LatLng(result.lat, result.lng), 
     map: map, 
     id: result.id 
    }); 
    google.maps.event.addListener(marker, 'click', function() { 
     createWindow(marker.id); //<==== this doesn't work because marker always points to the last results when this function is called 
    }); 

} 

Come risolvere questo problema?

risposta

24

Prova questa:

with ({ mark: marker }) { 
    google.maps.event.addListener(mark, 'click', function() { 
     createWindow(mark.id); 
    }); 
} 

Un esempio che dimostra l'uso di with:

for (var i = 0; i < 10; i++) { 
    setTimeout(function() { console.log(i); }, 1000); 
} 

Quanto sopra registrerà 10 dieci volte.

for (var i = 0; i < 10; i++) { 
    with ({ foo: i }) { 
     setTimeout(function() { console.log(foo); }, 1000); 
    } 
} 

Ciò registrerà 0 a 9, come desiderato, grazie ad with introdurre un nuovo ambito.

JavaScript 1.7 ha una dichiarazione let che è più gradevole, ma finché questo è ampiamente supportato, è possibile utilizzare with.

E utilizzare var per le variabili.

4

Il classic closure problem colpisce ancora!

google.maps.event.addListener(marker, 'click', function(id) { 
    return function(){ 
     createWindow(id); //<==== this doesn't work because marker always points to the last results when this function is called 
    } 
    }(marker.id));  
1

provare questo

var marker = new Array(); 
for (var i = 0; i < data.results.length; i++) { 
    result = data.results[i]; 
    // do stuff and create google maps marker  
    marker[i] = new google.maps.Marker({ 
     position: new google.maps.LatLng(result.lat, result.lng), 
     map: map, 
     id: result.id 
    }); 
    google.maps.event.addListener(marker[i], 'click', example(marker[i].id)); 

} 

creare nuova funzione

function example(my_window){ 
    return function(){ 
     createWindow(my_window); 
    } 
}