Starting to dig into the 1.0.4 docs and I’m wondering about the use case for the new template subscriptions in a the onCreated
object:
Template.notifications.onCreated(function () {
this.subscribe("notifications");
});
As I understand it, I should use this with a {{#if Template.subscriptionsReady}}
tag to see if the subs have loaded. This would have the benefit of loading static content while waiting for subscribed content. This also makes waiting for subscriptions a 2-step process instead of the current Iron Router process of using waitOn
.
If this is the case, when should I use this pattern vs. the current waitOn
on my router?
Similarly, if two pages currently use the same subscription, this new template-level pattern means I would sub onCreated, stop onDestroyed, then sub again on the new page’s onCreated. This makes me wonder, would it be more efficient to just continue using a Meteor.subscribe
if a subscription is used across multiple templates? Any use-case examples would be great
8 Likes
@sacha wrote a great blog post a while ago on this topic:
https://www.discovermeteor.com/blog/template-level-subscriptions/
It explains use cases for template level subscriptions where there also are app/page level subscriptions and concludes exactly like this
One of the best (and worst!) things about Meteor is that there is often no “right” way to do things. So the best you can hope for is to familiarize yourself with an array of different techniques, and pick the right one at the right time.
I suggest you also take a look at these packages among which are ones you can further customize how your subscriptions behave in certain situations. @arunoda’s subs-manager for one answers your question about two different pages using the same subscription.
So basically, it boils down to something like this:
- subscribe within your route controller (waitOn) for page level data
- subscribe within your template for data specific to a fragment/widget on a page
- use a subscription cache/manager to keep the state of your subscriptions across page transitions
But as that blog post concluded, this is not a general recipe
4 Likes
Okay. I’ve written a blog post about when to use Template level subscriptions and router level subscriptions. As the router, I’m using newly released our Flow Router.
In that’s I’ve urged to stay away from pattern like waitOn on the router. Instead we can delegate that task to templates. Here’s the only rule we need to follow when dealing with subscriptions.
Templates(or the UI layer) should be able to check the state of a subscription and do actions based on it.
Read my whole blog post about Flow Router and Subscription Management.
7 Likes