【问题标题】:How do I make sure that Iron-Router's before function runs?如何确保 Iron-Router 的 before 函数运行?
【发布时间】:2013-11-14 05:27:55
【问题描述】:

我正在使用 Iron-Router 和 Meteor。当用户访问/foo/:routeID 时,重要的是在他们到达之前加载 foo。有时它不会及时加载,页面会呈现不稳定。我无法找出这些时间何时发生的可辨别模式。

如果我将其更改为在加载 foo 后重新呈现页面,那么就会有明显的更新。我宁愿只拥有它。加载 foo 对象时呈现页面。我该如何做到这一点?我目前的路线如下。

this.route('foo', {
    path:'/foo/:routeID',
    layoutTemplate:'base',
    before: function() {
        foo = Foos.findOne({routeID:this.params.routeID});
        console.log('before');
        console.log(foo);
        Session.set('foo', foo);
    }

【问题讨论】:

  • 您绝对应该阅读 Iron Router 文档的这一部分:github.com/EventedMind/…
  • 要和saimeunt 说同样的话。确保您订阅了 foo 并调用 .wait 。还要确保定义了加载模板。

标签: meteor rendering iron-router


【解决方案1】:

当您使用 IronRouter 时,Before 将始终运行,但不会始终阻塞,因此如果某些事情需要一段时间,您的其他代码仍然可能运行得太早。

为了确保您的收藏已加载,您需要对其调用 .wait() 以强制 Meteor/IronRouter 在加载收藏之前不尝试显示模板或运行其他相关代码。

这样的事情应该可以工作:

this.route('foo', {
path:'/foo/:routeID',
layoutTemplate:'base',
before: function() {
    this.subscribe('foos').wait();
    foo = Foos.findOne({routeID:this.params.routeID});
    console.log('before');
    console.log(foo);
    Session.set('foo', foo);
}

您需要确保为 foo 定义了 publish 函数(如果还没有,请关闭自动发布)。

编辑: 此外,为了安全并防止所有用户/路由下载每个 Foo 然后在客户端进行过滤,您可以使用带有参数的发布/订阅功能,以确保您没有下载整个每次点击页面时收集。

this.subscribe('foos', this.params.routeID).wait();

【讨论】:

  • 发布功能可以做到安全。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
相关资源
最近更新 更多