简体   繁体   中英

How to trigger an event when a Backbone model is saved?

If I have done my homework correctly, I have come to learn that Backbone does not have built-in save event that is triggered when a model is saved using the model's save method (even though there is a destroy event).

I have also learned that Backbone has a nifty mechanism for creating custom events using the Backbone.Events object. Using the latter works, but I have the impression that it is not fine-grained enough for my needs.

My setup is as follows. I have a table (view) built up of rows (views) with each row having a reference to a model. When the model is saved, I'd like to update/render the row to reflect the changes.

How does one go about creating a save event that is triggered when a model is saved so that the table row (view) that has a reference to that model is updated?

In other words, I'd like to be able to do the following:

this.model.bind('save', this.render);

Just 3 days ago, a commit was made to Backbone that triggers a sync event when the model is successfully saved. This commit hasn't been release yet, though, so you will need to download the source code from the github account if you want to use it.

View = Backbone.View.extend({
  initialize: function() {
    _.bindAll(this, 'onModelSaved');
    this.model.bind('sync', onSuccessCallback);
  },

  onModelSaved: function(model, response, options) {
    //perform your after save logic
  }
});

As of Backbone.js 1.0.0 you have sync event that is triggered if the model is saved successfully.

this.listenTo(this.model,'sync', this.render);

Note that, the change:attribute is fired first for relevant attributes if there is change in value of the attribute, followed by the change event then followed by the sync event. sync event is fired irrespective of the change in model. It is to denote that the model is now in sync with server values.

Also these event fire only if the values are valid. ie models.validate should not return any errors for these values got from the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM