我有一个集合,集合中的每个项目本身可以是一个集合。我可以渲染集合中的每个项目,并且确实可以渲染任何本身为集合的项目。我遇到的问题是如何在HTML反映数据结构的层次性时呈现此结构。目前,层次结构已经变平,我最终得到了一个长长的列表<div>
元素。在Backbone.js框架中向对方添加视图
我有在这使得单个项目集合每个项目查看,并检查是否任何嵌套项目存在需要渲染:
ItemView = Backbone.View.extend({
el: $("div#ItemView"),
initialize: function() {
_.bindAll(this, 'render');
},
render: function() {
// Render a single item from the Collection
$(this.el).append('<div id=' + this.model.id + '></div>');
// Create a View to render the nested Collection
var collectionView = new CollectionView({ collection: this.model.nestedCollection });
collectionView.render();
return this;
}
});
现在,这也许是在我的问题是,但CollectionView将为每个需要渲染的物品创建一个ItemView。这是处理层次结构的递归性质的方式,但是由于ItemView始终具有相同的$(“div#ItemView”)元素,所以它会将所有内容都附加到其中,因此会导致展平。
CollectionsView = Backbone.View.extend({
initialize:function() {
_.bindAll(this, 'render');
},
render: function() {
var self = this;
// Iterate over collection, rendering each item
_(this.collection.models).each(function(item) {
var itemView = new ItemView({model: item});
itemView.render();
}, this);
return this;
}
});
我希望能够追加项目到这是不是一个$("div#ItemView")
“父”元素。 HTML结构,我想最终了会是这样的:
<div>
<div>...</div>
<div>
<div>...</div>
...
</div>
...
</div>
有我自己画到这里的角落?