2012-09-29 41 views
1

當在初始fetch之後調用fetch(對用戶的操作作出響應)時,許多新抓取的模型可能與初始fetch。如果我使用add: true選項呼叫fetch,則該集合中可能存在重複的模型。Backbone的抓取():僅添加對集合新增的模型

問題:除刪除現有的所有車型從集合(與id=1,2,3,4說),並插入新取的模型(id=1,2,3,5),是有可能做到以下2個操作:

  1. 添加只有新機型id=5,導致與id=1,2,3,4,5收集。然後僅渲染新視圖(id=5

  2. 添加新模型id=5並刪除未在新的fetchid=4)中找到的模型。然後呈現新視圖(id=5),並刪除舊的意見(id=4

嘗試:

與其說App.listingCollection.fetch()的,使用fetchNew()功能。這隻適用於將新型號id=5添加到集合中。

如何在不重新渲染現有視圖id=1,2,3,4的情況下觸發新視圖的渲染(id=5)?我內ListingCollection與線new ListingMarkerView({ model:item }).render();嘗試這樣做,但我在ListingMarkerView得到一個錯誤響應線var marker = L.marker([this.model.get('lat'), this.model.get('lng')]);

錯誤

Uncaught TypeError: Object #<Object> has no method 'get' 

收集

ListingCollection = Backbone.Collection.extend({ 
    model: Listing, 
    url: '/api/search_by_bounds', 

    fetchNew: function(options) { 
     options = options || {}; 
     var collection = this, 
      success = options.success; 
     options.success = function(resp, status, xhr) { 
      _(collection.parse(resp, xhr)).each(function(item) { 
       // added this conditional block 
       if (!collection.get(item.id)) { 
        collection.add(item, {silent:true}); 
        new ListingMarkerView({ model:item }).render(); 
       } 
      }); 
      if (!options.silent) { 
       collection.trigger('reset', collection, options); 
      } 
      if (success) success(collection, resp); 
     }; 
     return (this.sync || Backbone.sync).call(this, 'read', this, options); 
    } 
}); 

查看

ListingMarkerView = Backbone.View.extend({ 

    render: function() { 
     var marker = L.marker([this.model.get('lat'), this.model.get('lng')]); 
     markers.addLayer(marker); 
    }, 

    close: function() { 
     this.unbind; 
    } 

}); 
+0

更新:true'做你想要的嗎? ''' App.listingCollection.fetch({update:true}); ''' –

回答

3

一個寧靜的API沒有它使一個GET請求時檢索對象的列表說話,因此客戶端的狀態的概念(例如, http://example.com/restapi/user/),其餘服務器應始終返回匹配對象的完整列表。

在骨幹端,您應該只收集來自服務器列表的.reset.reset將清空集合,然後添加的所有項目,如:

my_collection.fetch({success: function(collection, resp){ 
    collection.reset(resp, {silent: true}); 
}}); 

這樣,你沒有得到衝突,你不必擔心什麼。除非你有已經在本地集合中更改過但尚未保存回服務器的模型。

如果您正在尋找一種方法來防止對集合中的本地項目進行修改,那就需要類似上面提到的魔法。

相關問題