I recently inherited an application that relies heavily on Backbone.js. My application overrides the Backbone.sync() function to work with Qt (allowing the application perform AJAX requests in a browser embedded in a desktop application); so, it is preferred that Backbone is used as much as possible for AJAX.
I would like to use the jQuery Treeview plugin here and use Backbone to interact with my API for data. To load nodes asynchronously, this uses an additional plugin which overrides toggle(), making it use $.ajax to request new node data.
Does it make sense to use Backbone with this plugin, and how would you go about doing so? I assume it would involve writing an alternative 'async' plugin which uses Backbone directly?
Here is what I have so far:
;(function($) {
var proxied = $.fn.treeview;
$.fn.treeview = function(settings) {
// if (!settings.url) {
// return proxied.apply(this, arguments);
// }
var container = this;
var TreeNodeCollection = Backbone.Collection.extend({
url: '/api/subfolder_list',
tagName: 'ul',
initialize: function() {
},
parse: function(response) {
container.empty();
$.each(response, this.createNode, [container]);
//$(container).treeview({add: container});
},
createNode: function(parent) {
var current = $("<li/>").attr("id", this.id || "").html("<span>" + this.text + "</span>").appendTo(parent);
if (this.classes) {
current.children("span").addClass(this.classes);
}
if (this.expanded) {
current.addClass("open");
}
if (this.hasChildren || this.children && this.children.length) {
var branch = $("<ul/>").appendTo(current);
if (this.hasChildren) {
current.addClass("hasChildren");
if (typeof branch.collection == 'undefined') {
branch.collection = new TreeNodeCollection();
}
branch.collection.createNode.call({
classes: "placeholder",
text: " ",
children:[]
}, branch);
}
if (this.children && this.children.length) {
if (typeof branch.collection == 'undefined') {
branch.collection = new TreeNodeCollection();
}
$.each(this.children, parent.collection.createNode, [branch])
}
}
$(parent).treeview({add: container});
}
});
container.collection = new TreeNodeCollection();
if (!container.children().size()) {
container.collection.fetch();
}
var userToggle = settings.toggle;
return proxied.call(this, $.extend({}, settings, {
collapsed: true,
toggle: function() {
var $this = $(this);
if ($this.hasClass("hasChildren")) {
var childList = $this.removeClass("hasChildren").find("ul");
//load(settings, this.id, childList, container);
container.collection.fetch();
}
if (userToggle) {
userToggle.apply(this, arguments);
}
}
}));
};
})(jQuery);