如何使用Dojo引用Google Maps事件中的包含类

How do I reference the containing class from a Google Maps event using Dojo?

本文关键字:事件 包含类 Maps Google 何使用 Dojo 引用      更新时间:2023-09-26

我正在做一些工作,将一个使用Google Maps API v2到v3的遗留项目转换为v3。

有一个Dojo类看起来像这样:

dojo.declare
(
    "MyNamespace.MapControl",
    null,
    {
        constructor: function() {
            var mapElement = document.getElementById("map");
            this._map = new google.maps.Map(mapElement, {});
            google.maps.event.addListenerOnce(this._map, "idle", this.map_load);
        },
        map_load: function() {
            this.onLoad();
        },
        onLoad: function () { }
    }
);

问题是,当调用map_load函数时,this的上下文是Google map,而不是类。

我尝试在类中创建一个局部变量self,并使用

_self = this;

在构造函数中,但该变量没有onLoad函数。这是使用的代码:

dojo.declare
(
    "MyNamespace.MapControl",
    null,
    {
        _self: null,      
        constructor: function() {
            var mapElement = document.getElementById("map");
            this._map = new google.maps.Map(mapElement, {});
            google.maps.event.addListenerOnce(this._map, "idle", this.map_load);
            _self = this;
        },
        map_load: function() {
            _self.onLoad(); // fails as onLoad is undefined
        },
        onLoad: function () { }
    }
);

Dojo中有没有一种方法可以在*map_load*函数中获得对父类的引用,或者有没有其他方法可以将其连接起来?

使用dojo.hitch(/*Object*/ scope, /*Function|String*/ method):

google.maps.event.addListenerOnce(this._map, "idle", dojo.hitch(this, "map_load"));

有关更多信息,请参阅http://livedocs.dojotoolkit.org/dojo/_base/lang#hitch