Tutte le risposte che suggeriscono l'ascolto per le modifiche (con eventi) sono corrette a meno che non si passa {silenzioso: vero} opzione. In tal caso, è necessario sovrascrivere il metodo set predefinito per salvare gli attributi che sono stati modificati e ripristinare tale elenco dopo aver chiamato il metodo di salvataggio.
MidnightLightning's answer non è corretta. Se si chiama il metodo di impostare due volte, quindi changedAttributes torneranno solo gli attributi che ha cambiato da chiamata ultimo insieme - è nella documentazione Backbone:
changedAttributesmodel.changedAttributes([attributes])
recuperare un hash di attributi solo del modello che hanno cambiato da quando il ultimo set, o falso se non ce ne sono.
Nel mio caso ho risolto il problema con questo codice:
(function(_, Backbone) {
'use strict';
var _set = Backbone.Model.prototype.set,
_save = Backbone.Model.prototype.save;
_.extend(Backbone.Model.prototype, {
set: function(key, val, options) {
var options = this._getOptions(key, val, options),
toReturn = _set.call(this, key, val, options);
if(!_.isUndefined(options) && options.silent && !!this.changedAttributes()) {
this.silentChanges = _.extend([], this.silentChanges);
[].push.apply(this.silentChanges, _.keys(this.changedAttributes()));
}
return toReturn;
},
save: function(key, val, options) {
var options = this._getOptions(key, val, options),
toReturn = _save.call(this, key, val, options);
if(!_.isUndefined(options) && options.triggerSilents) {
this.triggerSilentChanges();
}
return toReturn;
},
unset: function(key, options) {
if(!_.isUndefined(options) && options.silent) {
this.silentChanges = _.extend([], this.silentChanges, _.keys(this.changedAttributes()));
}
},
triggerSilentChanges: function() {
if(!_.isEmpty(this.silentChanges)) {
var that = this;
_.each(this.silentChanges, function(key) {
that.trigger('change:' + key);
that.silentChanges = _.without(that.silentChanges, key);
});
Backbone.Model.prototype.trigger.call(this, 'change');
}
},
_getOptions: function(key, val, options) {
if(key == null || _.isObject(key)) {
return val;
}
return options;
}
});
})(_, Backbone);
Se voglio ottenere tutto è cambiato attributi Io uso proprietà silentChages all'interno del modello. Se voglio attivare l'evento per tutti gli attributi set/unset quando salvi aggiungo l'opzione 'triggerSilents: true'. Posso anche attivare manualmente tutti gli eventi di modifiche chiamando il metodo triggerSilentChanges.
il dirty bit non è la stessa cosa di controllare se è cambiato (a seconda della definizione). Es: il modello potrebbe inizialmente essere isGood: true, passa a isGood: false, quindi torna a isGood: true. In questo caso, il bit dirty potrebbe essere attivo, ma il modello non viene effettivamente modificato. Va bene? – Matt