Last active
December 23, 2015 15:19
-
-
Save m3nt0r/6655042 to your computer and use it in GitHub Desktop.
A simple snapshot extension for Backbone models written mainly to introduce a rollback() feature
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.extend(Backbone.Model.prototype, { | |
/** | |
* Copy current attributes and store it in a private property | |
* | |
* @returns Model Instance | |
* @type Object | |
*/ | |
createSnapshot: function () { | |
this._snapshot = _.clone(this.attributes); | |
return this; | |
}, | |
/** | |
* Clear the snapshot property (assign empty hash) | |
* | |
* @returns Model Instance | |
* @type Object | |
*/ | |
resetSnapshot: function () { | |
this._snapshot = {}; | |
return this; | |
}, | |
/** | |
* Return the current snapshot (shallow copy) | |
* | |
* @returns Snapshot Hash | |
* @type Object | |
*/ | |
snapshot: function () { | |
if (_.isUndefined(this._snapshot)) { | |
this.resetSnapshot(); | |
} | |
return _.clone(this._snapshot); | |
}, | |
/** | |
* Replace the current model contents with the latest snapshot | |
* | |
* @uses Model.set() | |
* @returns Model Instance | |
* @type Object | |
*/ | |
rollback: function () { | |
if (_.isEmpty(this._snapshot) === false) { | |
this.set(this._snapshot); | |
} | |
this.resetSnapshot(); | |
return this; | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var test = new Backbone.Model({ | |
name:'mike' | |
}); | |
test.snapshot(); | |
// >> Object {} | |
test.createSnapshot().snapshot(); | |
// >> Object {name: "mike"} | |
test.set('name', 'jim'); | |
// Backbone.Model {cid: "c1", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…} | |
test.snapshot(); | |
// >> Object {name: "mike"} | |
test.attributes | |
// >> Object {name: "jim"} | |
test.rollback().attributes | |
// >> Object {name: "mike"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment