gpt4 book ai didi

javascript - 主干关系 - 深层嵌套模型/集合

转载 作者:太空宇宙 更新时间:2023-11-04 16:23:09 26 4
gpt4 key购买 nike

享受 Backbone-relational.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/

地址模型或任务集合都不是作为 Backbone 实例创建的,这可能吗?或者我是否突破了该插件的限制?

最佳答案

  • 以下是我解决该问题的方法。你错过了reverseRelation
  • 顺便说一句,你看过这个吗 post ?它也有类似的问题。

关注fiddle here

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>

关于javascript - 主干关系 - 深层嵌套模型/集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40439183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com