Composite View: TreeView

A treeview build w/ Marionette

by metavige

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.modelbinding/master/backbone.modelbinding.min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.memento/master/backbone.memento.min.js"></script>
<script src="https://raw.github.com/derickbailey/backbone.marionette/master/lib/backbone.marionette.js"></script>
<script id="node-template" type="text/template">
    <li><%= nodeName %></li>
</script>
        
<div id="tree">
</div>

CSS

ul {
  list-style: disc;
  padding-left: 10px;
  margin-left: 10px;    
}

JavaScript

// The recursive tree view
var TreeView = Backbone.Marionette.CompositeView.extend({
    template: "#node-template",

    tagName: "ul",

    initialize: function() {
        // grab the child collection from the parent model
        // so that we can render the collection as children
        // of this parent node
        this.collection = this.model.nodes;
    },

    appendHtml: function(collectionView, itemView) {
        // ensure we nest the child list inside of 
        // the current list item
        collectionView.$("li:first").append(itemView.el);
    }
});

// The tree's root: a simple collection view that renders 
// a recursive tree structure for each item in the collection
var TreeRoot = Backbone.Marionette.CollectionView.extend({
    itemView: TreeView
});





// ----------------------------------------------------------------
// Below this line is normal stuff... models, templates, data, etc.
// ----------------------------------------------------------------
treeData = [
    {
    nodeName: "top level 1",
    nodes: [
        {
        nodeName: "2nd level, item 1",
        nodes: [{
            nodeName: "3rd level, item 1"}
                           ]}
    ]},
{
    nodeName: "top level 2",
    nodes: [
        {
        nodeName: "2nd level, item 3",
        nodes: [
            {
            nodeName: "3rd level, item 7"},
        {
            nodeName: "3rd level, item 8"},
        {
            nodeName: "3rd level, item 9"}
        ]}
    ]}

];


TreeNode = Backbone.Model.extend({
    initialize: function() {
        var nodes = this.get("nodes");
        if (nodes) {
            this.nodes = new TreeNodeCollection(nodes);
            this.unset("nodes");
        }
    }
});

TreeNodeCollection = Backbone.Collection.extend({
    model: TreeNode
});

var tree = new TreeNodeCollection(treeData);
var treeView = new TreeRoot({
    collection: tree
});

treeView.render();
$("#tree").html(treeView.el);