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.
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
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With