在定义Backbone模型时,我对'this'的范围有疑问。 在函数updateGeoLocation中,我正在调用一个匿名函数来处理标记的位置和位置的更新。
问题是当在匿名函数里面'this'指的是窗口而不是模型。 我试着将它添加到我的init函数中,但它仍然无法解决问题:
_.bindAll(this , 'updateGeoLocation');
代码是:
var googleMapsModel = Backbone.Model.extend ({
//Init map according to the window height
initialize: function () {
_.bindAll(this , 'updateGeoLocation');
this.set('currentLocation', new google.maps.LatLng(-34.397, 150.644));
$("#map-content").height(this.getRealContentHeight());
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
this.updateGeoLocation();
},
//Update geo location and place marker on the map
updateGeoLocation: function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
lat = position.coords.latitude;
long = position.coords.longitude;
console.log (lat);
console.log((long));
currentLocation = new google.maps.LatLng(lat,long);
map.setCenter(currentLocation);
//update marker
this.updateCurrentLocationMarker(currentLocation);
}) , function() {
alert("no Geo Location");
};
}
},
updateCurrentLocationMarker: function (markerLocation) {
myLocationMarker = new google.maps.Marker({
position: markerLocation,
map: map
});
this.model.set('currentLocationMarker', myLocationMarker);
},
任何帮助都会受到欢迎
答案 0 :(得分:1)
将updateGeoLocation
方法替换为:
updateGeoLocation: function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(_.bind(function (position) {
lat = position.coords.latitude;
long = position.coords.longitude;
console.log (lat);
console.log((long));
currentLocation = new google.maps.LatLng(lat,long);
map.setCenter(currentLocation);
//update marker
this.updateCurrentLocationMarker(currentLocation);
}, this)) , function() {
alert("no Geo Location");
};
}
},
这里的关键是_.bind,看看the doc