Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a default error handler to all Backbone models?

Background:

Backbone model provides an option to register a fallback error handler that will be called each time a call to the server fails and no specific handler is provided.

MyModel = new Backbone.Model.extend({
  initialize: function(option) {
    this.on("error", this.fallbackErrorHandler);
  },

  fallbackErrorHandler: function() {
    // default behavior in case of an error
  },

  foo: function() {
    this.fetch();             // fallbackErrorHandler will be called
    this.fetch({              // the inline error handler will be called
      error: function() {
        // some specific code for this error
      }
    });
  }    
});

What I want to do:

I would like all the backbone models in my application to have a fallback error handler. But - I don't want to explicitly add the handler for each model. I would like to define and register the handler once and have it applied to each backbone model in my application. In addition, I don't want to change existing code and I don't want to change the way developers define Models in my application.

What I already tried:

I added an initializer which registers a handler on the Backbone.Model.prototype object.

App.Marionette.addInitializer(function() {
  Backbone.Model.prototype.on("error",function(){
     // default behavior in case of an error
  });
});

This code worked and my fallback error handler was called. However, the side affect of this code was that all error handlers registered in any backbone models in the application were registered on the Backbone.Model.prototype instead of on the Backbone.Model. So obviously this is not a good solution.

I also thought about defining MyModel which extends the Backbone.Model and registers the default handler. All other models in my application will then extend MyModel instead of directly extending Backbone.Model. However, I'm trying to make this seamlessly without having to change existing code and then instructing all the developer to extend MyModel instead of Backbone.Model.

Does anyone have a solution for this problem?

like image 305
Dana Shalev Avatar asked Dec 02 '12 19:12

Dana Shalev


1 Answers

Backbone uses jQuery's AJAX method calls by default. You can hook in to this directly, instead of using Backbone:

http://api.jquery.com/ajaxError/

If that doesn't give you what you want, you can override the "fetch" method in Backbone's model:


var originalFetch = Backbone.Model.prototype.fetch;

Backbone.Model.prototype.fetch = function(options){

  var originalError = options.error;

  options.error = function(model, error){
    if (originalError){ originalError(model, error); }

    // call your global error handler here.
    App.myGlobalErrorHandler(model, error);

  }

  originalFetch.apply(this, arguments);
};
like image 149
Derick Bailey Avatar answered Nov 14 '22 20:11

Derick Bailey