【发布时间】:2014-05-24 22:26:30
【问题描述】:
我对 JavaScript 还很陌生,对 Backbone.js 完全陌生。
在下面的代码中,我创建了一个新的 UserLocationModel 并将这个模型实例传递给一个新的 UserLocationView 对象。在此视图的 initialize() 中,我(尝试)将 render() 绑定到传递的模型发生的任何更改。
我相当确定模型发生了变化,我从navigator.geolocation 收到了新的纬度和经度值,并将这些值分配给模型的值。我也知道视图成功接收模型(this.model 永远不会为空)。
为什么没有调用 UserLocationView.render()?
型号:
var UserLocationModel = Backbone.Model.extend({
defaults: {
latitude: -1,
longitude: -1
},
updateLocation: function() {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(this.positionSuccess, this.positionFailure);
}
},
positionSuccess: function(position) {
this.set({
latitude : position.coords.latitude,
longitude : position.coords.longitude
});
},
positionFailure: function() {
...
}
});
查看:
var UserLocationView = Backbone.View.extend({
initialize: function(){
_.bindAll(this,'render');
if(this.model) this.model.on('change',this.render,this);
},
render: function(){
console.log('UserLocationView render called.');
...
}
});
执行开始:
window.MyApp = Backbone.View.extend({
initialize: function() {
userLocationModel = new UserLocationModel();
userLocationView = new UserLocationView({ model: userLocationModel });
userLocationModel.updateLocation();
this.render();
}
});
编辑:
我已经重写了上面的一些代码,包括model.set。
编辑 2:moxn 的附加信息。
main.js:
define(['jquery', 'underscore', 'backbone','template', 'myapp'], function() {
$(document).ready(function() {
window.App = new MyApp({ appendTo: $('body') });
});
});
在 HTML 中被 this 调用:
<script data-main="../static/js/main" src="../static/js/vendor/require.js"></script>
【问题讨论】:
-
你能把你在
Model更改的代码贴出来吗? -
@DennisRongo 变化发生在 positionSuccess() 中。
-
您是否尝试过使用:
positionSuccess: function(position) { this.set({ latitude : position.coords.latitude, longitude : position.coords.longitude },...? -
@DennisRongo 我有,请查看我的问题的编辑。
-
@Caroline 你在哪里调用 MyApp.initialize?直接或通过
new MyApp()