How to rollback backbone.js model changes?

2019-06-14 21:18发布

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

标签: backbone.js
5条回答
一夜七次
2楼-- · 2019-06-14 21:50

Take a look at NYTimes' backbone.trackit. It tracks multiple changes to the model instead of only the most recent change like model.changedAttributes() and model.previousAttributes(). From the README:

var model = new Backbone.Model({id:1, artist:'Samuel Beckett', 'work':'Molloy'});
model.startTracking();

model.set('work', 'Malone Dies');
console.log(model.unsavedAttributes());  // >> Object {work: "Malone Dies"}

model.set('period', 'Modernism');
console.log(model.unsavedAttributes());  // >> Object {work: "Malone Dies", period: "Modernism"}

model.save({}, {
    success: function() {
        console.log(model.unsavedAttributes());  // >> false
    }
});

In addition, the library adds functionality to resetAttributes to their original state since the last save, triggers an event when the state of unsavedChanges is updated, and has options to opt into prompting to confirm before routing to a new context.

查看更多
爷的心禁止访问
3楼-- · 2019-06-14 21:51

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.

查看更多
【Aperson】
4楼-- · 2019-06-14 21:53

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);
  }
});
查看更多
ら.Afraid
5楼-- · 2019-06-14 21:56

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

查看更多
老娘就宠你
6楼-- · 2019-06-14 21:59

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(model.previousAttributes(), keys);

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

});
查看更多
登录 后发表回答