骨干关系——深度嵌套模型/集合



使用backbone - relationship .js v0.10.0玩得很开心

我有一个JSON对象,其中包含嵌套的模型和集合,为了保持简单,我做了下面的例子。一个公司可以有很多员工,员工可以有一个地址和多个任务。
{
    name: 'Nicks Company',
    employees: [{
        name: 'Bob',
        address: {
            line1: '1 City Lane',
            city: 'London'
        },
        tasks: [{
            description: 'Make this work'
        }]
    }, {
        name: 'Bill',
        address: {
            line1: '1 The Street',
            city: 'Birmingham'
        },
        tasks: [{
            description: 'Make a cake'
        }, {
            description: 'Fix all the things'
        }]
    }]
}

在下面的JSFiddle(控制台)中,您可以看到地址是一个普通对象,并且由于tasks作为数组返回,任务的注释代码已被禁用。

JSFiddle: https://jsfiddle.net/nwa29uLv/2/

地址模型或任务集合都不是作为主干实例创建的,这是可能的还是我在推动这个插件的限制?

    以下是我如何解决这个问题。你错过了reverseRelation。顺便说一句,你看了这篇文章吗?它有类似的问题。

跟着这里的小提琴

var Address = Backbone.RelationalModel.extend({});
var Task = Backbone.RelationalModel.extend({});
var TaskCollection = Backbone.Collection.extend({
  model: Task
});
var Employee = Backbone.RelationalModel.extend({
  relations: [{
    type: Backbone.HasOne,
    key: 'address',
    relatedModel: Address,
    reverseRelation: {
      type: Backbone.HasOne,
      key: 'employee'
    }
  }, {
    type: Backbone.HasMany,
    key: 'tasks',
    collectionType: TaskCollection,
    relatedModel: Task,
    reverseRelation: {
      type: Backbone.HasOne,
      key: 'operatesOn'
    }
  }]
});
var EmployeeCollection = Backbone.Collection.extend({
  model: Employee
});
var Company = Backbone.RelationalModel.extend({
  relations: [{
    type: Backbone.HasMany,
    key: 'employees',
    relatedModel: Employee,
    reverseRelation: {
      key: 'worksFor'
    }
  }]
});
var company = new Company({
  name: 'Nicks Company',
  employees: [{
    name: 'Bob',
    address: {
      line1: '1 City Lane',
      city: 'London'
    },
    tasks: [{
      description: 'Make this work'
    }]
  }, {
    name: 'Bill',
    address: {
      line1: '1 The Street',
      city: 'Birmingham'
    },
    tasks: [{
      description: 'Make a cake'
    }, {
      description: 'Fix all the things'
    }]
  }]
});
console.log('Company:', company.get('name'));
company.get('employees').each(function(employee) {
  console.log('Employee:', employee.get('name'));
  console.log('Employee:', employee.get('name'), 'Address Model:', employee.get('address').get('city'));
  employee.get('tasks').each(function(task) {
    console.log('Employee:', employee.get('name'), 'Task: ', task.get('description'));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone-relational/0.10.0/backbone-relational.js"></script>

相关内容

  • 没有找到相关文章

最新更新