Can I force an update to a model attribute to register as a change, even if it is not?

I know that I can set the value of the Backbone model attribute so that it does not raise a change event using {silent: true}. I also know that if I set the model attribute to the value that it already has, it will not raise a change event, which is almost always good. However, is there a way to force a model update to trigger a change event, even if it is set to the same value?

So, if in my model I installed:

defaults:{
    attributeToChange: "myValue"
}

And then in the view using this model, I call:

this.model.set('attributeToChange', 'myNewValue', {silent:true});

the value will change, but the change event will not be fired. But what if I wanted the change event to fire whenever the attribute value was set, regardless of what it was set for? So if instead I just did

this.model.set('attributeToChange','myValue');

is there a parameter that i can add that will make this look like a change? I believe that I can use

this.model.trigger('change:attributeToChange');

but I would like to know if there is a way to make the change event fire without this.

Bonus question: if I set the model attribute to the value that it already has, does that attribute make the previous value the value that it had before I initiated the change?

this.model.set('attributeToChange','someValue');
this.model.set('attributeToChange','anotherValue');
this.model.set('attributeToChange','anotherValue');
console.log(this.model.previous('attributeToChange')); //someValue or anotherValue?
+5
source share
3 answers

Backbone, Backbone (. https://github.com/documentcloud/backbone/blob/master/backbone.js#L342).

, changes , Backbone "change: {key}" , " " "true". (. https://github.com/documentcloud/backbone/blob/master/backbone.js#L357).

, "change" ( , "" true).

, , , Backbone, set, , @Loamhoof.

+4

, . , set, . ( "" , ).

, ( ).
, .

var set = Backbone.Model.prototype.set;
Backbone.Model.prototype.set = function() {
  // do stuff before
  set.apply(this, arguments);
  // do stuff after
  this.trigger('myCustomEvent');
  return this;
};

( , , , .)

+3

I had this problem when I installed an existing atrribute model of another object that has the same keys and values. It was a different object, but the model did not raise a “change” event. Therefore, for this problem, I used this solution: I set the attributes for the model in "silent" mode, after which I ran the "change" -event for a specific attribute. eg.

this.model.set({currentPage: page,
                currentPanel: panel}, {silent:true});
this.model.trigger('change:currentPanel');
+1
source

All Articles