2

Я использую метод getbone.js Collection fetch для отправки запроса для возврата данных на основе смещения и ограничения. Первый метод collection.fetch() возвращает 5 моделей, поскольку LIMIT 0 и LIMIT 5, а при вызове снова Backbone.Collection.prototype.fetch.call (это опции) возвращает те же данные (предыдущие модели), но ответ сервера с последующим OFFSET = 5 и LIMIT = 5, i, e следующий набор объектов. Но я хочу добавить в объект коллекции всякий раз, когда его метод выборки вызова.Метод backbone Collection 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

ответ

1

Я хотел бы сделать что-то вроде этого, когда выборка успешна это вызывает «синхронизации» событие. Таким образом, каждый раз, когда она успешна вы можете увеличить счетчик смещения:

offsetStep: 5, 

initialize: function() { 
    this.on('sync', this.incrementOffset); 
} 

incrementOffset: function() { 
    this.offset += this.offsetStep; 
} 

Тогда вместо того, чтобы метода вам просто нужно пройти {add: true} при выборке - это сольется в новых моделях от сервера до тех пор, как они имеют уникальные ids:

myCollection.fetch({ add: true }); 
+1

метод myCollection.fetch ({add: true}); не работают! Его надпишите существующую модель myCollection на вызов myCollection.fetch ({add: true}); –

+0

Это не должно, если вы смотрите на источнике магистрального, что это не то, что он делает - 'this.models.splice (при + я, 0, toAdd [я]),' это принимает новые модели и сращивание их в –

+0

Try ставя точку останова в collection.set (в backbone.js) и посмотреть, что происходит –