Saturday, 17 August 2013

Backbone.js: Always detect when a model has an attribute set, not /just/ changed

Backbone.js: Always detect when a model has an attribute set, not /just/
changed

In Backbone, when I set the attribute of a Model to the same value it had
before, "change" events do not trigger.
My View:
initialize: function() {
this.$lastRollResult = this.$el.find('#lastRollResult');
this.listenTo(this.model, 'change:lastRoll', this.render);
},
render: function() {
this.$lastRollResult
.html(this.model.get('lastRoll'))
.addClass('shaking');
var self = this;
setTimeout(function() {
self.$lastRollResult.removeClass('shaking');
}, 1000);
},
events: {
'click #button': function() {
this.model.set('lastRoll', getRandomInteger(1, 6));
}
}
Sometimes when I call getRandomInteger(), the int will be the same as the
previous one, causing my .set('lastRoll', int) to not register as a
"change" event. But this means my "shaking" class won't be applied, and
that is bad.
How can I make Backbone always recognize when an attribute is set, even if
the value I set was the same? Is there some sort of "set" event? (Didn't
see one in the docs.)
Edit: I'm aware that there is probably a {silent: true} / .trigger() hack
to accomplish this, but is there any "clean" or "semantic" way to always
recognize a .set() call?

No comments:

Post a Comment