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.
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() });
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