2009-11-02 23 views
10

mi códigoparámetro Pass para devolución de llamada función

// 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?

Respuesta

24

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 registrará 10 diez veces.

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

Esto registrará 0-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 sea ampliamente compatible, puede usar with.

Y use var para sus variables.

4

¡El classic closure problem 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));  
1

prueba este

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 nueva función

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