为了触发在执行路由回调之前触发的事件,我使用以下插件:
https://github.com/boazsender/backbone.routefilter
这个效果很好。
但是,在检查用户当前是否在后端进行身份验证之后,我希望将用户重定向到某个路由(触发器设置为true)。
我目前正在使用Ajax请求来完成这个任务,但显然这给我带来了麻烦。
在下面的代码中,ajax回调只有在路由器的'home‘回调已经执行(或任何其他路由)之后才会被触发。
我怎么才能完成这件事?
我有以下代码:
var Router = Backbone.Router.extend({
/* --- 1. Route management --- */
routes: {
'': 'landing_page',
'(/)login': 'login',
'(/)home': 'home',
'*actions': 'defaultAction',
},
before: function(route, params) {
var getAuthStatus = APP.controllers.auth_controller.isLogged();
var self = this;
$.when(getAuthStatus).then(function(response){
var auth_status = Object.keys(response.success)[0];
if(auth_status === 'guest'){
console.log(auth_status);
self.navigate("login", {trigger: true});
}
});
}
});
ajax请求:
Auth_controller.prototype.isLogged = function(){
//Check if the user is authenticated
var getAuthStatus = this.auth_model.fetch();
return getAuthStatus;
};
编辑:“前”方法中的“返回false”将停止执行回调,但在这种情况下,“登录”路由的回调也不会被触发。这不是目的。
发布于 2014-04-09 08:10:04
我找到了我所需要的插件:
https://github.com/fantactuka/backbone-route-filter
这个插件允许在路由命中之前创建/接收Ajax请求/响应。
在路由器中:
routes: {
'': 'landing_page',
'(/)login': 'login',
'(/)home': 'home',
},
/*--- Before filter checks authentication (BB async router plugin) ---*/
before: {
'(/)login': 'redirect_auth',
'(/)home': 'redirect_auth',
'(/)users/create_role': 'redirect_auth'
},
/*--- Checks if the user is logged in and redirects ---*/
redirect_auth: function(fragment, args, next) {
APP.controllers.auth_controller.redirect(fragment, args, next);
}
重定向逻辑是这样在auth_controller对象中实现的:
/*--- Check if the user is logged ---*/
/*--- PHP REST Show (GET) ---*/
Auth_controller.prototype.isLogged = function(){
//Check if the user is authenticated
var getAuthStatus = this.auth_model.fetch();
return getAuthStatus;
};
/*--- Redirect the user based on auth status (before -> route) ---*/
Auth_controller.prototype.redirect = function(fragment, args, next){
var getAuthStatus = this.isLogged();
var self = this;
$.when(getAuthStatus).then(function(response){
var auth_status = Object.keys(response.success)[0];
if(auth_status === 'guest'){
if(fragment === 'login'){
next();
}else{
APP.router.navigate("login", {trigger: true});
}
} else {
var sidebars_controller = new Sidebars_controller();
APP.user = response.success["auth"];
if(fragment === 'login'){
APP.router.navigate("home", {trigger: true});
}else{
next();
}
}
})
};
https://stackoverflow.com/questions/22946823
复制相似问题