I’ve created a MapObject that is handling my Google Mapping functionality. The object collects all the Markers on the map into an Array. (I’m using the Prototype JS Library.) As the Markers are created their Click event is mapped to a function on the MapObject. Everything works as expected except once I’m in the Click event I can no longer access the Marker that fired the event. If I bind the Marker to the event handler then I can’t access the methods and properties of the MapObject. Here’s some sample code to show what is going on.
MappingObject = Class.create({
initialize: function()
{
try
{
this.geocoder = new google.maps.Geocoder();
this.trucks = $A();
this.truckPic = "Images/TruckIcon.jpg";
}
catch (ex)
{
this.sendToConsole("FAIL! " + ex.toString());
}
},
putTruckOnMapWithLatLong: function(latitude, longitude, title)
{
var marker = this.getNewTruck(this.getNewLatLong(latitude, longitude));
try
{
marker.setTitle(title);
google.maps.event.addListener(marker, "click",
this.truckClickHandler);
this.trucks.push(marker);
}
catch (ex)
{
this.sendToConsole(ex.toString());
}
},
truckClickHandler: function(event)
{
$("dashboardmessage").update(this.getTitle());
this.setIcon("Images/small_smiley.jpeg");
}})
The getNewTruck() function just returns a Google Marker Object. The problem is that the “this” in the truckClickHandler can refer to the MapObject but then I can’t access the marker object. If I bind the marker object like such…
google.maps.event.addListener(marker, "click", this.truckClickHandler.bind(marker));
Then I can’t access the functions in the MapObject anymore. I’d appreciate any help I could get. Thanks!
Okay, for those who are interested I finally figured this out. Prototype has a .curry() method. If I declare my truckClickHandler like this…
And then set it like this…
Then I have access to both the marker object and this refers to my MapObject as expected. Go Prototype!