TL; DR?如果你想去(差不多)工作代码我做了一个jsFiddle here。
假设我有一个如下所述的Ember路由器。我想让它管理当前用户身份验证的状态。是否可以取消状态转换?
App.Router = Ember.Router.extend({
init: function() {
this.set('authenticated', false);
return this._super();
},
/*
* "Authentication" method - just toggle the state
*/
toggleAuthentication: function() {
var auth = this.get('authenticated');
this.set('authenticated', !auth);
if (auth) {
this.transitionTo('root.home');
} else {
this.transitionTo('loggedIn.home');
}
},
/*
* Root state
* Logged out state tree
*/
root: Ember.State.extend({
home: Ember.State.extend()
}),
/*
* Authenticated state tree
*/
loggedIn: Ember.State.extend({
/* Enter checks user is authenticated */
enter: function(manager, transition, async, resume) {
if (manager.get('authenticated')) {
// proceed
} else {
// cancel the transition & redirect to root.home
}
},
/* Exit sets authenticated to false just to be sure */
exit: function(manager, transition, async, resume) {
manager.set('authenticated', false);
},
/* Sub-states */
home: Ember.State.extend(),
news: Ember.State.extend({
list: Ember.State.extend()
})
})
});
答案 0 :(得分:2)
答案 1 :(得分:0)
Dean提到的票已经关闭;但有一种方法可以做到这一点。您可以覆盖Router.enterState,如下所示:
App.Router = Ember.Router.extend({
enterState: function(transition) {
if (!transition.finalState.get('isLeafRoute') || !App.User.get('authenticated')) {
// Only transition when your user is authenticated
this._super.apply(this, arguments);
} else {
// Otherwise "cancel this transition and move to the login state
App.get('router').transitionTo('users.login');
}
},
root: Ember.Route.extend({}) // Your routes
});
这在ember 1.0 pre中对我有用。就个人而言,我认为这种方法是合理的,因为有很多方法可以转换到路径(URL,动作等)以及许多突然变得未经身份验证的方法。我不确定这实际上是Ember团队想要的东西;)。