当我在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
答案 0 :(得分:1)
应在原型上定义idAttribute属性。您的代码为类的每个实例定义了idAttribute。
根据您要支持的浏览器,您可以使用getter方法在TypeScript中执行此操作。
export class Animal extends Backbone.RelationalModel {
public get idAttribute () { return 'AnimalId' }
}
使用vanilla JavaScript定义后,您也可以将其添加到类中。
Animal.prototype.idAttribute = 'AnimalId';
答案 1 :(得分:0)
咦。如果在初始化中设置idAttribute而不是构造函数,它似乎有效:
initialize: function(attributes) {
this.id = attributes['AnimalId'] || attributes['id'];
},