In Backbone, how can I call a method every time I trigger an Ajax call?

So, every time I have an AJAX call in my Backbone app, I want to hit a method that essentially leaves the server and checks if I am validated using a JWT token. This token has an expiration time, so let's say the expiration time is 1 minute for the sake of argument. If I stay on this page and download the file after 30 seconds, everything is fine. If I upload the file after 2 minutes, it should check if I am not authenticated, see that I am not, and upload me back to the login page.

Now, of course, I could add this call to a method in each of my AJAX calls, sort of like this (I wouldn't do it in an if like below, but that's just to illustrate my point ...)

if (isAuthenticated === true) {

            $.ajax({
                url: '/dosomething',
                type: 'POST',
                data: data,
                processData: false,
                cache: false,
                contentType: false
            }).done(function () {

                //do stuff here
            }).fail(function (jqXHR, textStatus) {
                console.log(jqXHR);
                console.log(textStatus);
            });

}

      

The problem is I have a lot of AJAX calls, so I feel like I'm wasting time adding this method call to all AJAX calls. I'm not too familiar with all Backbone ins and outs, so I just wondered if there is something I could do to bind my method to all AJAX calls?

Hooray!

+3


source to share


1 answer


Have you tried ajaxSend? https://api.jquery.com/ajaxSend/



$(document).ajaxSend(function(e, xhr) {
    if (isAuthenticated === false){
        xhr.abort();
    }
});

      

0


source







All Articles