我最近繼承了一個嚴重依賴Backbone.js的應用程序。我的應用程序將覆蓋Backbone.sync()函數與Qt一起工作(允許應用程序在嵌入桌面應用程序的瀏覽器中執行AJAX請求);所以,AJAX最好儘可能使用Backbone。你會如何使用Backbone.js與這個jQuery插件?
我想使用jQuery Treeview插件here並使用Backbone與我的API進行數據交互。要異步加載節點,它使用覆蓋toggle()的additional plugin,使其使用$ .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沒什麼特別的... – PhD
它與Qt/Webkit相關的東西不兼容。我可以覆蓋$ .ajax,類似於Backbone.sync()被覆蓋的方式...... –
'Backbone.sync'應該沒問題,但@JayC在他的回答中提出了一些好的觀點。您也可以查看骨幹關係(https://github.com/PaulUithol/Backbone-relational)來幫助維護您的層次結構。 – rjz