The code below is small function to guaranteed all Backbone.collection / model fetch operation. The only problem that I'm facing right now is deferred.resolve
where you can see the Models
is actually an array.
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;
}
The purpose of this is to cater simple for-loop operation whereby each loop has it's own fetch operation.
Example call 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);
I am expecting fetchData
will return Collection/Model in order of ipid
. But result of console will always showing res_ipid
not in order because it depends on race condition of fetch.
Hope someone will shed even more light for this.