Skip to content

Instantly share code, notes, and snippets.

@berzniz
Last active October 22, 2021 20:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berzniz/8010245 to your computer and use it in GitHub Desktop.
Save berzniz/8010245 to your computer and use it in GitHub Desktop.
A model that "knows" if it has unsaved changes
// 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);
}
});
@priithaamer
Copy link

Thanks for this! Why override sync method instead of listening to "sync" event in initializer? Wouldn't this be shorter:

var ChangeTrackableModel = Backbone.Model.extend({

  hasChangedSinceLastSync: false,

  initialize: function() {
    this.listenTo(this, 'change', this.modelChanged);
    this.listenTo(this, 'sync', this.modelSynced);
  },

  modelChanged: function() {
    this.hasChangedSinceLastSync = true;
  },

  modelSynced: function() {
    this.hasChangedSinceLastSync = false;
  }
});

@rafegoldberg
Copy link

rafegoldberg commented Aug 24, 2017

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