Helper level subscriptions

Subscriptions have moved from being top level to router level and from router level to template/component level.

I’ve been thinking about taking it a step further and doing helper level subscriptions. Specifically, I’d like to subscribe in my collection helpers that connect me to related data. But if this is a solid idea, it could also be used for template helpers.

But is there something wrong with this approach? I just keep thinking that if it was a good idea, I’d have seen other people using it but I’m not. So is there some bad reason that I’m not thinking of?

const Authors = new Mongo.Collection('authors');
const Posts = new Mongo.Collection('posts');

Posts.helpers({
  author() {
    Meteor.subscribe('author', this.authorId);
    return Authors.findOne(this.authorId);
  },
});
1 Like

the subscription probably won’t have finished by the time it hits the findOne - depending on your context, using subscriptionsReady / placing the findOne inside Meteor.subscribe’s onReady callback would solve that though.

any reason you are looking to use this approach?

Do you know “template subscription” approach? I think it is better than do it inside a helper.

If you split your view into smalls templates template subscription is a good call.

Let me know if you need help.

Thanks for the link to the onReady callback. Did not know about that.

My thinking behind this was that the reason to do template/component level in the first place is to subscribe to the data where it’s actually being used. It makes it super clear to the developer where the data is needed.

So I thought that it would make even more sense to do this at a helper level for association helpers. You could then easily call the helper in whatever template you want without subscribing in each and every template.

I’ve used and am using template/component subscriptions. Putting it in a helper seems like an even cleaner way to do it.