Chris
Chris

Reputation: 27384

Reference correct this within callback function

I have a class function in Typescript that adds a circle to google maps and adds an event listener. Within that listener I want to reference this, asign the object I am adding the listener too. See this as a reference on how it would work in pure JS

Unfortunately Typescript stops me from referencing the correct this, how do I fix this (problem, as opposed to this)?

public drawGeoFence(/* params removed */) : void {
    google.maps.event.addListener(circle, "mouseover", (event) => {
        this.showGeofenceInfoWindow(map, geofence, this); // <<- this!
    });
}

Upvotes: 1

Views: 98

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123861

Just use a function, not an arrow function

public drawAThing(/* params removed */) : void {
    let self = this;
    //google.maps.event.addListener(circle, "mouseover", (event) => {
    google.maps.event.addListener(circle, "mouseover", function(event){
        self.showGeofenceInfoWindow(map, geofence, this); // <<- this!
    });
}

Also, to have an access to original showGeofenceInfoWindow we need some more coding... to keep the original this in the self variable

Upvotes: 2

Related Questions