Template Subscription Behavior with Parameters
I have a question about subscribing to a template. I found that not a bug, but inadequate behavior, consider the following:
Router (iron-router):
this.route('test', {
path '/test/:_id'
});
Then subscribing to the template:
Template.test.onCreated(function () {
this.subscribe('mydata', Router.current().params._id);
});
Basically a route where the subscription is associated with an identifier given by the route parameter.
Then if I have two links:
<a href="/test/hello">hello</a>
<a href="/test/hi">hello</a>
As / test / hello and / test / hi use the same pattern, onCreated from test is called only once (same for onRendered). This means that the subscription will exist for id: hello, but not for id: hi (since onCreated is called once for hello).
I avoid this issue by moving the subscription along the route using the subs-manager package. However, I am very interested in knowing how to handle such problems in a template (I just prefer the idea the template knows better than the route it needs to follow).
In short, if some people didn't get it: Two pages, same route (with parameter), same template, onCreated / onRendered, called only once, but changing the route parameter, so it must have two subscriptions. But since onCreated / onRendered is only called once (since they use the same template), there is only one subscription. How do I handle this case with a template subscription method?
source to share
You can use reactive computation within your lifecycle onCreated
.
Template.test.onCreated(function () {
this.autorun(function(){
var currentRouteParamId = Router.current().params._id;
this.subscribe('mydata', currentRouteParamId);
}.bind(this));
});
Router.current()
being the source of reactive information, the internal reactive computation setting this.autorun
will not be repeated whenever the current route is changed using navigation.
Subscriptions made inside a Tracker.autorun
are automatically stopped and re-subscribed (if the parameter is changed).
source to share