2013-02-23 54 views
1

我有一個場景,我需要通過多個參數過濾車輛集合 - 一系列收音機,選擇框等,用戶可能選擇組合,即燃料,座位,顏色。實施例的組合可以是:Backbonejs - 如何通過多個參數過濾集合?

  • 顏色=紅色
  • 座椅= 4 &燃料=汽油
  • 燃料=柴油
  • 燃料=汽油&顏色=黑色&座椅= 2

它很簡單,可以通過來過濾一個集合參數,但需要多個提示。

這是我的車收集:

Vehicles = Backbone.Collection.extend({ 
     model: Vehicle, 
     withFuelType: function(fuel) { 
      return this.models.filter(function(vehicle) { return vehicle.get('fuel') === fuel; }); 
     }, 
     withSeats: function (seats) { 
      return this.models.filter(function (vehicle) { return vehicle.get('seats') === seats; }); 
     }, 
     withColor: function(color) { 
      return this.models.filter(function (vehicle) { return vehicle.get('color') === color; }); 
     } 
    }) 

任何指針十分讚賞。

回答

3

可以使用where簡單的等式搜索:

其中collection.where(attributes)

返回所有型號的那場比賽所傳遞的屬性集合中的數組。適用於filter的簡單情況。

所以你不需要這些功能,你可以這樣做,而不是:

c.where({ fuel: 'petrol', color: 'black' }); 
c.where({ seats: 2 }); 

你應該能夠把你的搜索查詢字符串轉換成一個對象和手,要where得到你需要。