2016-03-03 79 views
0
initialize: function(){ 
    this.collection = app.RequestLines; 
    this.subView = app.TransportationLineView; 

    this.listenTo(this.collection, 'add', this.addOne); 
    this.listenTo(this.collection, 'reset', this.addAll); 

    this.collection.fetch(); 

    this.render(); 
} 

在此上下文中,該視圖將提取數據庫上的所有模型。我如何才能獲取屬性上的模型過濾器。我已經定義了一個過濾器在我的收藏品要做到這一點:基於過濾器的骨幹提取模型

byTransportation: function(){ 
     return this.where({transportationConfirmation: true}); 
    } 

這是當事件添加被觸發那麼當一個模型被追加到視圖。

+0

你想收集來從服務器只篩選結果,或過濾收集客戶端從服務器獲取所有數據後..?如果是第一種情況,顯然你必須在服務器端實現邏輯。 –

+0

這將是第二種情況。 –

回答

1

您可以使用收集的parse方法從後端與過濾結果過濾數據和更新集合:

var SomeCollection = Backbone.collection.extend({ 
    // Other stuff 
    filterResponse: false, 
    filterStuff: function(stuff) { 
    if(!stuff) 
    stuff = this.models; 
    return _.where(stuff, { // need to use _ since stuff will not always 
          // be a collection instance(when invoked from parse) 
     something: true 
    }); 
    }, 
    parse: function(response) { // invoked after obtaining response from server 
           // and before updating it to collection 
    if(this.filterResponse) 
     return this.filterStuff(response); 
    return response; 
    } 
}); 
+0

我想過濾每當我打電話「那」,而不是每次我從服務器獲取的東西。有時候我想要獲取所有模型。 –

+0

我將如何參考集合中的項目而不是說'東西'。? –

+0

@DiegoGallegos你使用'this.models'來引用模型,東西就是你傳遞給filterStuff的任何東西。你可以看到,如果某些東西沒有手動傳遞給過濾器函數,我將'this.models'分配給這個東西。如果要有條件地過濾獲取的項目,可以在集合上設置標誌並避免基於'parse'中的標誌進行過濾。這很簡單,不是嗎?看到更新 –