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.
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.
Share Improve this question edited Jan 21, 2014 at 13:51 David Victor 8279 silver badges31 bronze badges asked May 14, 2012 at 18:27 BoutranBoutran 10.1k16 gold badges59 silver badges86 bronze badges1 Answer
Reset to default 17Backbone 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() });