简体   繁体   中英

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!
    });
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM