Dinesh
Dinesh

Reputation: 4559

bootstrap fires event twice when model changes - "change" and "change:model-attribute-name"

I have a Backbone.Model that represents the user inputs. In the UI callback, I update a model object's properties using xxx.set(). The Backbone.View manager listens to change events as follows:

// create view viewObj with a new model instance modObj
this.listenTo( this.modObj, "all", function() {
                alert("event! from FBox: " + arguments[0] + "; arg2=" + arguments[2]) });

I was expecting one but actually got two callbacks when something on screen, say a dropdown, was changed.

1. change:name-of-changed-model-attribute
2. change

Is this something to be expected and handled, or is my listening method in need of fixing? I would like to avoid having to type all event names individually as that would mean too much code maintenance.

Thanks.

Upvotes: 0

Views: 121

Answers (2)

ayanami
ayanami

Reputation: 1706

Yes, this is by design.

If you want to update the UI when something changes, you can just listen to "change" event, not "all".

Upvotes: 1

krasu
krasu

Reputation: 2037

This happens, because backbone triggering two events on change "change" and "change:[attribute]"

From backbone source code:

 if (!silent) {
    if (changes.length) this._pending = true;
    for (var i = 0, l = changes.length; i < l; i++) {
      this.trigger('change:' + changes[i], this, current[changes[i]], options);
    }
  }
  ....
  if (!silent) {
    while (this._pending) {
      this._pending = false;
      this.trigger('change', this, options);
    }
  }

Upvotes: 1

Related Questions