How to implement TreeView with Backbone.js

I started to implement an application that uses backbone.js. One feature that I needed was some kind of treeview as a side menu. I searched some jQuery based treeviews (like jstree and jQuery plugin: Treeview) but they were not suitable as out of the box.

Finally I decided to implement feature by myself. I found that jstree had a very good model of <ul> and <li> element combinations and I went to that direction in my solution as well. See the DEMO

Basically I needed two Backbone View classes: TreeView and TreeViewItem.

TreeView

TreeView class just creates the master <ul>-element (templates/treeview/menu.jst.ejs)

<ul id="menu"></ul>

The class also fetches root level collection of MenuItems and creates TreeViewItem for each item.

TreeViewItem

TreeViewItem has one MenuItem model and a collection of TreeViewItems. In the template (templates/treeview/item.jst.ejs) name of the item is displayed and <ul> element is rendered as sub menu placeholder.

<ins>&nbsp;</ins>
<a href="#"><%= model.escape('name') %></a>
<ul></ul>

TreeViewItem handles clicks from arrow icon (<ins>-element has arrow image as a background) and opens/closes sub menu.

Both views extends Support.CompositeView (from backbone-support library).

Usage

application.js contains required libraries
backbone_treeview.js initializes TreeView class

window.BackboneTreeView = {
    Models: {},
    Collections: {},
    Views: {},

    menu: null,

    initialize: function() {

    },

    initializeMenu: function() {
        this.menu = new BackboneTreeView.Views.TreeView();
        this.menu.render();

    }

};
$(document).ready(function() {

    BackboneTreeView.initializeMenu();
});

How would you improve the implementation and should I make it as a library?

Link to project source: https://github.com/nevalla/backbone-treeview

Advertisements

2 thoughts on “How to implement TreeView with Backbone.js

  1. Hi Lauri,

    I need some help, how to use this library, I have a requirement developing a tree view, where clicking on a tree view item would render some more child elements calling a rest api
    .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s