Reputation: 63
I've a question regarding template subscription. I found, not a bug, but a un-cool behavior, consider the following:
Router (iron-router):
this.route('test', {
path '/test/:_id'
});
Then template subscription:
Template.test.onCreated(function () {
this.subscribe('mydata', Router.current().params._id);
});
Basically a route, where the subscribe is linked to id given by route parameter.
Then, if I have two links like this:
<a href="/test/hello">hello</a>
<a href="/test/hi">hello</a>
As /test/hello and /test/hi share the same template, the onCreated from test is called only once (same for onRendered). Which means the subscribe will exist for id: hello, but not for id: hi (as the onCreated is called once for hello).
I avoid this problem moving subscription in route using subs-manager package. Yet, I'm quite interested to know how to handle such problems in the template (I just prefer the idea the template knows better than the route what subscriptions he needs to perform).
In short if some people didn't get it: Two page, same route (with parameter), same template, onCreated/onRendered called only once, yet, route parameter change, so it should have two subscriptions. But as onCreated/onRendered is called only once (as they share same template), only one subscription trully exist. How to handle this case, with the template subscription method ?
Upvotes: 3
Views: 399
Reputation: 22696
You could use a reactive computation inside your onCreated
lifecycle event.
Template.test.onCreated(function () {
this.autorun(function(){
var currentRouteParamId = Router.current().params._id;
this.subscribe('mydata', currentRouteParamId);
}.bind(this));
});
Router.current()
being a reactive data source, the inner reactive computation setup by this.autorun
will rerun whenever the current route is modified via navigation.
Subscriptions calls made inside a Tracker.autorun
are automatically stopped and re-subscribed to (if the parameter is modified).
Upvotes: 1