最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 17

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论