Reputation: 135
I have a class in jQuery that handles a google map and its markers. After each marker creation, i add a click listener for each marker :
var marker = new google.maps.Marker(options);
google.maps.event.addListener(marker, "click", function(event) {
//Do something with event
});
However, i would like to use a function from the class instead :
google.maps.event.addListener(marker, "click", this.onVehiculeClick.bind(this));
onVehiculeClick: function(event) {
console.log(this);
console.log(event);
//Do something with event
}
It is working well on firefox and chrome : it's logging this (my object) and the google map event. But not in Safari or IE (and also on some other versions of Firefox) : it is not calling the onVehiculeClick method and if i add a console.log right after the google.maps.event.addListener, nothing is output.
If i remove the .bind(this) part, the method is called but i lose the this context and this will stand for the google map object. I also tried to add a var that = this in the constructor but it is undefined in the method context.
I found something that i think might help me here : Google Maps JS API v3: Need to access Marker Object from inside the Event Handler but it's using prototype and i can't find any equivalent of the curry method in jQuery.
Thanks for your help !
Upvotes: 0
Views: 2651
Reputation: 1891
Try changing your addVehicule method to this:
addVehicule: function(vehicule) {
try {
var marker = this.addMarker(vehicule.latitude, vehicule.longitude);
var that = this;
//Observe clicks on vehicule
google.maps.event.addListener(marker, "click", function(event){
that.onVehiculeClick(event)
});
this.vehicules.push(vehicule);
} catch (error) {}
}
Upvotes: 1