【问题标题】:Template subscription behavior with parameters带参数的模板订阅行为
【发布时间】:2015-07-16 14:38:56
【问题描述】:

我有一个关于模板订阅的问题。我发现,不是错误,而是一种不酷的行为,请考虑以下几点:

路由器(铁路由器):

this.route('test', {
  path '/test/:_id'
});

然后模板订阅:

Template.test.onCreated(function () {
  this.subscribe('mydata', Router.current().params._id);
});

基本上是一个路由,其中​​订阅链接到由路由参数给出的 id。

那么,如果我有两个这样的链接:

<a href="/test/hello">hello</a>
<a href="/test/hi">hello</a>

由于 /test/hello 和 /test/hi 共享相同的模板,因此来自 test 的 onCreated 仅被调用一次(与 onRendered 相同)。这意味着订阅将存在于 id: hello,但不存在于 id: hi(因为 onCreated 会为 hello 调用一次)。

我使用 subs-manager 包在路由中移动订阅时避免了这个问题。然而,我很想知道如何在模板中处理此类问题(我只是更喜欢模板比路由更了解他需要执行哪些订阅的想法)。

简而言之,如果有些人没有得到它: 两个页面,相同的路由(带参数),相同的模板,onCreated/onRendered 只调用了一次,但是,路由参数改变了,所以它应该有两个订阅。但是由于 onCreated/onRendered 只被调用一次(因为它们共享相同的模板),所以只有一个订阅真正存在。这种情况如何处理,使用模板订阅方式?

【问题讨论】:

    标签: templates meteor publish-subscribe


    【解决方案1】:

    您可以在 onCreated 生命周期事件中使用响应式计算。

    Template.test.onCreated(function () {
      this.autorun(function(){
        var currentRouteParamId = Router.current().params._id;
        this.subscribe('mydata', currentRouteParamId);
      }.bind(this));
    });
    

    Router.current() 是一个响应式数据源,this.autorun 的内部响应式计算设置将在当前路由通过导航修改时重新运行。

    Tracker.autorun 内进行的订阅调用会自动停止并重新订阅(如果修改了参数)。

    【讨论】:

      猜你喜欢
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 2017-11-26
      • 2020-02-27
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      相关资源
      最近更新 更多