backbone-relational .set()方法不更新相关模型

Squ*_*kle 5 javascript backbone.js backbone-relational

到目前为止,我的骨干关系工作得相当好.我建立了良好的关系和反向关系(见下文).当我最初调用.fetch()我的Country模型实例时,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
            }
        }
    ]
});
Run Code Online (Sandbox Code Playgroud)

JSON响应 country.fetch()

{
  "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
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

一如既往,我们将非常感谢任何帮助.

Squ*_*kle 2

因此,骨干关系似乎专门放弃了自动更新关系(请参阅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 );
    }
};
Run Code Online (Sandbox Code Playgroud)

(请注意,这不处理从集合中删除模型,仅处理现有模型的更新以及向集合添加新模型)