Tree with BackboneJS

by kapilgopinath

HTML

<div id="treelist">
            <div id="scroll-list"></div>
        </div>       
        <script id="liTemplate" type="text/template">
            <a data-id="<%=id%>" data-parid="<%=parent_id%>"><%=text%></a>
        </script>
        <script id="navTemplate" type="text/template">
            <a class="goBack" data-navid="<%=nav_id%>"> << Back </a>
        </script>

CSS

ul{float:left;margin:10px}
            #treelist{position:relative;width:13%;height:200px;overflow:hidden;border-style: ridge;border-width: 5px;}
            #scroll-list{width:1500px;height:100%;position:absolute}
            #scroll-list ul{ float: left;height: 91%;width: 151px;margin: 10px 0 0 26px;padding: 0;position:relative;font-weight:bold}
            .goBack{font-weight: bold;position: absolute;right: 5px;bottom: -6px;color: rgb(0, 143, 255);font-style: italic;}

JavaScript

//https://backbonejs.org/test/vendor/underscore.js,http://backbonejs.org/backbone.js
(function($) {
    parId = 0;
    parentArr = {};
    var Item = Backbone.Model.extend({
        defaults: {
            text: 'world'
        }
    });

    var Collection = Backbone.Collection.extend({
        url: 'json/json.json',
        ret: [],
        parse: function(response) {
            return this._parseTree(response);
        },
        _parseTree: function(response, parent_id) {
            if (!response)
                return;
            if (!response.length) {
                var model = _.extend({
                    id: _.uniqueId(),
                    parent_id: parent_id
                }, _.omit(response, 'children'));
                this.ret.push(model);
                this._parseTree(response.children, model.id);
            } else {
                response.forEach(function(item) {
                    this._parseTree(item, parent_id);
                }, this);
            }
            return this.ret;
        },
        collFilter: function(filter) {
            return filteredCollection = collection.filter(function(item) {
                if (filter == "parent_id") {
                    return (typeof (item.get("parent_id")) === 'undefined');
                } else if (filter == "id") {
                    return (item.get("parent_id") == parId);
                }
            });
        }
    });

    var ItemListView = Backbone.View.extend({
        tagName: 'ul',
        events: {
            "click .goBack": 'goBack'
        },
        initialize: function() {
            _.bindAll(this, "renderItem");
        },
        template: _.template($('#navTemplate').html()),
        renderItem: function(model) {
            var itemView = new ItemView({model: model});
            itemView.render();
            $(this.el).append(itemView.el);
        },
        render: function(filter) {
            var str = '';
            var pId = 0;
           ...