1

TL;博士?如果你想去(几乎)工作代码,我在这里做了一个 jsFiddle 。

假设我有一个如下所述的 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()
        })
    })
});
4

2 回答 2

2

那将是“还没有”。https://github.com/emberjs/ember.js/issues/745

于 2012-06-15T13:48:09.733 回答
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 团队的意图;)。

于 2012-10-18T13:42:12.953 回答