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
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, 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 }, });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With