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);
js trigger Event is used to invoke or callback the function for the given event or a space-delimited list of events. The subsequent arguments will be passed along to the event callbacks in order to trigger it. Parameter Values: event: It is used to bind an object with an event.
10) What is the usage of Backbone. sync? When Backbone. js wants to save or read a model to the Server, it calls out a function called Backbone.
js Event once() The event once method is just like event on method but it causes the bound callback to only fire once before being removed.
defaults() The Backbone. js defaults model is used to set a default value to a model. It ensures that if a user doesn't specify any data, the model would not fall with empty property.
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. i.e models.validate
should not return any errors for these values got from the server.
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