到目前为止,我的主干关系工作得相当好。我建立了良好的关系和反向关系(见下文)。当我最初在我的 Country
模型实例上调用 .fetch()
时,nominees
数组被解析为 nominee
完美的模型。
当我稍后再次调用 .fetch()
时,这些相关模型不会更新,即使 nominee
数据已更改(例如,投票计数已增加).从本质上讲,似乎 Backbone 的 .set()
方法最初理解关系,但随后不理解。
国家模式
var Country = Backbone.RelationalModel.extend({
baseUrl : config.service.url + '/country',
url : function () {
return this.baseUrl;
},
relations : [
{
type : Backbone.HasMany,
key : 'nominees',
relatedModel : Nominee,
collectionType : Nominee_Collection,
reverseRelation : {
key : 'country',
includeInJSON : false
}
}
]
});
country.fetch()
上的 JSON 响应
{
"entrant_count" : 1234,
"vote_count" : 1234,
"nominees" : [
{
"id" : 3,
"name" : "John Doe",
"vote_count" : 1,
"user_can_vote" : true
},
{
"id" : 4,
"name" : "Marty McFly",
"vote_count" : 2,
"user_can_vote" : true
}
]
}
一如既往,我们将不胜感激。
最佳答案
因此看起来 backbone-relational 专门放弃了自动更新关系(参见 updateRelations
方法),并简单地发出一个 relational:change:nominees
事件,您的模型可以目标。但是,如果您希望以编程方式更新相关模型,只需按如下方式修改 updateRelations
方法:
Backbone.RelationalModel.prototype.updateRelations = function( options ) {
if ( this._isInitialized && !this.isLocked() ) {
_.each( this._relations || [], function( rel ) {
// Update from data in `rel.keySource` if set, or `rel.key` otherwise
var val = this.attributes[ rel.keySource ] || this.attributes[ rel.key ];
if ( rel.related !== val ) {
this.trigger( 'relational:change:' + rel.key, this, val, options || {} );
// automatically update related models
_.each(val, function (data) {
var model = rel.related.get(data.id);
if (model) {
model.set(data);
} else {
rel.related.add(data);
}
});
}
}, this );
}
};
(请注意,这不处理从集合中删除模型,仅处理现有模型的更新以及向集合添加新模型)
关于javascript - backbone-relational .set() 方法不更新相关模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13144494/