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
Take a look at NYTimes' backbone.trackit. It tracks multiple changes to the model instead of only the most recent change like
model.changedAttributes()
andmodel.previousAttributes()
. From the README: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:
FWIW - i wrote a plugin to handle this automatically, specifically with the idea of "cancel" buttons in mind: http://github.com/derickbailey/backbone.memento
model.previousAttributes()
returns all of the previous attributes, whilemodel.changedAttributes()
returns all the changed attributes, but with their new values (orfalse
if nothing has changed). So you could combine them to write acancelChanges
method in your prototype :