我有一个场地对象集合,它们都有自己的纬度/经度属性,使用这个和用户位置我可以计算用户和每个场地之间的距离。
我的问题是,我不能只在创建 Venue 对象时执行此操作,因此需要在更新位置变量时触发此计算,无论是通过观察位置变量还是触发函数,我都没有取得太大成功任何一种方法。
window.App = {};
// Venue Object
App.Venue = Backbone.Model.extend({
urlRoot: '/rest/venue',
defaults: {
distance: ''
},
initialize: function(){
console.log(App.position);
this.set('distance', getDistance(App.position.coords.latitude, App.position.coords.longitude, this.get('latitude'), this.get('longitude')));
},
events: {
// Doesn't seem to work
App.position.on('change', function() { console.log('change event'); })
},
updateDistance: function() {
console.log('updateDistance');
}
});
// Venues Collection Object
App.Venues = Backbone.Collection.extend({
url: '/rest/venues',
model: App.Venue,
comparator: function(venue) {
return venue.get('name');
}
});
$(document).ready(function(){
// Setup Model
App.venues = new App.Venues();
App.venues.fetch();
navigator.geolocation.watchPosition(gotPosition);
function gotPosition(position) {
console.log(position);
App.position = position;
// Somehow trigger updateDistance function on all model objects?
}
});
这里的正确方法是什么?