Is there way to bind one error handler for ajax requests that performs by backbone.js?
My situation: I can get 401 (Unauthorized) at any time, so I need to show login popup.
Backbone's sync triggers an 'error' event when errors occur. So one approach you could take is to extend Backbone's Model and Collection objects to add these add-on error checks. It would look something like this:
ErrorHandlingModel = Backbone.Model.extend({ initialize: function(attributes, options) { options || (options = {}); this.bind("error", this.defaultErrorHandler); this.init && this.init(attributes, options); }, defaultErrorHandler: function(model, error) { if (error.status == 401 || error.status == 403) { // trigger event or route to login here. } } }); OtherModel = ErrorHandlingModel.extend({ });
and you would do something similar for the Collection object. I haven't tested the above, but think its pretty close. Obviously, you would choose better class names. The init method just enables subclasses to get a chance to do their own initialization.
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