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

标签 javascript backbone.js backbone-relational

到目前为止,我的主干关系工作得相当好。我建立了良好的关系和反向关系(见下文)。当我最初在我的 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/

相关文章:

JavaScript 值可以在同一网页的框架之间来回传递吗?

javascript - 重绘: Bars not displaying on Print Preview with React-Responsive

javascript - 在 Marionette 中使用 appendHtml() 时是否可以避免添加默认 View 元素 "div"?

mysql - 数据建模,我应该使用多少 fk?

javascript - Backbone-relational 不能实例化两个 RelationalModel 对象

javascript - 用于登录和注销功能的 Backbone.js 架构

javascript - bootstrap 4 对 select 的验证似乎不起作用

javascript - 如何在 Backbone 中使用 setTimeout()?

javascript - 如何将 Backbone 函数作为参数传递

javascript - 将具有相同属性的模型嵌套到 div 中的最简单方法?