Search code examples
meteormeteor-publications

Where does Meteor.subscribe() belong?


I just noticed that my subscription code "Meteor.subscribe('my-publications')" at the top of my JS file affects ALL my templates, not just the template that the JS file is created for.

This was unexpected because all the demos did it this way.

Where is the subscription code suppose to be in if I want it to affect one template only? Inside Template.name.created()?


Solution

  • Don't assume the only data in minimongo is what is relevant to your template. Be specific when selecting your data for the template.

    You have several options as far as subscriptions go, the most common by far is adding a subscription to the waitOn section of your routes definitions. Using waitOn will result in the subscription being unsubscribed when the route is no longer in use.

    Router.map(function() { 
      this.route('route', {
        waitOn: function(){ return Meteor.subscribe("yourSub"; }
      });
    });
    

    You can also subscribe per template. A package I've created for this purpose can be added via

    meteor add elevatedevdesign:template-subscriptions
    

    This pattern will also be coming soon as a part of blaze, but with some slight differences in how you call it. This will automatically unsubscribe when the template is no longer active. It also allow's subs-manager to be subscribed to on template destruction.