gpt4 book ai didi

javascript - Backbone.js-模型方法中 'this' 的范围

转载 作者:行者123 更新时间:2023-11-28 01:57:01 25 4
gpt4 key购买 nike

在定义 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);
},

如有任何帮助,我们将不胜感激

最佳答案

将您的 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

关于javascript - Backbone.js-模型方法中 'this' 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18976819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com