新手问题 了解 Ember.js routes

armstrong · 2015年07月17日 · 1424 次阅读

本文包括两个 ember 内置 route 处理程序:ApplicationRoute 和 IndexRoute

我创建了一个有/entries 简单程序。每当访问根目录 / 的时候,就会跳转到这个/entries 路径,为了达到这个目标,我们将在 Route 对象中使用 beforeModel 钩子。

着手:

route handler 是达到目标的最佳地点,因它为负责指定 url 处理。当有人访问 / 时把它转到 /entries,然后我就想到在 ApplicationRoute 的 beforeModel 钩子里加上 this.transitionTo(“entries”)

代码如下:

App = Ember.Application.create();

App.Router.map(function() {
  this.resource("entries");
});

App.ApplicationRoute = Ember.Route.extend({
  beforeModel: function() {
    this.transitionTo("entries");
  }
});

App.EntriesRoute = Ember.Route.extend({
  model: function() {
    return ["red", "blue"];
  }
});

在如看到的一样,当手动进入/目录时,它顺利地进入到/entries 目录下。然后,我添加了一个内包含的 url: /entries/new,代码如下:

App = Ember.Application.create();

App.Router.map(function() {
  this.resource("entries", function() {
    this.route("new");
  });
});

App.ApplicationRoute = Ember.Route.extend({
  beforeModel: function() {
    this.transitionTo("entries");
  }
});

App.EntriesIndexRoute = Ember.Route.extend({
  model: function() {
    return ["red", "blue"];
  }
});

当从 /entries 转到 /entries/new 是没有问题的

有意思的部分

每当在浏览器地址栏手动输入 /entries/new 时总跳回到 /entries,但点击页面的新建按钮却是好的。开始的时候有些蛋疼,但马上就想通了

原因是在 ApplicationRoute 的 beforeModel 钩子里添加的 this.transitionTo("entries"),它高效地强调说: “当任何人通过 url 进入时,都会转到 /entries,它并不会根据 url 而有什么不同”,考虑到 ApplicationRoute 作为所有路径的父路径,它并没有绑定到指定的 url

我们想要的只是当输入根目录 / 时才跳转,你能想像当 root 目录 /,使用的是啊个 route handler 吗?,如果你猜到是 IndexRoute 就对了

然后为了修正这个问题,我简单地把 this.transitionTo("entries") 放入 IndexRoute 里。以下是最终的版本

App = Ember.Application.create();

App.Router.map(function() {
  this.resource("entries", function() {
    this.route("new");
  });
});

App.IndexRoute = Ember.Route.extend({
  beforeModel: function() {
    this.transitionTo("entries");
  }
});

App.EntriesIndexRoute = Ember.Route.extend({
  model: function() {
    return ["red", "blue"];
  }
});

现在看起来非常清楚,解决问题的过程令人快乐。 希望有所帮助!

原文地址

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请 注册新账号