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

Dav*_*win 3 javascript google-maps backbone.js

我有一个视图,其中包含可通过视图范围内的this.map访问的Google地图.一切都在世界上很好.

接下来,我想通过视图中的事件更新地图位置.为此,我接受文本输入,使用google.maps.Geocoder.geocode(),然后通过以下方式更新位置:

setMapLocation:function(location){

    _.bind(this.setMapLocationCallback, this);

    console.log(this);

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

},
Run Code Online (Sandbox Code Playgroud)

执行console.log(本)在这里表明我的观点的范围,与this.map正常访问.请注意,我在这里明确地将回调绑定到此.这是回调:

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'});
    }
},
Run Code Online (Sandbox Code Playgroud)

问题是,回调中的console.log(这)表明,是作用于Window对象,即使我束缚,明确视图对象的此范围内.

我需要在回调中访问this.map,因为我可能在页面上有多个地图,需要区分我正在谈论的那个.

如何将此回调绑定到适当的范围?或者,有更好的方法吗?

我正在使用backbonejs和underscorejs,但这应该是一个相当普遍的问题.

大卫先生,谢谢你

fca*_*ran 5

尝试改变

 geocoder.geocode({'address': location}, this.setMapLocationCallback);
Run Code Online (Sandbox Code Playgroud)

使用call(),所以你可以改变this内部的范围setMapLocationCallback

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

MDN有关call()函数的文档