1

我正在从 Google Maps V2 升级到 V3。我被这个功能困住了。在添加事件侦听器时,我必须将 this 对象传递给函数。我无法做到这一点。

例子:

Namespace.mapWrapper.prototype.enableZoneDraw = function(callback) {
    if (!this.isDrawing) {
        //this.clickListener = GEvent.bind(this.api, 'click', this, this.toggleZoneDraw);
        this.clickListener = google.maps.event.addListener(this.api, 'click', this.toggleZoneDraw); //this.api is map object
        if (callback) {
            this.drawEndCallback = callback;
        }
    }
}

Namespace.mapWrapper.prototype.toggleZoneDraw = function(event) {
    // Start drawing zone
    if (!this.isDrawing) {
        if(event.latLng){
            this.zoneCenter = event.latLng;
            this.isDrawing = true;
            this.drawListener = google.maps.event.addListener(this.api, 'mousemove', another_function);
        }
    } else {
        this.isDrawing = false;
        google.maps.event.removeListener(this.drawListener);
        google.maps.event.removeListener(this.clickListener);
    }
}

我想在toggleZoneDraw中访问更多的enableZoneDraw对象,但是在toggleZoneDraw中如果我访问这个对象,它指的是新对象。

请帮忙。

谢谢

4

1 回答 1

0
Namespace.mapWrapper.prototype.enableZoneDraw = function(callback) {
    if (!this.isDrawing) {
        //create a reference to the current this object
        var obj = this;
        this.clickListener = google.maps.event.addListener(
            this.api, //this.api is map object
            'click',
            //use a closure to maintain our reference to this object
            function (evt) {
                obj.toggleZoneDraw(evt);
            }
        );
        if (callback) {
            this.drawEndCallback = callback;
        }
    }
}
于 2013-04-24T12:14:27.660 回答