我正在做一些与本文中描述的树结构非常相似的事情:
http://lostechies.com/derickbailey/2012/04/05/composite-views-tree-structures-tables-and-more/
这个想法是在集合视图(TreeRoot)中拥有一个根节点的集合,其中每个根节点也有一个递归复合视图(TreeView)。可以在此处找到显示文章中树结构的最简单工作示例的 jsFiddle:
http://jsfiddle.net/hoffmanc/NH9J6/
我想修改示例,以便可以将一些选项传递给每个树视图,而不管它在树结构中的什么位置。这是我的(只有非常轻微的修改)jsFiddle:
我修改后的示例中的 JS 代码是:
// The recursive tree view
var TreeView = Backbone.Marionette.CompositeView.extend({
template: "#node-template",
tagName: "li",
initialize: function(){
// grab the child collection from the parent model
// so that we can render the collection as children
// of this parent node
this.collection = this.model.nodes;
console.log(this.options.msg); // undefined!
},
appendHtml: function(cv, iv){
cv.$("ul:first").append(iv.el);
},
onRender: function() {
if(_.isUndefined(this.collection)){
this.$("ul:first").remove();
}
}
});
// The tree's root: a simple collection view that renders
// a recursive tree structure for each item in the collection
var TreeRoot = Backbone.Marionette.CollectionView.extend({
tagName: "ul",
itemView: TreeView
});
// ----------------------------------------------------------------
// Below this line is normal stuff... models, templates, data, etc.
// ----------------------------------------------------------------
treeData = [
{
nodeName: "top level 1",
nodes: [
{
nodeName: "2nd level, item 1",
nodes: [
{ nodeName: "3rd level, item 1" },
{ nodeName: "3rd level, item 2" },
{ nodeName: "3rd level, item 3" }
]
},
{
nodeName: "2nd level, item 2",
nodes: [
{ nodeName: "3rd level, item 4" },
{
nodeName: "3rd level, item 5",
nodes: [
{ nodeName: "4th level, item 1" },
{ nodeName: "4th level, item 2" },
{ nodeName: "4th level, item 3" }
]
},
{ nodeName: "3rd level, item 6" }
]
}
]
},
{
nodeName: "top level 2",
nodes: [
{
nodeName: "2nd level, item 3",
nodes: [
{ nodeName: "3rd level, item 7" },
{ nodeName: "3rd level, item 8" },
{ nodeName: "3rd level, item 9" }
]
},
{
nodeName: "2nd level, item 4",
nodes: [
{ nodeName: "3rd level, item 10" },
{ nodeName: "3rd level, item 11" },
{ nodeName: "3rd level, item 12" }
]
}
]
}
];
TreeNode = Backbone.Model.extend({
initialize: function(){
var nodes = this.get("nodes");
if (nodes){
this.nodes = new TreeNodeCollection(nodes);
this.unset("nodes");
}
}
});
TreeNodeCollection = Backbone.Collection.extend({
model: TreeNode
});
var tree = new TreeNodeCollection(treeData);
var treeView = new TreeRoot({
collection: tree,
itemViewOptions: {msg: 'hi'}
});
如您所见,我正在尝试使用 itemViewOptions 传递选项,但是当 TreeView 初始化时,它不存在。我假设这是因为只有 TreeRoot 正在获取 itemViewOptions。
我的问题是:如何将选项从 TreeRoot 传递到 TreeView?
谢谢!