简体   繁体   English

如何绑定谷歌地图geocoder.geocode()回调函数

[英]How do I bind a google maps geocoder.geocode() callback function

I have a view that contains a google map accessible via this.map within the view scope. 我有一个视图,其中包含可通过视图范围内的this.map访问的Google地图。 All is well in the world. 一切都在世界上很好。

Next I want to update the map position via events in my view. 接下来,我想通过视图中的事件更新地图位置。 To do this I take text input, use google.maps.Geocoder.geocode(), then update the position via: 为此,我接受文本输入,使用google.maps.Geocoder.geocode(),然后通过以下方式更新位置:

setMapLocation: function (location) { setMapLocation:function(location){

    _.bind(this.setMapLocationCallback, this);

    console.log(this);

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': location}, this.setMapLocationCallback);

},

The console.log(this) here shows me the scope of the view, with this.map properly accessible. console.log(this)在这里向我展示了视图的范围,可以正确访问this.map Notice that I explicitly bind the callback to this here. 请注意,我在这里显式绑定回调。 Here's the callback: 这是回调:

setMapLocationCallback: function (results, status) {

    console.log('this in the callback');
    console.log(this);

    if (status == google.maps.GeocoderStatus.OK) {
        this.map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: this.map,
            position: results[0].geometry.location
        });
        this.mapCanvas.css({visibility: 'visibile'});
    } else {
        this.mapCanvas.css({visibility: 'hidden'});
    }
},

The problems is that inside the callback console.log(this) shows that this is scoped to the Window object even though I bound it explicitly to the view object's this scope. 问题是,回调的console.log(这)表明, 可以被限制,即使我束缚,明确视图对象的此范围内的Window对象。

I need to access this.map in the callback because I may have more than one map on a page and need to distinguish which one I'm talking about. 我需要在回调中访问this.map,因为我可能在页面上有多个地图,需要区分我正在谈论的那个。

How do I bind this callback to the proper scope? 如何将此回调绑定到适当的范围? or, is there a better way to do this? 或者,有更好的方法吗?

I'm using backbonejs and underscorejs, but this should be a fairly generic problem. 我正在使用backbonejs和underscorejs,但这应该是一个相当普遍的问题。

Thanks in advance, David 大卫先生,谢谢你

try changing 尝试改变

 geocoder.geocode({'address': location}, this.setMapLocationCallback);

using call() , so you can change the scope of this inside setMapLocationCallback 使用call() ,所以你可以改变的范围thissetMapLocationCallback

 var _this = this;
 geocoder.geocode({'address': location}, function(result, status) {
     _this.setMapLocationCallback.call(_this, result, status);
 });

MDN Documentation about call() function MDN有关call()函数的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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