所以我有这个非常简单的用例:
init: function() {
app.products = new app.Collections.Products();
app.categories = new app.Collections.Categories();
var collections = [app.products, app.categories];
var complete = _.invoke(collections, 'fetch');
$.when(null, complete).then(function(){
// fetched, but no models
});
};
从 XHR 的角度来看,这工作正常,但在回调中,尚未创建相应集合的模型。有没有办法在这个基于承诺的解决方案中也从"获取"中寻找"重置"事件?
您可以构建自己的延迟来协调您的呼叫。例如,您可以在集合的原型上添加此功能:
function promiseSync() {
var dfd = $.Deferred();
this.once('sync', function() {
dfd.resolve();
});
return dfd.promise();
}
app.Collections.Products.prototype.promiseSync = promiseSync;
app.Collections.Categories.prototype.promiseSync = promiseSync;
然后,就像您对请求所做的那样,合并延迟的:
var syncs = _.invoke(collections, 'promiseSync');
$.when.apply(null, syncs).then(function(){
console.log('syncs');
});
还有一个演示 http://jsfiddle.net/nikoshr/Xb9Mk/
请注意 $.when.apply(null, array)
的用法。 $.when(null, array)
会立即解决,这可能就是您在回调中看不到模型的原因。
使用此代码,您将获取产品和类别集合,并填充其模型。
deferredFetch
函数设置延迟对象,并在填充集合后对其进行解析。通过使用 {reset: true}
选项调用fetch
,Backbone 将填充集合并触发一个reset
事件,而不是多个add
事件。
init
只是获取两个集合,then
执行注释的代码块。传入products
和categories
是因为延迟对象已使用reset
侦听器中的这些对象进行解析。
function deferredFetch(collection) {
var deferred = $.Deferred();
collection.once('reset', function(collection) {
deferred.resolve(collection);
});
collection.fetch({ reset: true });
return deferred;
}
init: function() {
app.products = new app.Collections.Products();
app.categories = new app.Collections.Categories();
$.when(deferredFetch(app.products), deferredFetch(app.categories))
.then(function(products, categories) {
// do yo thang
});
}