Truly change a model attribute silently in Backbon

2019-04-10 04:19发布

Is there a way I can change attributes on a model without ever firing a change event? If you pass {"silent":true} right now, the next time an attribute is changed, the silent change event will be triggered. Can I change an attribute safely without the change event ever being triggered?

from change, Backbone 0.9.2:

// Silent changes become pending changes.
for (var attr in this._silent) this._pending[attr] = true;

// Silent changes are triggered.
var changes = _.extend({}, options.changes, this._silent);
this._silent = {};
for (var attr in changes) {
    this.trigger('change:' + attr, this, this.get(attr), options);

标签: backbone.js
3条回答
甜甜的少女心
2楼-- · 2019-04-10 05:00

You can change model attributes directly using model.attributes['xyz'] = 123.

查看更多
不美不萌又怎样
3楼-- · 2019-04-10 05:02
item.set(
        {
           sum: sum
          ,income: income
       },
       {silent: true}
    );

since backbone 0.9.10

查看更多
你好瞎i
4楼-- · 2019-04-10 05:12

I think the cleanest way if you really want to default to silent (but still be able to do silent:false) sets would be to override set. This should do it:

var SilentModel = Backbone.Model.extend({

    set: function(attrs, options) {
        options = options || {};
        if (!('silent' in options)) {
            options.silent = true;
        }
        return Backbone.Model.prototype.set.call(this, attrs, options);
    }
});
查看更多
登录 后发表回答