Backbone.js嵌套模型

时间:2012-06-20 16:33:02

标签: javascript backbone.js

我刚开始学习Backbone.js。如何为以下用例创建Backbone模型

  • 国家:[0-n]的
    • 姓名
    • 县:[0-n]的
      • 名称
      • 城市:[0-n]的
        • 姓名:
        • 公园[0-n]的
          • 名:

非常感谢任何帮助。 这是我到目前为止所尝试的

window.Team = Backbone.Model.extend({
        initialize: function(){
          this.id = this.get('id');
        }
      });
      window.Teams = Backbone.Collection.extend({model:Team});

      window.Ward = Backbone.Model.extend({
        initialize: function(){
          this.name = this.get('name');
          this.code = this.get('code');
          this.teams = new Teams(this.get('teams'));
        }
      });

      window.Wards = Backbone.Collection.extend({model:Ward});

      window.LGA = Backbone.Model.extend({
        initialize: function(){
          this.name = this.get('name');
          this.wards = new Wards(this.get('wards'));
        }
      });

      window.LGAs = Backbone.Collection.extend({model:LGA});

      window.State = Backbone.Model.extend({
        initialize: function(){
          this.name = this.get('name');
          this.lgas = new Wards(this.get('lgas'));
        }
      });

      window.States = Backbone.Collection.extend({model:State,

        initialize: function(){
          _.bindAll(this, 'fetch_success');
          this.bind('change', this.fetch_success);
        },

        url: function(){
            return "data.json"
        },

        fetch_success:function(){
            var data = Backbone.Syphon.serialize(someViewWithAForm);
            var model = new Backbone.Model(data);
        }
      });

由于

1 个答案:

答案 0 :(得分:2)

根据您构建/获取模型的方式,您可能会对Backbone-relational感兴趣,它可以让您定义模型之间的关系。

来自文档:

Person = Backbone.RelationalModel.extend({
    relations: [
        {
            type: 'HasMany',
            key: 'jobs',
            relatedModel: 'Job',
            reverseRelation: {
                key: 'person'
            }
        }
    ]
});