不确定我是否正确理解了设置,但您有一个 BoxModel。
BoxModel = Backbone.Model.extend({
defaults: {
'image':string,
'title':string,
'description':string
}
});
BoxModel 可以包含子 BoxModel 吗?
boxModel.children = new Collection(); // of box models?
并且您想遍历子集合并将每个模型表示为表格行?
如果这是你想要的,这就是我会做的。盒子模型由 BoxView 表示,它是一个表,它的子项本质上表示为行。所以我们将其定义为:
BoxView = Backbone.View.extend({
tagName: 'table',
className: 'list-items-template', // I just used this name to connect it with your ex.
// I'd probably change it to like, box-table
template: _.template('<tr>
<td><%= image %> </td>
<td><%= title %> </td>
<td><%= description %> </td>
</tr>'),
initialize: function() {
// Note: We've passed in a box model and a box model has a property called
// children that is a collection of other box models
this.box = this.model;
this.collection = this.box.children // Important! Assumes collection exists.
},
render: function() {
this.$el.html(this.addAllRows());
return this;
},
addAllRows: function() {
var that = this;
var rows = '';
this.collection.each(function(box) {
rows += that.template(box.toJSON());
});
return rows;
}
});
// This assumes that whatever BoxModel you have instantiated, it has a property called
// children that is a collection of other BoxModels. We pass this in.
// Get the party started
var myBoxTable = new BoxView({
'model': someBoxModel // Your box model, it has a collection of children boxModels
});
// Throw it into your page wherever.
$('#placeToInsert').html(myBoxTable.render.el());
另请注意,这基本上意味着您的孩子 boxModel 在此示例中以视觉方式表示。如果每个子(行)都必须有一些功能,而不是仅仅使用模板来写出视觉表示,我会使用该addAllRows()
方法来实例化第二种类型的 BoxModel 视图。作为表格行的视图,具有更多功能,例如正确委派的事件。