I have a Collection, where each item in the Collection could itself be a Collection. I can render each item in the Collection, and indeed can render any items which themselves are Collections. The problem I have is how to render this structure where the HTML reflects the hierarchical nature of the data structure. At the moment, the hierarchy is flattened and I end up with one long list of <div> elements.
I have a View for each item in a Collection which renders a single item and also checks to see if any nested items exist require rendering:
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;
}
});
Now this is perhaps where my problem is, but the CollectionView will create an ItemView for each Item it needs to render. This is how the recursive nature of the hierarchy is handled, however the flattening occurs because an ItemView always has the same $("div#ItemView") element it appends everything to.
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;
}
});
I would like to be able to append Items to a 'parent' element which is not $("div#ItemView"). The HTML structure I would like to end-up with would be something like:
<div>
<div>...</div>
<div>
<div>...</div>
...
</div>
...
</div>
Have I painted myself into a corner here?