我想知道这里最好的模式/方法.这是我的路由器中的一个功能,因此用户点击'quotes /:id',但是要呈现该视图,我需要一个他们的项目,客户和货币的列表.在尝试实例化quotesEdit视图之前,确保所有3个fetches()都已发生的最佳方法是什么?当用户点击某些内容时,获取所有信息被认为是不好的做法吗?
quotesEdit: function(id) {
kf.Collections.quotes = kf.Collections.quotes || new kf.Collections.Quotes();
kf.Collections.projects = kf.Collections.projects || new kf.Collections.Projects();
kf.Collections.currencies = kf.Collections.currencies || new kf.Collections.Currencies();
//do a fetch() for the 3 above
kf.Collections.customers = kf.Collections.customers || new kf.Collections.Customers();
var quote = kf.Collections.quotes.where({Id: parseInt(id, 10)});
kf.Utils.ViewManager.swap('sectionPrimary', new kf.Views.section({
section: 'quotesEdit',
model: quote[0]
}));
}
Run Code Online (Sandbox Code Playgroud)
jev*_*lio 40
我发现jQuery延迟的组合和下划线的invoke方法优雅地解决了这个问题:
//call fetch on the three collections, and keep their promises
var complete = _.invoke([quotes, projects, currencies], 'fetch');
//when all of them are complete...
$.when.apply($, complete).done(function() {
//all ready and good to go...
});
Run Code Online (Sandbox Code Playgroud)
mra*_*ton 20
承诺!特别是jQuery.when
你可以这样做:
$.when(
kf.Collections.quotes.fetch(),
kf.Collections.projects.fetch(),
kf.Collections.currencies.fetch()
).then(function(){
// render your view.
});
Run Code Online (Sandbox Code Playgroud)
jQuery.ajax(以及扩展主干fetch)返回一个promise,你可以$.when在解决多个promise后设置一个回调函数.