我想知道这里最好的模式/方法。这是我的路由器中的一个功能,因此用户点击'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]
}));
}
答案 0 :(得分:40)
我发现jQuery deferreds和下划线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...
});
答案 1 :(得分:20)
承诺!具体来说是jQuery.when
您可以这样做:
$.when(
kf.Collections.quotes.fetch(),
kf.Collections.projects.fetch(),
kf.Collections.currencies.fetch()
).then(function(){
// render your view.
});
jQuery.ajax(以及扩展主干fetch)返回一个promise,一旦多个promise被解析,你就可以使用$.when
来设置一个回调函数。
答案 2 :(得分:4)
Backbone的fetch
返回一个jQuery Deferred
对象(一个promise)。因此,您可以使用jQuery的when function等待所有要解决的承诺:
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
var quotePromise = kf.Collections.quotes.fetch();
var projectsPromise = kf.Collections.projects.fetch();
var currenciesPromise = kf.collections.currencies.fetch();
// wait for them to all return
$.when(quotePromise, projectsPromise, currenciesPromise).then(function(){
// do stuff here, now that all three have resolved / returned
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]
}));
};
}
我在这里写了一些关于promises和jQuery的文章:
第二个链接仍然有效,尽管主要主题是Win8 JS