Bootstrap-TreeView with Knockout

Allow Knockout to bind with a Bootstrap-Treeview

by Cralis

HTML

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js"></script>
<div id="bindSection">
  <div id="tree"></div>
</div>

JavaScript

// Dummy function that will end up being an API call.
function getTree() {
  // Some logic to retrieve, or generate tree structure
  return [{
    text: "Root Folder",
    nodeLevel: 0,
    selectable: false,
    nodes: [{
      text: "Folder 1",
      nodeLevel: 1,
      nodes: [{
        nodeLevel: 2,
        text: "File 1",
        data: "This is data to diplay for File 1"
      }, {
        nodeLevel: 2,
        text: "File 2",
        data: "This is data to diplay for File 2"
      }]
    }, {
      nodeLevel: 1,
      text: "Folder 2"
    }]
  }, {
    nodeLevel: 1,
    text: "Folder 3"
  }, {
    nodeLevel: 1,
    text: "Folder 4"
  }];
}



// Create the View Model.
var ViewModel = function(jsonData) {
  var self = this;
  self.MyData = ko.observable(jsonData);

  ko.computed(function() {
    $('#tree').treeview({
        data: self.MyData()
      })
      .on('nodeSelected', function(event, data) {
        if (data.nodeLevel == 2) { // Are we clicking a File?
          alert("Clicked a File. Data: " + data.data)

        }
        else
        if(data.nodeLevel == 1) { // We're clicking a folder.
           alert("Clicked a folder. Would like to somehow alert a list of all child node text values.")
        }
      });
  })
}

// Create the View Model and initialise with initial data 
var vm = new ViewModel(getTree());

// Bind.
ko.applyBindings(vm, document.getElementById("bindSection"));