Search code examples
javascriptbackbone.js

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.


Solution


  • 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
    }