如何将属性传递给Backbone.Model,我不希望将其作为属性处理?

aw *_*rud 23 javascript backbone.js

我有一个名为的Backbone.Model Company.我的Company模型有一个Employees包含Employee模型的Backbone.Collection .

当我实例化我的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
Run Code Online (Sandbox Code Playgroud)

she*_*sek 48

您可以随时从options对象中手动读取它并随意存储它.选项作为第二个参数传递给initialize方法:

var Employee = Backbone.Model.extend({
    initialize: function(attributes, options) {
        this.company = options.company;
    }
});
var shesek = new Employee({name: 'Nadav'}, {company: Foobar});
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用Backbone-relational,这样可以更轻松地处理包含对其他模型和集合的引用的模型.

您可能也有兴趣将toJSON()递归(我提交给他们的问题跟踪器的补丁)