2012-06-15 71 views
1

TL; DR?如果你想要(幾乎)工作代碼,我做了一個jsFiddle here是否可以取消Ember狀態轉換?

假設我有一個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

這是覆蓋在另一計算器問題 http://stackoverflow.com/questions/11190928/emberjs-conditional-redirect-in-router –

回答

0

院長提到的票已經關閉;但是有一種方法可以做到這一點。您可以覆蓋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 
}); 

這對我在燼1.0預處理。就我個人而言,我認爲這種方法是合理的,因爲有很多方法可以轉換爲路線(URL,動作等等)以及突然獲得未經驗證的許多方法。我不確定這實際上是Ember團隊打算的東西;)。

相關問題