下面的代码是一个小功能,以保证所有Backbone.collection /模型获取操作。我现在面临的唯一问题是deferred.resolve
,您可以看到Models
实际上是数组。
fetchData: function(Models) {
var deferred = $.Deferred();
var xhr = $.when.apply(this, Models).done(function(data, textStatus, jqXHR) {
deferred.resolve(Models, data, textStatus, jqXHR);
}).fail(deferred.reject);
var promise = deferred.promise();
//promise.abort = _.bind(xhr.abort, xhr);
return promise;
}
这样做的目的是为了满足简单的for循环操作,即每个循环都有自己的获取操作。
示例电话fetchData
:
var param = = [{
ipid: 44,
measure: "cumec"
}, {
ipid: 45,
measure: "meter"
}, {
ipid: 46,
measure: "milimeter"
} {
ipid: 47,
measure: "cumec"
}];
var ajax_calls = [];
var _this = this;
var complete = _.after(param.length, function() {
_this.fetchData(ajax_calls).done(performanotherfunction);
});
_.each(param, function(value, key) {
var data = new Collection();
data.id = value.ipid;
ajax_calls.push(data.fetch({
success: function(model) {
console.log(model.get('res_ipid'));
}
}));
complete()
}, this);
我希望fetchData
将按ipid
的顺序返回Collection / Model。但是控制台的结果总是显示res_ipid
不按顺序排列,因为它取决于获取的竞争条件。
希望有人能为此做出更多启示。
答案 0 :(得分:0)
我认为你正在努力实现这一目标。而不是:
var complete = _.after(param.length, function() {
_this.fetchData(ajax_calls).done(performanotherfunction);
});
_.each(param, function(value, key) {
var data = new Collection();
data.id = value.ipid;
ajax_calls.push(data.fetch({
success: function(model) {
console.log(model.get('res_ipid'));
}
}));
complete()
}, this);
你应该能够做到:
var promises = _.map(param, function(value, key) {
var data = new Collection();
data.id = value.ipid;
return data.fetch({
success: function(model) {
console.log(model.get('res_ipid'));
}
});
});
$.when.apply($, promises).done(performanotherfunction);