0

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

1 回答 1

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,即那些也存储在 each中的实例Block

于 2012-11-19T13:04:26.467 回答