Pasar parámetro para devolución de llamada función
-
12-09-2019 - |
Pregunta
Mi código
// hacer petición AJAX y obtener respuesta 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
});
}
¿Cómo resolver esto?
Solución
Prueba esto:
with ({ mark: marker }) {
google.maps.event.addListener(mark, 'click', function() {
createWindow(mark.id);
});
}
Un ejemplo que demuestra el uso de with
:
for (var i = 0; i < 10; i++) {
setTimeout(function() { console.log(i); }, 1000);
}
Lo anterior log 10
diez veces.
for (var i = 0; i < 10; i++) {
with ({ foo: i }) {
setTimeout(function() { console.log(foo); }, 1000);
}
}
Esto log 0
a 9
, según se desee, gracias a with
introducción de un nuevo ámbito de aplicación.
JavaScript 1.7 tiene una declaración let
que es más agradable, pero hasta que se apoya ampliamente, puede utilizar with
.
Y el uso de var
para sus variables.
Otros consejos
El cierre clásica problema ataca de nuevo!
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));
Parece que tienes un problema de cierre. Ver estas preguntas:
intente éste
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));
}
crear una nueva función
function example(my_window){
return function(){
createWindow(my_window);
}
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow