我的视图包含可通过视图范围内的 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);
},
console.log(this)在这里向我展示了视图的范围,可以正确访问 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'});
}
},
问题是回调内部 console.log(this)显示此的范围限定为Window对象,即使我明确绑定它到视图对象的这个范围。
我需要在回调中访问this.map,因为我可能在页面上有多个地图,需要区分我正在谈论的那个。
如何将此回调绑定到适当的范围?或者,有更好的方法吗?
我正在使用backbonejs和underscorejs,但这应该是一个相当普遍的问题。
提前致谢, 大卫
答案 0 :(得分:5)
尝试更改
geocoder.geocode({'address': location}, this.setMapLocationCallback);
使用call()
,这样您就可以更改this
内setMapLocationCallback
的范围
var _this = this;
geocoder.geocode({'address': location}, function(result, status) {
_this.setMapLocationCallback.call(_this, result, status);
});