Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global error handler for Backbone.js ajax requests in Requirejs environment

define(function (require) {

    "use strict";

    var $         = require('jquery'),
        Backbone  = require('backbone'),
        Shell     = require('app/views/Frame/Shell'),
        Auth      = require('app/models/json/session');

    // Tell jQuery to watch for any 401 or 403 errors and handle them appropriately
    $.ajaxSetup({
        statusCode: {
            401: function(){
                // Redirect the to the login page.
                Backbone.history.navigate("login", true);            
            },
            403: function() {
                // 403 -- Access denied
                Backbone.history.navigate("login", true);
            }
        }   
    });

    return Backbone.Router.extend({

        routes: {
            "" : "home",
            "login" : "login",
            "logout" : "logout"
        },

        initialize: function (opt) {
            ev = opt.ev;            
            //Session.fetch();
        },

        home: function (id) {           
            new Dashboard({ev: ev});
        }

    });
});

The structure above I learned from http://clintberry.com/2012/backbone-js-apps-authentication-tutorial/ and I feel setting ajax error globally error like this not the proper way

What is the right way using backbone and requirejs?

like image 222
Muhaimin Avatar asked Nov 23 '25 10:11

Muhaimin


1 Answers

define(["Backbone"], function(Backbone){
    Backbone.ajax = function() {
        // Invoke $.ajaxSetup in the context of Backbone.$
        Backbone.$.ajaxSetup.call(Backbone.$, {
            statusCode: {
                401: function(){
                    // Redirect the to the login page.
                    Backbone.history.navigate("login", true);
                },
                403: function() {
                    // 403 -- Access denied
                    Backbone.history.navigate("login", true);
                }
            }
        });
        return Backbone.$.ajax.apply(Backbone.$, arguments);
    };    
});
like image 130
Muhaimin Avatar answered Nov 25 '25 09:11

Muhaimin