Backbone一对一关系,如何获取父模型数据?
Backbone relational one to one relation, how to get parent's model data?
exampleData = {
id: 1,
name: 'A',
house: {
address1: 'California'
address2: 'California'
}
}
House = Backbone.RelationalModel.extend({
urlRoot: function urlRoot() {
var personId = this.get('person').id; // this.get('person') is null
}
});
Person = Backbone.RelationalModel.extend({
relations: [
{ // Create a (recursive) one-to-one relationship
type: Backbone.HasOne,
key: 'house',
relatedModel: House,
reverseRelation: {
type: Backbone.HasOne,
key: 'person'
}
}
],
initialize: function() {
}
});
我需要获取House模型中人物的模型数据,
但是this.get('person')returns null,即使我设置了reverseRelation。
如何获取内部人员的数据?
我认为您的代码无法运行。模型的定义有点错误。当你定义关系时,它应该是对对象的引用,而不是字符串值:
relatedModel: House // instead of 'House' as a string
然后你可以通过 getters 来引用每个模型,例如:
houseModel.get("person");
personModel.get("house");
exampleData = {
id: 1,
name: 'A',
house: {
address1: 'California'
address2: 'California'
}
}
House = Backbone.RelationalModel.extend({
urlRoot: function urlRoot() {
var personId = this.get('person').id; // this.get('person') is null
}
});
Person = Backbone.RelationalModel.extend({
relations: [
{ // Create a (recursive) one-to-one relationship
type: Backbone.HasOne,
key: 'house',
relatedModel: House,
reverseRelation: {
type: Backbone.HasOne,
key: 'person'
}
}
],
initialize: function() {
}
});
我需要获取House模型中人物的模型数据,
但是this.get('person')returns null,即使我设置了reverseRelation。
如何获取内部人员的数据?
我认为您的代码无法运行。模型的定义有点错误。当你定义关系时,它应该是对对象的引用,而不是字符串值:
relatedModel: House // instead of 'House' as a string
然后你可以通过 getters 来引用每个模型,例如:
houseModel.get("person");
personModel.get("house");