0
我有两个收集视图。这个视图从products.json渲染每个对象,然后从categories.json渲染到<li><%= title %></li>
。 现在,我想呈现每个类别包括从每类产品...每个类别中的骨干过滤器产品(过滤器参数将是类别名称)
//!所有类别查看
App.Views.Categories = Backbone.View.extend({
tagName: 'ul',
className: 'categories',
initialize: function() {
this.collection.on('add', this.addOne, this);
},
render: function() {
this.collection.each(this.addOne, this);
return this;
},
addOne: function(category) {
var categoryView = new App.Views.Category({ model: category });
this.$el.append(categoryView.render().el);
},
});
//!单一分类视图
App.Views.Category = Backbone.View.extend({
tagName: 'li',
className: 'category',
template: template('allCategoryTemlate'),
initialize: function() {
this.model.on('destroy', this.unrender, this);
this.model.on('change', this.render, this);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
});
//!所有产品视图
!210App.Views.Products = Backbone.View.extend({
tagName: 'ul',
className: 'products',
initialize: function() {
this.collection.on('add', this.addOne, this);
},
render: function() {
this.collection.each(this.addOne, this);
return this;
},
addOne: function(product) {
var productView = new App.Views.Product({ model: product });
this.$el.append(productView.render().el);
},
});
//单品VIEW
App.Views.Product = Backbone.View.extend({
tagName: 'li',
className: 'product',
template: template('allProductTemlate'),
initialize: function() {
this.model.on('destroy', this.unrender, this);
this.model.on('change', this.render, this);
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
});
我的产品:
[
{"product_id": 1, "category": "CATEGORY1", "title": "Product 1", "price": 12},
{"product_id": 2, "category": "CATEGORY1", "title": "Product 2", "price": 12},
{"product_id": 3, "category": "CATEGORY1", "title": "Product 3", "price": 12},
{"product_id": 4, "category": "CATEGORY2", "title": "Product 4", "price": 12},
{"product_id": 5, "category": "CATEGORY2", "title": "Product 5", "price": 12}
]
我的类别:
[
{"category_id": 1, "value": "CATEGORY1", "title": "Category 1"},
{"category_id": 2, "value": "CATEGORY2", "title": "Category 2"},
]
例我需要的东西:
Category 1
- Product 1
- Product 2
- Product 3
Category 2
- Product 4
- Product 5
这对我的应用程序非常重要,所以我会非常乐意接受每一个意见。 我可以是这样的:
var filtered = products.filter(function(product) {
return product.get('category') == 'and there I need value from category ?';
});
或者模板是这样的:
<% _.each(categories, function(category) { %>
<%= category.get('title') %>
<li><%= title %></li>
<% _.filter(products, function(product){ %>
<%= return product category == value; %>
<%= product.get('title') %>
<% }); %>
<% }); %>
<% }); %>
<% }); %>
非常感谢您!
谢谢回答!是的,这是工作,但我需要为每个类别过滤器。而我的分类将是动态的因此,我需要像View这样的分类收集和产品收集数据。然后,我可以在模板中进行基于类别名称的产品过滤器......但我不知道如何做到这一点:/ – Makromat
@MatejMarko:你在寻找['filter'](http:// underscorejs .org /#filter),它是混合到Backbone集合中的[Underscore方法]之一(http://backbonejs.org/#Collection-Underscore-Methods)? –