2

我有这个代码:

        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;

我是否认为可能有更多的 Backbone 方式来执行for in循环?

4

1 回答 1

0

您可以使用Collection.where简化过滤器

where collection.where(attributes)
返回集合中与传递的属性匹配的所有模型的数组。对于过滤器的简单情况很有用。

您可以使用_.invoke删除您的 for 循环

invoke _.invoke(list, methodName, [*arguments])对列表中的每个值调用由methodName
命名的方法。传递给调用的任何额外参数都将转发给方法调用。

这些修改可能看起来像

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

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

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

如果您不介意使用链式方法更改操作顺序

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 })
于 2013-04-15T16:26:35.563 回答