Ember:直接转到URL时,WillTransition不会触发

时间:2015-05-14 21:42:13

标签: javascript ember.js ember-cli

我需要对允许用户访问的路由执行授权。根据ember的文档,我应该使用' WillTransition'

http://guides.emberjs.com/v1.11.0/routing/preventing-and-retrying-transitions/

  

尝试转换时,无论是通过{{link-to}},transitionTo,还是更改网址,都会对当前活动的路由触发willTransition操作。这给出了每条活动路线,从最多叶的路线开始,有机会决定是否应该进行过渡。

所以我把这段代码放在我的应用程序路由中,尝试首先记录它所调用的所有时间。

   actions: {
        willTransition: function(){
            console.log('Transitioning');
        }
    }

当我在我的应用内部然后点击转换到另一条路线时,此功能正常。但是,如果我直接进入受保护的路线,它就不会发射。防爆。 / myapp / protected / route

但是使用调试标志

NV.APP.LOG_TRANSITIONS = true;

设置我在控制台中获取这些日志。即使是'Wil​​lTransition'事件没有被解雇。

Preparing to transition from 'myapp.index' to 'myapp.protected.index'
Transitioned into 'myapp.protected.index'

所以我去看看ember源中的日志事件,我看到了

/**
  Handles notifying any listeners of an impending URL
  change.
   Triggers the router level `willTransition` hook.
   @method willTransition
  @private
  @since 1.11.0
*/
willTransition: function (oldInfos, newInfos, transition) {
  run['default'].once(this, this.trigger, "willTransition", transition);

  if (property_get.get(this, "namespace").LOG_TRANSITIONS) {
    Ember['default'].Logger.log("Preparing to transition from '" + EmberRouter._routePath(oldInfos) + "' to '" + EmberRouter._routePath(newInfos) + "'");
  }
},

在写入控制台日志的行的正上方是一条看起来应该触发事件的行,但它没有到达我的代码。我究竟做错了什么?

1 个答案:

答案 0 :(得分:2)

授权检查在beforeModel函数中直接在路由上可能更好。

您可以创建mixin并在每条路线上实施

App.Auth =  Ember.Mixin.create({
   beforeModel: function(){
       if(!this.get('userAuthorized')){
           //prevent entering and go to login route
           this.transitionTo('login');
           //show msg to user that it needs access
       }
   }
});

你可以在像这样的路线上实施mixin

App.UserStuffRoute = Ember.Route.extend(App.Auth,{ });