Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally listen for Backbone.js Model.save

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?

like image 483
mbeasley Avatar asked Dec 19 '25 02:12

mbeasley


1 Answers

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.

like image 81
Paul Hoenecke Avatar answered Dec 21 '25 17:12

Paul Hoenecke