Passare parametro callback funzione
-
12-09-2019 - |
Domanda
Il mio codice
// 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?
Soluzione
Prova questo:
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);
}
È possibile che questo sarà il login 10
dieci volte.
for (var i = 0; i < 10; i++) {
with ({ foo: i }) {
setTimeout(function() { console.log(foo); }, 1000);
}
}
Questa registrerà 0
a 9
, come desiderato, grazie ad with
introduzione di un nuovo ambito.
JavaScript 1.7 ha una dichiarazione let
che è più bello, ma fino a che è ampiamente supportato, è possibile utilizzare with
.
E utilizzare var
per le variabili.
Altri suggerimenti
Il classica chiusura problema ancora scioperi!
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));
Sembra che hai un problema di chiusura. Vedere queste domande:
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);
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow