12

I'm working on an application that has need of a form that allows the user to manage a hierarchy of product categories that go to an arbitrary depth. I can pretty easily get the data onto the page, but I'm a bit lost as to what I need to do to make such a thing work with backbone.js. Basically, I'm looking for nested ULs. When the user selects one, I want them to be able to edit/delete the category or add another category underneath it.

I'm having trouble finding cases online where someone has an arbitrarily deep hierarchy of the same data type in backbone.js. Would I just make my model class contain an instance of my collection class? How would saving be accomplished? I know this is a bit of a broad question, but I'm mainly in need of some general suggestions for how to approach this (or better yet, a sample somewhere that I haven't looked).

Will Gant
  • 583
  • 5
  • 21
  • The leaf elements are products themselves? – paddle42380 Oct 07 '11 at 16:30
  • I hadn't thought about doing that, but now that you mention it, it would make the interface even more usable. I was just trying to get something to manage the category hierarchy for the moment. – Will Gant Oct 15 '11 at 16:38

2 Answers2

5

You can model a tree as a collection of items with parent-child links. So your model should have something like this:

      id:           id,
      parent_id:    parent_id 

Then build a tree from a collection using recursive function calls in JS. Here is a piece of live code:

 function buildTree(branch, list) {
  //recursively builds tree from list with parent-child dependencies
  if (typeof branch == 'undefined') return null;
  var tree = [];
  for(var i=0; i<branch.length; i++)      
    tree.push( {
      item: branch[i],
      children: buildTree( list[ branch[i].id ], list)
    });
  return tree;
}

Before calling the function group items by parent_id using underscore.js (which is a prerequisite for backbone.js anyway), and then call:

  var list = _.groupBy(arrayOfItems,'parent_id');
  var tree = buildTree(list[0],list); 

Finally, render the tree using recursive function calls again (no example here, but I believe you got the idea).

PS. Adding/saving an item shoudn't be a problem if you indicate right parent_id.

Dmitry G.
  • 584
  • 5
  • 13
0

You can find answer on this link.

Backbone with a tree view widget

You have many ways to create hierarchical tree. One of them i posted in my question. If you want, try it! I used Backbone.js and Epoxy.js to create it. Link to Epoxy.js

http://epoxyjs.org/index.html

This library provide you easily to bind different events what contains tree

Community
  • 1
  • 1
Alexey
  • 11
  • 2