JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://raw.github.com/documentcloud/underscore/ba3e31b53ef5752b40cfb2d71f594536fefbe916/underscore-min.js"></script>
<script src="https://raw.github.com/documentcloud/backbone/master/backbone-min.js"></script>
<div id="wrapper"></div>
CSS
body { font-family: Arial; }
#wrapper {
padding: 10px;
background: #ccc;
}
ul {
margin-left: 10px;
list-style: disc;
}
ul ul {
list-style: circle;
}
JavaScript
var data = [
{"id":1,"name":"test1","parent_id":null},
{"id":2,"name":"test2","parent_id":null},
{"id":3,"name":"test3","parent_id":2},
{"id":4,"name":"test4","parent_id":2}
]
var NestedView = Backbone.View.extend({
render: function(){
this.$el.html( "<ul id='ul-null'></ul>" )
this.collection.each( function( model ){ this.renderElement( model ) }, this )
},
renderElement: function( model ){
var ul = this.getParentUl( model );
this.appendElement( ul, model );
},
getParentUl: function( model ) {
var ul = this.$el.find( "#ul-" + model.get( "parent_id" ) );
if( ul.length == 0 ) {
this.appendListInElement( model );
ul = this.$el.find( "#ul-" + model.get( "parent_id" ) );
}
return ul;
},
appendListInElement: function( model ){
var li = this.$el.find( "#li-" + model.get( "parent_id" ) );
li.after( "<ul id='ul-" + model.get( "parent_id" ) + "'></ul>" );
},
appendElement: function( ul, model ){
ul.append( "<li id='li-" + model.get( "id" ) + "'>" + model.get( "name" ) + "</li>" );
}
});
var elements = new Backbone.Collection( data );
var nestedView = new NestedView({ el: "#wrapper", collection: elements });
nestedView.render();