【发布时间】:2012-05-17 19:32:53
【问题描述】:
我最近继承了一个严重依赖 Backbone.js 的应用程序。我的应用程序覆盖 Backbone.sync() 函数以使用 Qt(允许应用程序在嵌入桌面应用程序的浏览器中执行 AJAX 请求);所以,AJAX 最好尽量使用 Backbone。
我想使用 jQuery Treeview 插件here 并使用 Backbone 与我的 API 进行数据交互。为了异步加载节点,这使用了additional plugin,它覆盖了toggle(),使其使用$.ajax 来请求新的节点数据。
在这个插件中使用 Backbone 是否有意义,您将如何去做?我认为这将涉及编写一个直接使用 Backbone 的替代“异步”插件?
这是我目前所拥有的:
;(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);
【问题讨论】:
-
是什么阻止您直接在代码中调用
$.ajax? Backbone.sync 没什么特别的…… -
它与 Qt/Webkit 相关的东西不兼容。我可以像覆盖 Backbone.sync() 一样覆盖 $.ajax...
-
Backbone.sync应该没问题,但@JayC 在他的回答中提出了一些优点。您还可以查看骨干关系 (github.com/PaulUithol/Backbone-relational) 以帮助维护您的层次结构。
标签: jquery-plugins backbone.js