In Backbone.js, why do silent changes trigger change events eventually?

后端 未结 2 854
半阙折子戏
半阙折子戏 2021-02-05 04:29

When I pass {\"silent\":true} while setting an attribute in a Backbone model, why doesn\'t that just suppress the change:attribute event? What is the a

相关标签:
2条回答
  • 2021-02-05 04:43

    In backbone 0.9.2 the set function runs validation before any changes are updated.

      // Run validation.
      if (!this._validate(attrs, options)) return false;
    

    In case of {silent: true} option is passed, the validation code will not be executed.

      if (options.silent || !this.validate) return true;
    

    That means, model.set({value: 100}, {silent: true}); is able to set "invalid" value into model, so attributes are updated, but change event's are not firing.

    It is useful, then you want to update some field and prevent whole mode validation, so if model is not yet completed, the change still propagated to attributes. But you usually you also want the view to show the change, so you have to manually call model.change() or model.trigger('change:value', model, value).

    0 讨论(0)
  • 2021-02-05 04:50

    This has confused me for some time as well.

    The reason is that {silent:true} does not mean "Do everything as normal, but just don't trigger the event".

    From various comments and answers by @jashkenas, what it seems to mean is "simply change the attribute value (and add it to the 'changedAttributes' hash), but defer all other "change-related" activities until later".

    'silent' doesn't prevent the change event for that/those properties, it simply queues up the 'announcement' until the next change event is triggered.

    So, its probably better named something like defer.

    Relevant information:

    https://github.com/documentcloud/backbone/pull/850

    the point of a "silent" change is that it isn't considered a change from the models point of view. Later, when the change actually occurs, you get the full difference all at once.

    https://github.com/documentcloud/backbone/issues/870

    Because the point of silent changes is that you're allowed to twiddle with the internal state of your model, temporarily, without actually making a change. Later, when the attribute actually changes, the validation runs and events are emitted. It wouldn't make sense to emit an error event when making a silent change.

    Update 4/7/2013

    Note: I have not tested this to confirm behavior, this is just based on my reading of the release notes...

    As of Backbone 0.9.10, the behavior described above has changed. In that version (and newer), silent:true suppresses the change:attr events entirely - not just delays them.

    http://backbonejs.org/#changelog

    0 讨论(0)
提交回复
热议问题