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

Ember: WillTransition does not fire when going directly to URL

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

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

When a transition is attempted, whether via {{link-to}}, transitionTo, or a URL change, a willTransition action is fired on the currently active routes. This gives each active route, starting with the leaf-most route, the opportunity to decide whether or not the transition should occur.

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

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

当我在我的应用程序中然后单击以转换到另一条路线时,这工作正常。但如果我直接去受保护的路线,它不会开火。前任。 /myapp/protected/route

但是有调试标志

NV.APP.LOG_TRANSITIONS = true;

设置我在控制台中获取这些日志。即使 'WillTransition' 事件还没有触发。

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) + "'");
  }
},

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

在 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
       }
   }
});

你可以像这样在路由上实现混入

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