Created
May 28, 2013 14:25
-
-
Save martinnormark/5663133 to your computer and use it in GitHub Desktop.
Change tracking for Backbone models
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
| (function () { | |
| Backbone.ChangeAwareModel = Backbone.Model.extend({ | |
| initialize: function () { | |
| Backbone.Model.prototype.initialize.apply(this, arguments); | |
| _.bindAll(this, "mark_to_revert", "revert"); | |
| this.attributesChanged = []; | |
| this.on("change", this.trackChanges, this); | |
| return this.mark_to_revert(); | |
| }, | |
| save: function (attrs, options) { | |
| options || (options = {}); | |
| var self = this, | |
| value = null, | |
| success = options.success; | |
| options.success = function (resp) { | |
| self.trigger("save:success", self); | |
| if (success) { | |
| success(self, resp); | |
| } | |
| return self.mark_to_revert(); | |
| }; | |
| this.attributes["_previousAttributes"] = _.pick(this._revertAttributes, _.map(this.attributesChanged, function (value, key, list) { return value.Key; })); | |
| this.attributes["_changedAttributes"] = _.clone(this.attributesChanged); | |
| this.trigger("save", this); | |
| value = Backbone.Model.prototype.save.call(this, attrs, options); | |
| return value; | |
| }, | |
| mark_to_revert: function () { | |
| return this._revertAttributes = _.clone(this.attributes); | |
| }, | |
| revert: function () { | |
| if (this._revertAttributes) { | |
| return this.set(this._revertAttributes, { | |
| silent: true | |
| }); | |
| } | |
| }, | |
| trackChanges: function (model, options) { | |
| var that = this; | |
| for (var key in model.changedAttributes()) { | |
| var modelChange = _.find(that.attributesChanged, function (change) { | |
| return change && change.Key === key; | |
| }); | |
| if (modelChange) { | |
| modelChange.Value = model.get(key); | |
| } else { | |
| that.attributesChanged.push({ Key: key, Value: model.get(key) }); | |
| } | |
| } | |
| } | |
| }); | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment