Backbone 当 silent 为 true 时,模型属性不是绑定值以查看

Backbone Model attributes are not binding value to view when silent is true

我在为模型设置值时遇到问题。

这是我的代码:

SuperModel = Backbone.Model.extend({

    initialize: function() {
        //some code......
    }
});

ChildModel = SuperModel.extend({

    initialize: function() {

        //some code..........
        SuperModel.prototype.initialize.call(this, arguments);
    }
});

在我看来,我试图用 { silent : true }.

为模型(childModel 的实例)设置一个值

模型使用 ModelBinder 与视图绑定。

this.model.set('firstName','tom',{silent:true}); // Not Working
this.model.set('firstName','tom'); //  Working
this.model.set('firstName','tom',{silent:true}).trigger('change'); // Not Working

当我删除 SuperModel.prototype.initialize.call(this,arguments); 时,silent:true 正在工作(值开始设置为 UI)。

在这里我可以看到模型中的值,但没有反映在我的 UI 上。

首先,如果您要将 arguments 传递给其父 initialize 函数,则需要使用 apply and not call.

SuperModel.prototype.initialize.apply(this, arguments);

然后,如果您通过 { silent: true },则不会触发 the Backbone's events。如果以后要模拟事件,应该正确模拟:

var options = { silent: true },
    value = 'tom';

this.model.set('firstName', value, options);
this.model.trigger('change:firstName', this.model, value, options)
          .trigger('change', this.model, options);

但这违背了 silent 选项的目的。

我发现问题出在父模型中 SuperModel 我有一行代码

this.set('editedElements', someValue);

我不知道当我将 { silent: true } 作为选项传递时该值没有反映在 ui 上的真正原因,但后来当我删除代码时 this.set(...) 它开始了正在工作。

我修改如下

this.set('editedAttributes'),...) -> this.attributes['editeAttributes'] = ...

现在我通过 { silent: true } 的那些模型值反映在 UI。