带参数的模板订阅行为

Template subscription behavior with parameters

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

路由器(铁路由器):

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 共享相同的模板,onCreated from 测试仅被调用一次(onRendered 也是如此)。这意味着订阅将存在于 id:hello,但不存在于 id:hi(因为 onCreated 为 hello 调用一次)。

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

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

您可以在 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 内进行的订阅调用会自动停止并重新订阅(如果修改了参数)。