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
}
});
}
});
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.
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?
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);
};
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