idAttribute属性应该在原型上定义。您的代码为类的每个实例定义idAttribute。
当我在主干模型上定义自定义idAttribute时,findOrCreate将不起作用,即
Uncaught Error: Cannot instantiate more than one Backbone.RelationalModel
with the same id per type!
我认为这是一个TypeScript问题。我不知道它是否相关,但当你用TypeScript创建一个类并将idAttribute设置为如下时,你会看到对象本身有一个显式的"idAttribute"属性,而当你用纯javascript做它时,情况并非如此;
module Application.Models {
export class Zoo extends Backbone.RelationalModel {
constructor(options?) {
this.relations = [{
type: Backbone.HasMany,
key: 'animals',
relatedModel: 'Application.Models.Animal',
collectionType: 'Application.Models.AnimalCollection',
reverseRelation: {
key: 'livesIn',
includeInJSON: 'id'
}
}];
super(options);
}
}
export class Animal extends Backbone.RelationalModel {
constructor(options?) {
this.idAttribute = "AnimalId";
super(options);
}
}
export class AnimalCollection extends Backbone.Collection {
constructor(options?) {
super(options);
this.model = 'Application.Models.Animal';
}
}
}
var artis = new Application.Models.Zoo({ name: 'Artis' });
var lion = new Application.Models.Animal({ AnimalId: 123, species: 'Lion', livesIn: artis });
Application.Models.Animal.findOrCreate({ AnimalId: 123 }); // FIRST TIME FINE
Application.Models.Animal.findOrCreate({ AnimalId: 123 }); // SECOND TIME - NOT FINE
根据您想要支持的浏览器,您可以在TypeScript中使用getter方法来实现这一点。
export class Animal extends Backbone.RelationalModel {
public get idAttribute () { return 'AnimalId' }
}
您也可以在使用普通JavaScript定义它之后将它添加到类中。
Animal.prototype.idAttribute = 'AnimalId';
嗯。如果在initialize而不是构造函数中设置idAttribute,它似乎可以工作:
initialize: function(attributes) {
this.id = attributes['AnimalId'] || attributes['id'];
},