Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rollback backbone.js model changes?

Tags:

I have a "Cancel" button on my page which should reverts all the changes I made back to the state it was loaded from server..

I guess I need to store an initial state of Backbonejs model and restore a current (changed) state back to initial.

What is the best way to achieve that?

Thank you

like image 754
arkadiy kraportov Avatar asked Jun 28 '11 05:06

arkadiy kraportov


2 Answers

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

like image 164
Derick Bailey Avatar answered Oct 02 '22 21:10

Derick Bailey


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     },  }); 
like image 24
Tobias J Avatar answered Oct 02 '22 23:10

Tobias J