簡體   English   中英

過濾Backbone.js集合

[英]Filtering Backbone.js collection

我正在使用多個骨干集合,有時我需要根據一些標准來訪問其中的一部分。

方法1

本問題所述 ,在集合本身上使用filter()返回模型數組,而不是另一個集合。 這可以在簡單的情況下工作,但是會丟失集合的方法級聯,因為模型的簡單數組不會在集合中定義所有方法。

方法2

該問題的答案建議創建一個新集合,將模型數組傳遞給構造函數。 此方法有效,但具有每次調用集合的構造函數的副作用,因此,每次過濾集合時,可能會在此定義的任何事件綁定都會堆積在堆棧上。

那么,基於某些過濾條件創建子集合的正確方法是什么?

我是否應該使用方法1並創建更多的過濾方法,而不是依靠方法鏈?

我應該使用方法2並避免在集合的構造函數中綁定事件嗎?

我個人會在集合上創建更多的過濾方法,因為它具有將邏輯封裝在集合內的額外好處。

您也可以嘗試重用現有集合。 我在想着這個主意,得出這樣的結論:

var Collection = Backbone.Collection.extend({
  //Takes in n arrays. The first item of each array is the method you want
  //to call and the rest are the arguments to that method. 
  //Sets the collection.models property to the value of each successive filter
  //and returns the result of the last. Revers the collection.models to its original value.
  chainFilters: function(/*args..*/) {
    var models = this.models;
    try {
      filters = _.toArray(arguments);
      _.each(filters, function(filter) {
         this.models = filter[0].apply(this, _.rest(filter));
      }, this);
    } catch(err) {
      this.models = models;
      throw err;
    }

    var filtered = this.models;
    this.models = models;
    return filtered;   
  }
});

用法:

var results = collection.chainFilters(
  [ collection.filter, function(model) { return model.get('name') === 'foo'; } ],
  [ collection.someMethod, 'someargument' ],
  [ collection.someOtherMethod ]
);

這是一個工作示例。 我知道這有點奇怪。

這取決於用例。 如果您希望這些模型更新視圖,則可能需要一個新集合,否則您將無法獲得很好的反應性模板更新。 如果您只是希望模型迭代或操作數據而不必擔心數據更新,請使用array + underscore.js。

嘗試使用數組,如果您發現自己編寫了許多樣板代碼,而這些樣板代碼具有集合中已有的功能,而沒有underscore.js中的功能,那么就開始使用集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM