如何重置骨干模型的嵌套树

时间:2012-11-19 12:40:37

标签: backbone.js

下面是一个描述嵌套树模型的代码,以及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;

1 个答案:

答案 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内的实例。