2013-04-15 75 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