我有两个集合视图。此视图将 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;
},
});
// !所有产品视图
App.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);
},
});
// !单一产品视图
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') %>
<% }); %>
<% }); %>
<% }); %>
<% }); %>
非常感谢 !!!