下面是一个描述嵌套树模型的代码,以及json中的示例数据。
如何使用提供的blocks
重置data
?
var Block, Blocks, data, blocks;
Block = Backbone.Model.extend({
initialize: function() {
this.blocks = new Blocks;
}
});
Blocks = Backbone.Collection.extend({
model: Block
});
data = [
{
id: 1,
blocks: [
{id: 2, blocks: [{id: 3}]}, {id: 4}
]
},
{
id: 5
}
];
blocks = new Blocks;
答案 0 :(得分:0)
var Block, Blocks, data, blocks;
Block = Backbone.Model.extend({
initialize: function() {
// access 'blocks' via attributes
// and initialize collection by passing the attributes in
this.attributes.blocks = new Blocks(this.attributes.blocks);
}
});
Blocks = Backbone.Collection.extend({
model: Block
});
data = [
{
id: 1,
blocks: [
{ id: 2,
blocks: [
{ id: 3 }
]
},
{ id: 4 }
]
},
{
id: 5
}
];
// initialize blocks by passing 'data' in
blocks = new Blocks(data);
好的,因为属性在初始化之前存储在attributes
下,您需要在初始化函数中调用this.attributes.blocks
以确保不会与this.blocks
混淆(有)。
您还需要通过将数据传递到它的构造函数来初始化blocks
,这对于Blocks
的每个其他实例都是相同的,即那些也存储在每个Block
内的实例。