Last active
October 22, 2021 20:25
-
-
Save berzniz/8010245 to your computer and use it in GitHub Desktop.
A model that "knows" if it has unsaved changes
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
// This model (and any other model extending it) will be able to tell if it is synced with the server or not | |
var ChangeTrackableModel = Backbone.Model.extend({ | |
hasChangedSinceLastSync: false, | |
initialize: function() { | |
// If you extend this model, make sure to call this initialize method | |
// or add the following line to the extended model as well | |
this.listenTo(this, 'change', this.modelChanged); | |
}, | |
modelChanged: function() { | |
this.hasChangedSinceLastSync = true; | |
}, | |
sync: function(method, model, options) { | |
options = options || {}; | |
var success = options.success; | |
options.success = function(resp) { | |
success && success(resp); | |
model.hasChangedSinceLastSync = false; | |
}; | |
return Backbone.sync(method, model, options); | |
} | |
}); |
these pointers are much appreciated. @priithaamer's suggestion is quite useful– succinct and legible, a rare combo!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this! Why override sync method instead of listening to "sync" event in initializer? Wouldn't this be shorter: