【问题标题】:Error Substates错误子状态
【发布时间】:2013-12-13 21:42:38
【问题描述】:

当嵌套路由中发生错误时,抛出的错误会冒泡到父路由,直到其中一个捕获它。
可以处理错误的根级别是Application's。但是,ApplicationRoutesetupController 钩子是在使用 undefined 上下文从 ErrorRoute 转换后触发的。

代码示例可以在这里查看:http://jsbin.com/ucanam/2563/edit(在控制台中给出输出)

ApplicationRoute 中,我指望它的初始模型在从ErrorRoute 转换后出现。为什么它被重置为undefined,否则我该如何解决?

编辑:

以下是一些相关代码:

App = Ember.Application.create({});

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

App.ApplicationRoute = Ember.Route.extend({
  model: function() {
    /* model hook is not being called when the error bubbles up (nor afterModel hook) */
    /* This is the model expected in Application level */
    return [
      {"key1": "val1"},
      {"key2": "val2"},
      {"key3": "val3"}
    ];
  },

  setupController: function(controller, model) {
    /* This hook is called in the usual scenario, when ApplicationRoute first 
       invoked, with same model as defined in the model hook */
    /* However, it is also invoked after an error thrown from Articles Route,
       what happens then is:
       typeof model == "undefined" */
    console.log("SetupController invoked in Application Route:", model);    
  }
});

App.ArticlesRoute = Ember.Route.extend({
  model: function() {
    /* The following throws the error */
    Ember.$.ajax("http://");
  }
});

【问题讨论】:

  • 链接不错,但在正文中也要提供相关代码。

标签: javascript ember.js error-handling ember-router


【解决方案1】:

路线从来没有“有”模型,它只是有一个模型挂钩,用于获取路线的模型。当转换到错误时,不会尝试解决任何模型(如果出现错误,您将处于无限循环中)。

如果您的模型是静态内容,您可以在 setupController 中进行设置。

【讨论】:

  • setupController中设置模型对我来说不是一个好的解决方案,因为当模型解析并将其内容注入页面时模板中会出现闪烁(与@中的解析相反987654323@ 钩子,当模板仅在承诺返回后呈现时)。另一个问题是这里没有调用afterModel 钩子(可以在附加的jsbin 示例中看到),这使得它也不同于常见的转换。
  • 是的,因为同样的原因没有调用 afterModel。当您的应用程序路径中有真实模型时,我可以看到问题出在哪里,但是如果根中存在可能导致错误的逻辑,您怎么能进入错误状态?
  • machty 进行了更改,也许文档会有所帮助 gist.github.com/machty/5723945
  • 嵌套路由报错,冒泡后由Application全局处理。
  • 关于 machty 的帖子,我认为它有点过时了,因为上述场景发生在 Ember 的最新版本 (1.2) 中。虽然,他确实提供了另一种解决问题的方法(使用 events 哈希),如果我找不到使用 ErrorRoute 解决它的方法,我可能会使用它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 2015-10-24
  • 2012-11-14
  • 1970-01-01
  • 2016-09-18
相关资源
最近更新 更多