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).
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.
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