【发布时间】:2011-08-16 20:33:32
【问题描述】:
我有一个名为 Company 的 Backbone.Model。
我的Company 模型有一个Employees Backbone.Collection,其中包含Employee 模型。
当我实例化我的Employee 模型以填充Employees 集合时,我希望它们能够引用它们所属的Company。但是当我在其中传递Company 时,它成为Employee 的属性之一。这是我保存Employee 时的问题,因为toJSON 方法将包含Company 对象,而我在数据库中存储的只是外键整数company_id。
我希望 Backbone.Model 有第二个参数,它接受不属于核心属性的模型属性。我怎样才能解决这个问题?我意识到我可以实例化我的 Employee 模型,然后附加 Company,但我真的想在传统的“构造函数”中完成所有任务,而不是从外部附加属性。
例如:
Employee = Backbone.Model.extend({});
Employees = Backbone.Collection.extend({
model: Employee
});
Company = Backbone.Model.extend({
initialize: function() {
this.employees = new Employees({});
}
});
c1 = new Company({id: 1});
e = new Employee({name: 'Joe', company_id: 1, company: c1});
c1.employees.add(e);
e.get('company'); // => c1
e.save(); // BAD -- attempts to save the 'company' attribute, when in reality I only want to save name and company_id
//I could do
c2 = new Company({id: 2});
e2 = new Employee({name: 'Jane', company_id: 2});
e2.company = c2;
c2.employees.add(e);
e.company; // => c2
//I don't like this second method because the company property is set externally and I'd have to know it was being set everywhere in the code since the Employee model does not have any way to guarantee it exists
【问题讨论】: