我正在使用脊骨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类型的集合,但是第三级(myTree.models[0].get('children').models[0].get('children'))只是直接从参数对象中获得JSON。
对我来说,这是最奇怪的部分,第二层是好的,而第三层则不是。console.log在initialize()中是要检查的,而且非常正确,它被触发4次,而不是6次。
我在试着理解为什么第三层没有被转换成一个集合。
发布于 2013-11-22 20:26:12
您可以覆盖模型中的解析函数来完成此操作。
var treeItem = Backbone.Model.extend({
defaults : {
'label' : '',
'children' : null
},
initialize : function() {
console.log('model init');
},
parse: function(response) {
if (response["children"]) {
response["children"] = new treeItemCollection(response["children"]);
}
return response;
}
});这样,每次进行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
https://stackoverflow.com/questions/20152456
复制相似问题