当模型向服务器发出请求时,我正在尝试更新过滤的video
集合。user
问题出在update
方法上。fetch()
没有得到video
集合的最新数据。
我需要修复什么update
来获取最新数据,以便视图正确重新呈现?
var VideosView = Backbone.View.extend({
tagName: 'ul',
id: 'video-list',
initialize: function() {
var user = this.model;
var _videos = user.get('videos');
user_vids = videos.filter_videos(_videos);
this.listenTo(user, 'request', this.update);
},
render: function() {
user_vids.each( this.addOne, this );
return this;
},
addOne: function(video) {
var videoView = new VideoView({ model: video });
this.$el.append( videoView.render().el );
},
update: function() {
$('#video-list').empty();
_videos = this.model.get('videos');
videos.fetch();
user_vids = videos.filter_videos(_videos)
user_vids.each( this.addOne, this );
}
});
// Instantiate
var videosView = new VideosView({
model: user,
collection: videos
});
$('#allVideos').append( videosView.render().el );
编辑
添加附加代码:
这里videosView
是初始化的地方。
var IndexView = Backbone.View.extend({
initialize: function() {
user = this.model;
},
render: function() {
var videosView = new VideosView({
model: user,
collection: videos
});
$('#allVideos').append( videosView.render().el );
var addVideoView = new AddVideoView({
model: user,
collection: videos
});
$('#addVideo').append( addVideoView.render().el );
}
});
listenTo
inVideoViews
正在监听这里发生的add_to_user_array
事情AddVideoView
:
var AddVideoView = Backbone.View.extend({
tagName: 'div',
template: _.template( AddVideoTemplate ),
events: {
'click #videoSubmitButton': 'submit'
},
initialize: function() {
user = this.model;
},
render: function() {
var template = this.template();
this.$el.html(template);
return this;
},
submit: function(event) {
event.preventDefault();
console.log('form submitted');
var vimeo_id = parseInt( $('#vimeo_id').val() );
var newVideo = {vimeo_id: vimeo_id};
this.collection.create(newVideo, {wait: true});
this.add_to_user_array(vimeo_id);
},
add_to_user_array: function(vimeo_id) {
var _videos = user.get('videos');
_videos.push(vimeo_id);
user.save({videos: _videos}, {wait: true});
}
});
在路由器内部,我正在实例化模型和集合:
index: function() {
users = new Users;
users.fetch({
success: function(user_data) {
var user = user_data.findWhere({username: App.username})
videos = new Videos;
videos.fetch({
success: function(video_data) {
var indexView = new IndexView({
model: user,
collection: videos
});
var indexController = new IndexController;
indexController.showView( indexView );
}
});
}
})
}