【发布时间】:2014-10-22 03:08:31
【问题描述】:
我有一个主干视图,它有一个单击事件来更新集合。在我的控制台中,我可以看到正在更新的对象并且返回的模型数量正在发生变化,但是在第一次触发事件后视图保持静态并且任何第二次尝试触发它都会给我错误TypeError: text is undefined。作为参考,我的脚本加载在页面底部,模板(使用下划线)在其上方。
这是我的看法
app.MyView = Backbone.View.extend({
el: 'body',
events: {
'click #submit': 'fetchData'
},
initialize: function() {
this.collection = new app.MyCollection();
// On my first attempt, I tried having a the render tied to the sync event when the view initiated, although the sync event doesn't actually occur until something is clicked
// this.collection.on('sync', this.render, this);
},
render: function() {
console.log('rendering');
var schedule = $('#schedule');
var template = _.template($('#times-template').html());
schedule.html(template({ collection: this.collection.toJSON() }));
},
fetchData: function() {
that = this;
stationQuery.station_start = $('#start').val();
stationQuery.station_end = $('#end').val();
var query = stationQuery;
this.collection.fetch({
data: query,
success: function(collection, response) {
console.log('fetching data');
console.log(collection);
// attempt #2 - moving the sync event to the success callback of fetch doesnt allow the view to update a second time either
// collection.on('sync', that.render, that);
},
error: function(collection, response) {
console.log('error on fetch', response);
}
});
},
});
app.myView = new app.MyView;
// Third attempt, this time checking if listenTo will allow the view to update every time the event is fired. It still only works on the first time and fails to render for consecutive clicks, even though the console is showing updated models
app.myView.listenTo(app.myView.collection, 'sync', app.myView.render);
【问题讨论】: