Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable Backbone.sync for a new model, and re enable sync *after* the user hits a save button

I have a Backbone collection model (with sub-models as elements) and views to edit it.

I would like it that when the model is initially created, to "turn off" sync, so the back end is never invoked until the user clicks on a button, then I would like to "turn on" the sync, and invoke the save method on the root model, in order to save it to the DB. Once a model it saved, it should behave like a normal model.

The goal is to avoid saving until the user determines that he is happy with what he has entered.

like image 996
Max L. Avatar asked May 14 '12 18:05

Max L.


1 Answers

Backbone will initially look for a model's local sync function before going to Backbone.sync.

Backbone.js Documentation: The sync function may be overriden globally as Backbone.sync, or at a finer-grained level, by adding a sync function to a Backbone collection or to an individual model.

Therefore you can do this:

var MyModel = Backbone.Model.extend({
    // New instances of this model will have a 'dud' sync function
    sync: function () { return false; }
});

var MyView = Backbone.View.extend({

   ...

   events : {
       'click #my-button' : 'enableSync',
       'click #my-save-button' : 'saveModel'
   },

   enableSync: function () {
       // If this view's model is still pointing to our fake sync function,
       // update it so that it references Backbone.sync going forward.
       if (this.model.sync !== Backbone.sync) {
          this.model.sync = Backbone.sync;
       }
   },

   saveModel: function () {
       // This won't actually do anything until we click '#my-button'
       this.model.save();
   }

   ...

});

var view = new MyView({ model: new MyModel() });
like image 103
isNaN1247 Avatar answered Nov 15 '22 22:11

isNaN1247