Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js: Is there a change since last server-save?

I have a backbone-Model. With model.set() I can set a local value, with model.save() I can save the whole model to the server.

How do I know, whether there was a change since the last server-save meaning the local version is dirty.

model.isNew(); works only if the model has never been saved to the server.

like image 564
knub Avatar asked Feb 09 '12 16:02

knub


2 Answers


EDIT: This answer was written prior to the 1.0 version of Backbone. As of the current Backbone version (1.2.2) hasChanged no longer reflects "since last save" changes. Instead, it reflects changes "since last set".


Listen for change events or check hasChanged.

If the model has changed, you can save on change. You can even wire your save method to fire when the change event happens.

If you don't want to save on change, then set a property for the model being dirty and clear it when you explicitly save.

Something like:

change: function(){
    this.dirty = true;
}

save: function(){
    // do your save
    if(success){
        this.dirty = false;
    }
}

isDirty: function(){
    return this.dirty
}
like image 117
tkone Avatar answered Sep 25 '22 08:09

tkone


I'm working with CouchDB and Couch has a _rev attribute that changes after every save success. I solved the problem of "since-last-server-save" by placing the following code in the models initialize function:

     initialize : function() {
        this.on('change',function(){
            if(this.hasChanged('_rev')) {
                this.isSaved = true;
            }else{
                this.isSaved = false;
            }
        },this);
      }
like image 22
Tim van Oostrom Avatar answered Sep 25 '22 08:09

Tim van Oostrom