1

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!
    });
}
Community
  • 1
  • 1
Chris
  • 26,744
  • 48
  • 193
  • 345
  • Related: [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) and [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) – Felix Kling Jun 03 '16 at 13:24

1 Answers1

2

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

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Why can't you use this for the `showGeofenceInfoWindow`? – Blubberguy22 Jun 03 '16 at 12:03
  • Because `this` now references the local function scope as opposed to the class – Chris Jun 03 '16 at 12:03
  • @Blubberguy22 this will be coming from different context. The *magic* which Typescript does with arrow functions, won't be applied... Check this for detailed how to https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html – Radim Köhler Jun 03 '16 at 12:04