了解Ember Route挂钩以重定向

问题描述 投票:2回答:2

我有这个路由器设置

this.route('dashboard', function () {
    this.route('numbers');
    this.route('workspaces', function () {
        this.route('workspace', {path: '/:wid'});
});

dashboard.workspaces是导航栏中的链接。当您单击它时,加载dashboard.workspaces.workspace并立即重定向到第一个subnav。我是这样做的:

export default Ember.Route.extend({

     model: function() {
         return this.modelFor('dashboard');
     },

     afterModel: function(model) {
         this.transitionTo('dashboard.workspaces.workspace', model.get('workspaces.firstObject.id'));
     }
}

这一切都很好,除非我已经在dashboard.workspaces.workspace路由并单击dashboard.workspaces然后“afterModel”挂钩未被调用,我最终在dashboard.workspaces上,这是不需要的空页。是否还会有其他钩子?我已经尝试过“激活”而其他几个没有运气。

能够保存最后一个subnav转换并在单击主导航时重定向到in也很好。

ember.js ember-data
2个回答
4
投票

因此将路由器视为堆栈非常重要。当您访问路线时,您可以在堆栈上打开/关闭路线。正在向上或向下推送的项目将触发与当前过渡相关的事件。

在您的特定情况下,当前实现有两个问题。您已经提到的一个问题是,当您弹出子路线时,父路线不会触发任何事件。第二个问题是在这种情况下发生的。

  1. 导航到工作区/workspaces(它重定向到第一个工作区/workspaces/1
  2. 导航到第二个工作区/workspaces/2
  3. /workspaces/2上刷新页面(当它在工作空间的afterModel钩子中时,它重定向到第一个工作区/workspaces/1

因此,处理此问题的最简单方法是在workspaces路径下创建子路径,其唯一目的是重定向到第一个工作区。

this.route('dashboard', function () {
    this.route('numbers');
    this.route('workspaces', function () {
        this.route('first');
        this.route('workspace', {path: '/:wid'});
});

afterModel路线中删除workspaces逻辑并将其放入workspaces.first路线。

export default Ember.Route.extend({
  redirect: function() {
     var first = this.modelFor('workspaces').get('firstObject');
     this.transitionTo('dashboard.workspaces.workspace', first);
  }
}

现在在你的模板中,而不是指向workspaces,你会指向workspaces.first

{{link-to 'Workspaces' 'dashboard.workspaces.first'}}

现在,当您在仪表板中并单击它时,它将推动workspaces路径进入堆栈执行其挂钩。然后它会将first路由推入堆栈并执行其挂钩。 first路线的钩子将使它从堆叠中弹出first路线并将workspace路线推入堆叠。当你试图再次点击workspaces路线时,它会将workspace从堆栈中弹出,然后将first推回堆栈,然后再次执行其挂钩。

示例:http://emberjs.jsbin.com/cipawapali/edit?html,js,output


0
投票

可能有点晚了,但对于那些寻找这个空白页的解决方案的人来说,就像我一样。

Ember提供隐式/隐藏路径,可以使用它而不是创建一个新路径,这对此非常有用。在这个问题的情况下,它将是DashboardWorkspacesIndexRoute,无需在路由器中声明它,只需添加路由文件与您想要的重定向

export default Ember.Route.extend({
    redirect() {
       let first = this.modelFor('workspaces').get('firstObject');
       this.replaceWith('dashboard.workspaces.workspace', first);
    }
}

然后你可以使用{{link-to 'Workspaces' 'dashboard.workspaces'}},它将保留active类,同时仍然每次重定向。

有关更多信息,请访问here's the source

© www.soinside.com 2019 - 2024. All rights reserved.