我有一个索引视图,用于调用集合,因此调用项目视图。用户可以勾选项目,然后单击索引模板中的复制。
下面的代码工作正常,该项目在索引中触发了一个事件。但问题是,我希望能够知道所有事件何时完成复制这些帖子。我能想到的唯一方法就是将复制逻辑移到索引视图中,但我认为这是一个项目视图操作。
文章/ index.js
// copy posts from the collection
onClickCopyPosts: function() {
// are we sure we want to delete these posts
var platform = $('#copyPlatforms option:selected').val();
if (confirm('Are you sure you want to copy these posts to that platform?')) {
// get the post ids of the ticked posts
var postIds = this.getSelectedPostsArray();
_.each (postIds, function (postId, key) {
MyApp.vent.trigger('post:copy:'+postId, platform);
})
}
},
item.js
initialize: function () {
var that = this;
this.listenTo(MyApp.vent, 'post:copy:'+this.model.get('id'), function(platform) {
// fetch the collection and pass its filters through
that.onCopy(platform);
});
},
onCopy: function(platform) {
// copy the current model to a new variable
var modelJSON = this.model.toJSON();
// set platform to the platform passed to the method
modelJSON.platform = platform;
modelJSON = Factory.create(modelJSON);
// create a new instance of that model
var newModel = new Model(modelJSON);
// save the new model
newModel.save({}, {
success: function() {
//console.log('copy post', 'success');
},
error: function() {
//console.log('copy post', 'error');
},
complete: function() {
//console.log('copy post', 'complete');
}
});
return;
},
答案 0 :(得分:0)
我认为您应该重新设计它以保存一组模型,而不是为每次保存触发事件。通过这种方式,您可以使用Jquerys $.when收听一组XHRS,以便在完成所有操作后触发回调。
请参阅Brian Mann's solution他允许任意数量的可同步骨干实体触发"when:fetched"
事件,但同样可用于保存模型。好Video就好了。