I'd like to append Backbone's native Model.save() method with a custom logging method that logs success and errors. I know that on a per model basis I can call something like:
myModel.save().success(function() {
// do something cool
});
But rather than adjusting every call to various models' save events, I'd like to simply listen for the save event on any model. One way that I think I want to avoid is actually modifying the Backbone.Model.prototype.save method (although if someone has an elegant way to do this I'm open to it).
Any thoughts on how to create such an event listener?
If all your models/collections are using the default Backbone.sync method, you could create a new sync method to do the logging.
var originalSync = Backbone.sync;
var loggingSync = function(method, model, options) {
// call original Backbone.sync
var promise = originalSync(method, model, options);
promise.done(function() {
// if method is 'update' or 'create', log success
});
promise.fail(function() {
// if method is 'update' or 'create', log failure
});
return promise;
};
Backbone.sync = loggingSync;
By default, Model.sync and Collection.sync both proxy through to Backbone.sync, so if you are using default sync, this change would take care of it.
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