user472875
user472875

Reputation: 3175

JavaScript Event Handler Scope

I'm working on an application that uses the Google Maps API. I have no prior experience with javascript. What I'm trying to do is the following:

function SpeedMarker(position) {
    this.speed = 50;
    this.marker = new google.maps.Marker({
        position: position,
        map: map,
        icon: 'http://maps.google.com/mapfiles/markerA.png',
        zIndex: Math.round(position.lat() * -100000) << 5
    });
    google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow)        
}

SpeedMarker.prototype.ShowInfoWindow = function () {
    var contentString = 'stuff';
    infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    infowindow.open(map, this.marker);
}

The issue is that the click event happens in the document object, and this.marker does not exist in that context.

Is there any way to handle the event within the SpeedMarker object I created?

Upvotes: 2

Views: 2305

Answers (1)

Matt Ball
Matt Ball

Reputation: 359776

Change

google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow);

to

var self = this;
google.maps.event.addListener(this.marker, 'click', function () {
    self.ShowInfoWindow();
});

or use Function.bind (warning: may require shim):

google.maps.event.addListener(this.marker, 'click', this.ShowInfoWindow.bind(this));

Upvotes: 5

Related Questions