不知道我是否正確理解設置,但您有BoxModel。
BoxModel = Backbone.Model.extend({
defaults: {
'image':string,
'title':string,
'description':string
}
});
而一個BoxModel可以包含兒童BoxModels?
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());
另外請注意,這基本上意味着您的孩子boxModels在此示例中可視化表示。如果每個孩子(行)必須具有一些功能,而不是僅僅使用模板寫出可視表示,我會使用addAllRows()
方法來實例化第二種類型的BoxModel視圖。一個視圖,它是一個表格行,並具有更多的功能,如正確委派的事件。
骨幹,你必須使用* *獲取函數可以訪問模型的屬性:http://backbonejs.org/#Model-get – elevine
是的,我會更新的例子,但那不是我正在努力的。 –