2013-04-15 70 views
2

我有這樣的代碼:呼叫.toJSON()在一個骨幹集合.filter每個模型()

 var products = kf.Collections.products.filter(function(product) { 
      return product.get("NominalCode") == chargeType 
     }); 

     if (products.length) { 
      for (x in products) { 
       products[x] = products[x].toJSON(); 
      } 
     } 

     return products; 

我是正確的思維有可能是做for in環的多個骨幹的方式?

+0

我不認爲有。您可以創建一個易變的集合,但這意味着會執行更多的代碼,並且會混淆模型中的'collection'屬性。 – Loamhoof

回答

0

您可以通過使用Collection.where

簡化你的過濾器,其中 collection.where(屬性)
返回所有集合中的匹配屬性,通過該模型的數組。適用於 過濾器的簡單情況。

,您可以通過使用_.invoke

刪除您的for循環調用 _.invoke(列表,方法名,[*參數])
調用由方法名上每個命名方法值在列表中。傳遞給調用的任何額外 參數將轉發到方法 調用。

這些修改可能看起來像

var products = kf.Collections.products.where({ 
    NominalCode: chargeType 
}); 

return _.invoke(products, 'toJSON'); 

http://jsfiddle.net/nikoshr/3vVKx/1/

如果你不介意改變操作的順序,chained methods

return kf.Collections.products.chain(). 
    invoke('toJSON'). 
    where({NominalCode: chargeType}). 
    value() 

http://jsfiddle.net/nikoshr/3vVKx/2/

或者正如@kalley在評論中建議的那樣,一個簡單的

_.where(kf.Collections.products.toJSON(), { NominalCode: chargeType }) 
+1

你也可以只是'_.where(kf.Collections.products.toJSON(),{NominalCode:chargeType})' – kalley

+0

@kalley你是完全正確的,我將這個添加到我的答案中 – nikoshr