[英]How do I bind a google maps geocoder.geocode() callback function
我有一个视图,其中包含可通过视图范围内的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内(这)表明, 这可以被限制,即使我束缚,明确视图对象的此范围内的Window对象。
我需要在回调中访问this.map,因为我可能在页面上有多个地图,需要区分我正在谈论的那个。
如何将此回调绑定到适当的范围? 或者,有更好的方法吗?
我正在使用backbonejs和underscorejs,但这应该是一个相当普遍的问题。
大卫先生,谢谢你
尝试改变
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.