Composite View: TreeView

A treeview build w/ Marionette

by dbouwman

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">
    <a href="#"><%= name %></a>
    <ul></ul>
</script>
        
<div id="tree">
</div>

CSS

body{
    padding-left: 10px;
}
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: "li",
    events: {'click':'nodeClick'},
    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(cv, iv){
        cv.$("ul:first").append(iv.el);
    },
    nodeClick:function(){
        console.log(this.model.get('name'));
        return false;                
    }            
    
});

// 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({
    tagName: "ul",
    itemView: TreeView
});





// ----------------------------------------------------------------
// Below this line is normal stuff... models, templates, data, etc.
// ----------------------------------------------------------------
treeData = [
  {
    "children": [],
    "id": "6e7f9a0b-ffc3-4ea7-a9c0-07dac5dd994c",
    "name": "Project Documents",
    "order": 0,
    "projectId": 1
  },
  {
    "children": [],
    "id": "a2905b6f-c4eb-447c-82ab-71729720a7b4",
    "name": "Environmental Impact Study",
    "order": 0,
    "projectId": 1
  },
  {
    "children": [
      {
        "children": [],
        "id": "5684b8db-ab59-48f7-b6a1-6145d0805a00",
        "name": "Another",
        "order": 2,
        "projectId": 1
      },
      {
        "children": [],
        "id": "0f89975b-a0b6-4d49-96b7-d20894878ae1",
        "name": "LRTP",
        "order": 1,
        "projectId": 1
      }
    ],
    "id": "4dcbdd82-233a-4702-8b25-a5ae9ce56197",
    "name": "Transportation Plan",
    "order": 0,
    "projectId": 1
  },
  {
    "children": [
      {
        "children": [],
        "id": "8bd28e40-7e68-4657-8201-19bf43bfed27",
        "name": "Record of...