我正在使用backbone.js Collection fetch方法根据偏移和限制发送返回数据的请求。第一个collection.fetch()方法返回5个模型,因为LIMIT 0和LIMIT 5,并且再次调用Backbone.Collection.prototype.fetch.call(this,options)时它返回相同的数据(以前的模型),但服务器响应下一个OFFSET = 5,LIMIT = 5,i,e下一组对象。但是我想在调用fetch方法时附加到集合对象中。
define([
'underscore',
'backbone',
'utils',
'core/base/models-and-collections',
'core/constants'
], function(_, Backbone, Utils, CollectionUtils, Constants) {
var Collection = Backbone.Collection.extend({
initialize: function(models, options) {
this.options = options;
_.bindAll(this, 'parse', 'url', 'pageInfo', 'nextPage');
typeof(options) != 'undefined' || (options = {});
typeof(this.limit) != 'undefined' || (this.limit = 5);
typeof(this.offset) != 'undefined' || (this.offset = 0);
typeof(this.size) != 'undefined' || (this.size = 5);
console.log("photo-collection-intitalize");
},
url: function() {
console.log("photo-collection-url-hit");
// if (this.size === this.limit) {
return Utils.keywordFormat("/api/student/{studentId}?limit={limit}&offset={offset}", {
studentId: this.options.studentId,
limit: this.limit,
offset: this.offset
});
},
nextFetch: function(options) {
console.log("next fetch method");
typeof(options) != 'undefined' || (options = {});
var self = this;
var success = options.success;
options.success = function(resp) {
if(success) {
success(self, resp);
console.info("-collection response on success");
console.info(resp);
}
};
return Backbone.Collection.prototype.fetch.call(this, options);
},
pageInfo: function(){
},
nextPage: function(){
},
parse: function(resp) {
console.info(resp);
if(!resp.items) {
console.error("items not specified", resp);
}
console.log("resp:limit "+resp.limit+ "resp: offset "+ resp.offset);
this.size= resp.limit;
return resp.items;
},
});
return Collection;
});
this.collection= new Collection();
this.collection.once("sync",this.GetFirstSetOfData,this);
this.collection.fetch();
GetFirstSetOfData: function(collection){
//set view
}
//set next data offset
this.collection.offset=this.collection.offset+this.collection.limit;
//call again fetch method
var newCollection=this.collection.nextFetch();
//new Collection is same data as previous this.collection have but server response next set of data
// i,e row 5-9
答案 0 :(得分:1)
我会做这样的事情,当fetch成功时会触发'sync'事件。所以每次成功都可以增加偏移计数器:
offsetStep: 5,
initialize: function() {
this.on('sync', this.incrementOffset);
}
incrementOffset: function() {
this.offset += this.offsetStep;
}
然后,在获取时只需要传递nextFetch
而不是{add: true}
方法 - 只要它们具有唯一ID,它就会在服务器中合并新模型:
myCollection.fetch({ add: true });