我有一个必须调用 4 个外部 API 的集合,例如:http://www.abc.com , http://www.fgt.com , http://www.jkl.com和 http://www.rty.com .
我有一个名为 Todos.js 的集合。有没有一种方法可以在一个集合中同时获取 4 个 api,因为所有 4 个 api 都会为我提供相同的模型响应 所以我从 4 个 API 获得的响应具有相同的数据结构,即“名称”和“链接”。
有没有一种方法可以将所有回复附加到同一个集合中?实现这一目标的最佳方法是什么?
最佳答案
我认为方法是覆盖 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);
}
}
});
Here's a Fiddle我将 $.get
替换为一种在短暂延迟后仅返回虚拟数据的方法。
回复评论
将响应添加到集合中可能更好(无论如何更容易)。 Here's an updated Fiddle.
关于javascript - 在 backbone js 中使用相同的集合从不同的 url 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13751253/