4.7 Routing -- Redirecting

一、Transitioning and Redirection

从一个route调用transitionTo或者从一个controller调用transitionToRoute将会停止任何进程中的任何跳转并且开启一个新的,作为重定向功能。

transitionTo携带的参数和行为和link-to辅助器完全一样:

  • 如果你跳转进一个没有动态字段的路由,该路由的model hook任然会运行。
  • 如果新的路由有动态字段,你需要为每一个字段传递一个model或者一个identifier (标识符)。传递一个model将会跳过字段的model hook。传递一个identifier将会运行model hook,并且你可以在参数中获取这个identifier (标识符)。

二、Before the model is known

如果你想要从一个路由重定向到另一个,你可以在路由的处理器的beforeModel hook做转换。

app/router.js

Router.map(function() {
  this.route('posts');
});

app/routes/index.js

export default Ember.Route.extend({
  beforeModel() {
    this.transitionTo('posts');
  }
});

三、After the model is known

如果你需要关于当前model的信息用来决定重定向,你应该使用afterModel或者redirect hook。它们接收解析过的model作为第一个参数并且transiton作为第二参数,因此function作为别名。(实际上,afterModel默认的实现就是调用redirect

app/router.js

Router.map(function() {
  this.route('posts');
  this.route('post', { path: '/post/:post_id' });
});

app/routes/post.js

export default Ember.Route.extend({
  afterModel(posts, transition) {
    if (posts.get('length') === 1) {
      this.transitionTo('post', posts.get('firstObject'));
    }
  }
});

当过跳转posts路由时如果它只有一条post数据,当前的跳转将终止,为了支持重定向到PostRoute,用一个单一的post object作为它的model

四、Based on other application state(基于其他应用程序的状态)

1. 你可以基于一些其他应用程序的状态有条件的跳转:

app/router.js

Router.map(function() {
  this.route('topCharts', function() {
    this.route('choose', { path: '/' });
    this.route('albums');
    this.route('songs');
    this.route('artists');
    this.route('playlists');
  });
});

app/routes/top-charts/choose.js

export default Ember.Route.extend({
  beforeModel() {
    var lastFilter = this.controllerFor('application').get('lastFilter');
    this.transitionTo('topCharts.' + (lastFilter || 'songs'));
  }
});

app/routes/filter.js

// Superclass to be used by all of the filter routes: albums, songs, artists, playlists
export default Ember.Route.extend({
  activate() {
    var controller = this.controllerFor('application');
    controller.set('lastFilter', this.templateName);
  }
});
  • 在例子中,导航到/,URL立即跳转到用户所在的最后一个过滤URL。第一次,它跳转到/songs URL。

2. 你的路由也可以选择只在某些情况下跳转。如果beforeModel hook不终止或者跳转到一个新的路由,剩下的hooks(model, afterModel, setupController,renderTemplate)将会向往常一样执行。

原文地址:https://www.cnblogs.com/sunshineground/p/5157962.html