我正在使用主干1.1并尝试从3-5级深树导航创建集合。主干集合树创建
我的代码的简化版本如下所示。
var treeItem = Backbone.Model.extend({
defaults : {
'label' : '',
'children' : null
},
initialize : function() {
console.log('model init');
if (_.isArray(this.get('children'))) {
this.set({children : new treeItemCollection(this.get('children'))});
}
},
});
var treeItemCollection = Backbone.Collection.extend({
model: treeItem
});
var myTree = new treeItemCollection([
{ "label" : "first", "id": 1 },
{ "label" : "second", "id": 1, "children":
[
{ "label" : "second.first", "id" : 21 },
{ "label" : "second.second", "id" : 22 },
{ "label" : "second.third", "id" : 22, "children" : [
{ "label" : "third.first", "id" : 31 },
{ "label" : "third.second", "id" : 32 }
] }
]
}
]);
在我的理解这应该正确地创建更深层次的孩子的集合(以我的理解,应该初始化当对象被构造从而正确地创建了更深层次的调用)。
由于某种原因,这似乎并非如此。第二个层次(如myTree.models[0].get('children')
是正确的treeCollection类型的集合,但第3级(myTree.models[0].get('children').models[0].get('children')
)只是直线上升JSON从参数对象。
对我来说,那是最离奇的一部分,第二级是确定,但第三个不是。在initialize()
console.log是检查,并非常正确,它被触发4次,而不是6.
我试图了解为什么第三级不转换为一个集合
btw,你的例子为我工作的原因。除非你在json中有重复的ID。我想知道这是否会造成问题。 –