Pregunta

I have code as below, I want the "authentication check" always be called before any subrouter triggered no matter what url will be access directly. as the fetch is async, currently the success callback always triggered after the subroute initialize, it's not good for me, as I want to do authentication check before everything happens. thanks

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");
        }
    });
    }
})
¿Fue útil?

Solución

What you need is before filter for the routes. You can use one of the route filter libraries available for backbone. Like https://github.com/boazsender/backbone.routefilter and https://github.com/fantactuka/backbone-route-filter

Consider backbone-route-filter(2nd link above). Your code will look something like the one below:

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

Since you have ajax request in you checkUser() method which is async, you may need to modify it a bit to make it work with route filter. Like making it synchronous by adding "async: false".

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top