如何在路由器触发之前同步模型获取登录



我有如下代码,我希望在触发任何子例程之前始终调用"身份验证检查",无论直接访问哪个url。由于fetch是异步的,目前成功回调总是在子例程初始化后触发,这对我来说不好,因为我想在一切发生之前进行身份验证检查。感谢

var Router = Backbone.Router.extend({
    routes: {
        'A/*subroute': 'A',
        'B/*subroute':'B'
    },
    initialize: function() {
        this.checkUser();
    }
    A:function(subroute) {
        xx
    },
    B:function(subroute) {
        xx
    }
    checkUser: function() {
        var identity = new Common.model.Identity( );
        var mainrouter1=this;
        identity.fetch( { "xhrFields": { "withCredentials" : true }, success : function ( model ) {
            console.log("authentication check");
        }
    });
    }
})

您需要的是在筛选路由之前。您可以使用一个可用于主干网的路由过滤器库。喜欢https://github.com/boazsender/backbone.routefilter和https://github.com/fantactuka/backbone-route-filter

考虑骨干路由筛选器(上面的第二个链接)。你的代码看起来像下面的代码:

var Router = Backbone.Router.extend({
    routes: {
        'A/*subroute': 'A',
        'B/*subroute':'B'
    },
    initialize: function() {
        this.checkUser();
    },
    before: {
    '*any': function(fragment, args) {
      var hasAccess = checkUser(); // Do your authentication logic
      if (!hasAccess) {
        Backbone.navigate('/', true);
      }
      return hasAccess; //return true if you want to proceed to routes else return false
    },
    A:function(subroute) {
        xx
    },
    B:function(subroute) {
        xx
    }
    checkUser: function() {
        var identity = new Common.model.Identity( );
        var mainrouter1=this;
        identity.fetch( { "xhrFields": { "withCredentials" : true },
         async: false,
         success : function ( model ) {
            console.log("authentication check");
        }
    });
    }
})

由于checkUser()方法中有ajax请求,这是异步的,因此可能需要对其进行一些修改,使其与路由过滤器一起工作。就像通过添加"async:false"使其同步一样。

最新更新