当我在我的 Backbone 模型上定义自定义 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