2013-11-22 102 views
0

我正在使用主干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.

我试图了解为什么第三级不转换为一个集合

+0

btw,你的例子为我工作的原因。除非你在json中有重复的ID。我想知道这是否会造成问题。 –

回答

0

你可以覆盖模型中的解析函数来做到这一点。

这样,每次你做fetch()或save()时,它都会自动包装你的子元素(和它们嵌套的子元素,如果存在的话)在treeItemCollection中。

但是,当你启动你的数据,或者你只是使用reset()时,这不起作用。因此您可能还想覆盖构造函数方法:

var treeItem = Backbone.Model.extend({ 
    //other stuff shown above 

    constructor: function(attributes, options){ 
    options = options || {}; 
    options.parse = true; 
    Backbone.Model.call(this, attributes, options); 
    } 
}); 

它应该适用于您的情况。

我们在很多项目中都使用过这种模式,我们很喜欢它。如果你想应用到所有模型/系列,并且更灵活,你可能想读这个: http://www.devmynd.com/blog/2013-6-backbone-js-with-a-spine-part-2-models-and-collections

+0

谢谢,这证明很有用。我最终使用了基本相同的模式。 – Marcus