fetch
方法は、各 API に対して Ajax 呼び出しを行うオーバーライドすることだと思います。返された部分セットを一時配列に格納し、4 つすべてが完了したら、 を使用してコレクションを作成しますthis.reset
。(JQuery を使用することもDeferred
、返された呼び出しの数を内部的にカウントすることもできます。)
このようなもの:
var Collection = Backbone.Collection.extend({
fetch: function() {
this.completeCount = 0;
this.errorCount = 0;
this.temp = [];
this.urls = [ 'url1', 'url2', 'url3', 'url4' ];
var self = this;
// make a $.get call for each URL and add
_.each(this.urls, function(url) {
$.get(url, { success: function(data) {
console.log("Got partial collection from " + url);
self.addPartial(data);
// alternatively, just call "self.add(data);" here
}, error: function(response) {
console.log("Oops, the Ajax call failed for some reason... ignoring");
self.completeCount ++;
self.errorCount ++;
} });
});
},
// add a JSON array that contains a subset of the collection
addPartial: function(data) {
this.completeCount ++;
var self = this;
// add each item to temp
_.each(data, function(item) {
self.temp.push(item);
});
// if all have been received, then create the collection
if (this.completeCount == this.urls.length) {
this.reset(this.temp);
}
}
});
$.get
これは、少し遅れてダミーデータを返すメソッドに置き換えた Fiddleです。
コメントへの返信
応答が入ってきたらコレクションに追加する方がおそらく良いでしょう (とにかく簡単です)。 これが更新されたフィドルです。