【问题标题】:How to map path to route?如何将路径映射到路由?
【发布时间】:2013-11-16 08:31:19
【问题描述】:

这是我的路由器的一部分:

this.resource('phoneNumbers', function () {

    this.resource('locators', function () {
        this.route('index');
        this.route('new');
        this.route('show',   { path: '/:locator_id/show' });
        this.route('edit',   { path: '/:locator_id/edit' });
    });

    this.resource('phonelocations', function () {
        this.route('index');
    });

});

有时我需要做以下事情:

  1. 用户点击编辑按钮
  2. 我抓住了当前路径:phoneNumbers.locators.index
  3. 显示一个编辑表单,带有一个cancel 按钮
  4. 如果单击取消按钮,我想过渡到旧路线,使用捕获的currentPaththis.transitionToRoute(oldCurrentPath);

但是transitionToRoute 期待的是locators.index 而不是完整路径phoneNumbers.locators.index

Assertion failed: The route phoneNumbers.locators.index was not found 
Uncaught Error: There is no route named phoneNumbers.locators.index.index

(不知道为什么ember会尝试phoneNumbers.locators.index.index

这是为什么呢?我怎样才能“映射”到路线的路径?我必须为此维护自己的PATH_TO_ROUTE_MAP 吗?这就是我已经开始做的事情,它有效,但Ember 肯定有更好的方法吗?

另一种方法是捕获当前路线而不是currentPath。这可能吗?怎么样?

【问题讨论】:

  • 我相信 Ember 知道定位器是 phoneNumbers 的嵌套资源,因此它不需要完整的路径...请参阅此图表了解如何生成嵌套资源路由名称:emberjs.com/guides/routing/defining-your-routes/…跨度>
  • @MatthewBlancarte:请看我的编辑
  • 所以在你的情况下,正确的转换应该是:transitionToRoute('locators'),因为你是如何命名嵌套资源的。如果您将其更改为this.resource('phoneNumbers.locators', function () {...,它将适用于您的phoneNumbers.locators 路线......希望这是有道理的。 :)
  • 我认为您也可以省略路线中的index 部分。
  • 您的意思是,由于我构建路由器的方式,路径和路由在我的应用程序中并不相同。所以我没有配置路由器 right 是我的错误(但是 ember 允许这样做!)我不知道可以像你说的那样命名资源。我会考虑,但我担心更改我的路由器配置会对控制器/模型/路由的命名产生巨大影响,谁知道还有什么其他副作用。

标签: ember.js url-routing


【解决方案1】:

不是缓存 currentPath,而是缓存来自 afterModel 挂钩的 targetName,

App.PostsRoute = Ember.Route.extend({
  afterModel: function(posts, transition) {
    //cache transition.targetName
  } 
});

【讨论】:

    【解决方案2】:

    钩子中可用的transition 对象有一些关于它在transition.router.currentHandlerInfos 下经过的路径的簿记。

    您可以从那里获取以前的状态并将它们缓存在某个地方(也许applicationController 可能是一个更好的地方),然后进行转换。

    Demo Fiddle

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 1970-01-01
      • 2011-02-10
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多