Requirejs环境中Backbone.js ajax请求的全局错误处理程序

时间:2014-05-25 05:11:01

标签: backbone.js requirejs

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

    });
});

上面我从http://clintberry.com/2012/backbone-js-apps-authentication-tutorial/学到的结构,我觉得设置ajax错误全局错误,这样不是正确的方法

使用backbone和requirejs的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

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