How to rollback backbone.js model changes?

FWIW - i wrote a plugin to handle this automatically, specifically with the idea of "cancel" buttons in mind: http://github.com/derickbailey/backbone.memento


I dont believe there's a single method call for returning a model to its unedited state.. but the unedited values are available individually through model.previous(attribute) and collectively via model.previousAttributes.


Here is what I came up with:

var RollbackEnabledModel = Backbone.Model.extend({
  initialize: function() {
    this._initAttributes = _.clone(this.attributes);
  },
  parse: function(data) {
    this._initAttributes = _.clone(data);
    return data;
  },
  rollback: function() {
    this.set(this._initAttributes);
  }
});

model.previousAttributes() returns all of the previous attributes, while model.changedAttributes() returns all the changed attributes, but with their new values (or false if nothing has changed). So you could combine them to write a cancelChanges method in your prototype :

var MyModel = Backbone.Model.extend({
    cancelChanges: function() {
        var changed = this.changedAttributes();

        if(!changed)
            return;

        var keys = _.keys(changed);
        var prev = _.pick(this.previousAttributes(), keys);

        this.set(prev, {silent: true}); // "silent" is optional; prevents change event
    },

});

Tags:

Backbone.Js