Backbone - 嵌套在模型中的集合

时间:2011-09-02 19:39:17

标签: javascript json backbone.js

是否可以在模型中嵌套集合?

我知道您可以在模型的初始化回调中创建新集合,并创建可以在集合和父模型之间来回传递的引用。但是可以将集合设置为模型的一部分,这样它导出的JSON就像这样:

{
  blah: 'blah',
  myCollection: [
      {
         foo: 'asdf',
         bar: 'qwer'
      },
      {
         foo: 'asdf123',
         bar: 'qwer123'
      }
  ]
}

如果没有,您如何处理将具有相关集合的模型同步到后端?您是否必须利用主干的同步并重建JSON或者是否有更无缝的东西?

很抱歉,如果这个问题已在其他地方得到解答。我环顾四周,看到了一些变通方法,但没有什么可以解决我正在寻找的问题。

2 个答案:

答案 0 :(得分:30)

有两种方法。第一个是定义获取所有内容的根模型。您可以覆盖它的parse()方法来为嵌套属性创建子集合和子模型,并覆盖toJSON()方法以转换回适合保存到服务器的JSON结构。

对于小的子集合,这是完全可以接受的。这需要一些编程,但是如果你能阅读Backbone源代码,那么该怎么做应该是,不是很明显,但至少可以理解。

或者您可以使用Backbone Relational,它可以为您完成所有工作。

答案 1 :(得分:7)

雷纳托很接近,但“有”和“设定”尚不可用。我相信Reckoner指出了部分原因。此外,您需要从响应中删除该属性,否则它将覆盖默认值。

_.extend(Backbone.Model.prototype, {
    parse: function(resp, xhr) {
        var attr, model, models, collection, options;
        for (var prop in resp) {
            if (this.defaults && this.defaults[prop]) {
                attr = this.defaults[prop];
                if (attr instanceof Backbone.Model) {
                    model = attr.clone();
                    model.set(resp[prop]);
                    resp[prop] = model;
                } else if (attr instanceof Backbone.Collection) {
                    models = attr.map(function (model) { return model.clone(); });
                    options = _.clone(attr.options);
                    collection = new attr.constructor(models, options);
                    collection.add(resp[prop]);
                    resp[prop] = collection;
                }
            }
        }
        return resp;
    }
});

希望能有所帮助。