I have an application using Backbone.js that has various AJAX requests. I want to be able to intercept all AJAX requests and do some pre and post request functions without having to specify these functions at the point of definition.
An example of what I want to do is if the response from the request indicated that the user is not logged in, then a full screen modal is displayed.
I have looked at doing something like the following via jQuery:
jQuery.ajaxSetup({
beforeSend: function() {
return console.log("mybefore");
}
});
but this seems to miss XHR requests using sockets.
I have also briefly looked at doing something like the following:
XMLHttpRequest.prototype.reallySend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
console.log('mybefore');
this.reallySend(body);
};
With this example, I wasn't sure how to do the after
So after all that, my question is: Is there an elegant way of overriding ajax functions to do pre and post processing without altering the way requests can be made.
(Any backbone.js specific solutions would be nice too)