简体   繁体   中英

How do I dynamically detect which initial state a Ember.StateManager should have?

I have an Ember.StateManager for managing the logged-in user's session. How can I detect whether or not the user is logged in when they visit the page, in order to set the initialState property? (As they might have logged in earlier and still have the cookie)

App.userSessionStateManager = Em.StateManager.create({
    initialState: 'signedout', // this should be dynamic

    signedin: Em.State.createWithMixins({
        enter: function(sm) {
            this._super(sm);
            console.log('entered signedin state');
        },
        exit: function(sm) {
            this._super(sm);
            console.log('exited signedin state');
        }
    }),

    signedout: Em.State.createWithMixins({
        enter: function(sm) {
            this._super(sm);
            console.log('entered signedout state');
        },
        exit: function(sm) {
            this._super(sm);
            console.log('exited signedout state');
        }
    }),
});

As with many classes in Ember.js you can create your own init() function to do your own set up. This way you can decide what to set the initialState property to. However, be sure to call the init() function of the parent class with this._super() so that it can do the default initialization too.

Edit: Since a recent update in the Ember.js API, you need to use createWithMixins() instead of just create() in order to call _super functions.

App.userSessionStateManager = Em.StateManager.createWithMixins({
    init: function() {
        this._super();

        // your login detection routine here
        if (user.signedin)
            this.initialState = 'signedin';
        else
            this.initialState = 'signedout';
    },

    // ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM