Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying a hierarchy(tree) using knockoutjs

Tags:

knockout.js

I have a tree of objects in my viewModel. The objects are something like this:

function Node() {
    var self = this;
    self.otherNodes = ko.observableArray([]);
    self.moreNodes = ko.observableArray([]);
}

So, the viewModel has a root node filled with Node objects in the root objects two arrays. Those Nodes may in turn have more Nodes in their arrays arbitrarily deep.

I'm having difficulty displaying this data structure in my view. A tree always suggests recursion to me but I'm not sure how to do that using knockoutjs. Any suggestions?

like image 700
Hector Scout Avatar asked Apr 02 '12 23:04

Hector Scout


People also ask

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

How do you activate a KnockoutJS model?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.

What is $data in knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.


1 Answers

Template bindings can refer to themselves:

http://jsfiddle.net/rniemeyer/UmBku/2/

some more tips here:

https://groups.google.com/forum/?fromgroups#!topic/knockoutjs/-x4X2AJK0HY

like image 161
Karl Rosaen Avatar answered Oct 24 '22 09:10

Karl Rosaen