Iron Router在onData中抛出异常

时间:2014-07-18 23:29:00

标签: meteor iron-router

我在铁路由器的路由控制器的onData()函数中看到了一个奇怪的异常。仅在我对文件进行更改后才会出现异常,这当然会导致meteor重新启动应用程序。我在github中提供了一个示例来说明问题:https://github.com/benmonro/iron-router-bug

如果您通过点击提交添加某人,然后点击该人的姓名,一切都会正常加载。但是,如果您随后对某些js进行了更改(例如添加注释)。 Meteor将重新加载,你将在' onData()'中获得例外。尝试使用从' data()'返回的数据属性的方法。功能

例外情况如下:

> Exception in defer callback: TypeError: Cannot read property 'name' of
> undefined
>     at RouteController.extend.onData (http://localhost:3000/irDataBug.js?8327f0bf1bedee2437ec14bc4509d8f7e85079ab:33:19)
>     at RouteController.runHooks (http://localhost:3000/packages/iron-router.js?e9fac8016598ea034d4f30de5f0d356a9a24b6c5:827:16)
>     at http://localhost:3000/packages/iron-router.js?e9fac8016598ea034d4f30de5f0d356a9a24b6c5:2137:16
>     at Utils.extend._run.withNoStopsAllowed (http://localhost:3000/packages/iron-router.js?e9fac8016598ea034d4f30de5f0d356a9a24b6c5:2098:21)
>     at _assign._compute (http://localhost:3000/packages/deps.js?4a82362ae66e863a1c1a8b0a5fec6f665e2038d1:228:38)
>     at new Deps.Computation (http://localhost:3000/packages/deps.js?4a82362ae66e863a1c1a8b0a5fec6f665e2038d1:160:10)
>     at Object._assign.autorun (http://localhost:3000/packages/deps.js?4a82362ae66e863a1c1a8b0a5fec6f665e2038d1:380:13)
>     at http://localhost:3000/packages/iron-router.js?e9fac8016598ea034d4f30de5f0d356a9a24b6c5:2134:12
>     at Utils.extend._run.withNoStopsAllowed (http://localhost:3000/packages/iron-router.js?e9fac8016598ea034d4f30de5f0d356a9a24b6c5:2098:21)
>     at _assign._compute (http://localhost:3000/packages/deps.js?4a82362ae66e863a1c1a8b0a5fec6f665e2038d1:228:38)

1 个答案:

答案 0 :(得分:1)

重新加载后数据尚未就绪,因此您需要添加guard或提前返回回调。这是一个简单的解决方法:

onData: function() {
  var thePerson = Router.current().data();
  if (!thePerson)
    return;

  if (thePerson.name === "Fred") {
    console.log("it's fred");
  } else {
    console.log("it's not fred");
  }
}

因为回调是被动的,所以在找到thePerson后它将重新运行。替代解决方案可能涉及waitOn回调,然后检查this.ready()