meteor Template scoped subscriptions


Example

Meteor's default templating system Spacebars and its underlying rendering subsystem Blaze integrate seemlessly with publication lifecycle methods such that a simple piece of template code can subscribe to its own data, stop and clean up its own traces during the template tear down.

In order to tap into this, one needs to subscribe on the template instance, rather than the Meteor symbol like so:

First set up the template

<template name="myTemplate">
  We will use some data from a publication here
</template>

Then tap into the corresponding lifecycle callback

Template.myTemplate.onCreated(function() {
  const templateInstance = this;
  templateInstance.subscribe('somePublication')
})

Now when this template gets destroyed, the publication will also be stopped automatically.

Note: The data that is subscribed to will be available to all templates.