javascript - Race Condition of Backbone.Collection fetch -
i'm generating date list in selected month every date, make backbone.collection
fetch.
here how loop every single date in month
for (var = 1; <= numofdays; i++) { var d = < 10 ? '0'+i:i; var v = new view({ dt: this.year + this.month + (d), param: this.array }); this.$el.append(v.render().el); }
as can see above, each view (backbone.view
) represent date
, param object
. loop param
object using underscorejs _.each
method upon callin render()
_.each(this.param, this.reading, this);
and later initiate new object of backbone.collection
, perform fetch right away.
reading: function (value, key) { var _this = this; this.fetchdata(new data.collection(), '/api/ + value.ipid').done(function(coll) { var input = $('<input>').val(value.ipid).attr('data-inid', coll.first().get('in_id')); _this.$el.append(input); }); }
i separate function this.fetchdata
this
fetchdata: function (obj, url) { var deferred = $.deferred(), collection = obj; collection.url = url; var xhr = collection.fetch().done(function(data, textstatus, jqxhr) { deferred.resolve(collection, data, textstatus, jqxhr); }).fail(deferred.reject); var promise = deferred.promise(); promise.abort = _.bind(xhr.abort, xhr); return promise; }
unfortunately, each view, order of item inside param
object shift because depends on race condition of backbone.ajax
. let see items of param
object
[{ipid: 44, measure: "cumec"},{ipid: 45, measure: "meter"},{ipid: 46, measure: "milimeter"}{ipid: 47, measure: "cumec"}]
the object items in proper order. 44, 45, 46 , 47. listing pass change after fetch operation.
how tell backbonejs or underscorejs wait every fetch operation complete before start looping item inside param
object
i want loop (_.each) wait fetch operation complete before continue looping
hope can enlighten way achieve this. thank , have day
if create , append dom element @ view creation time (i.e. inside reading
function), reference inside done callback, elements in same order inside param array.
side note: can instantiate collection
url directly, , there no need wrap jquery promise around promise returned fetch.
Comments
Post a Comment