2013-09-24 55 views
0

请问我该如何为每件产品制作一组过滤物品?或者我如何过滤来自类别数据的项目?Backbone.groupBy或过滤器?

var Categories = new Backbone.Collection(); 

Categories.add([ 
    { title: 'category 1', category_type: 'category 1' }, 
    { title: 'category 2', category_type: 'category 1' }, 
]); 

var Items = new Backbone.Collection(); 

Items.add([ 
    { title: 'Product 1', category: 'category 1' }, 
    { title: 'Product 2', category: 'category 1' }, 
    { title: 'Product 3', category: 'category 2' } 
]); 


var byFiltred = Items.groupBy('category'); 

var filtred = new Backbone.Collection(byFiltred['category 1']); 

console.log(filtred.pluck('title')); 

感谢您的意见和解答! Makromat

回答

2

这取决于你想得到什么。 .groupBy返回一个分层对象,而.filter(或只是.where)与您的条件匹配的项目数组。

所以用这个数组给定:

var a = [ 
    { title: 'Product 1', category: 'category 1' }, 
    { title: 'Product 2', category: 'category 1' }, 
    { title: 'Product 3', category: 'category 2' } 
] 
_.groupBy(a, 'category'); 
/* returns 
    { 
     "category 1" : [ { title: 'Product 1', category: 'category 1' }, { title: 'Product 2', category: 'category 1' } ], 
     "category 2" : [ { title: 'Product 3', category: 'category 2' } ] 
    } 
*/ 

_.where(a, { 'category': 'category 1' }); 

/* returns 
    [ { title: 'Product 1', category: 'category 1' }, { title: 'Product 2', category: 'category 1' } ] 
*/ 

要显示的层次结构视图,像

category 1 
    product 1 
    product 2 
category 2 
    product 1 

你应该再使用.groupBy循环遍历每个类别的对象和显示项:

example

+0

所以我需要使用手风琴风格进行视图,所以名称(标签)将是类别标题,内容是过滤项目集合。因此,我需要根据类别集合中的数据为每个类别过滤项目制作一些模板...您知道我的意思吗?希望这不仅对我有帮助...再次感谢 – Makromat

+0

@Makromat看看我的编辑,如果这是你要去的地方,我可以提供更多的细节。 – pawel

+0

非常感谢这是非常有帮助的,但我需要从两个阵列这个使... – Makromat

0

使用Backbone.Collection.filter()并提供与您的类别匹配的比较器。

http://underscorejs.org/#filter

+0

谢谢你的回答是的,我看到这个,但我不知道我该怎么做这个......你能给我发送一些样品吗?我会非常感谢! – Makromat