在定义主干模型时,我对“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);
},
任何帮助都会得到帮助