Search code examples
meteormeteor-blaze

this.subscribe and Template.instance().subscribe do not work


I am using Meteor 1.4.

Template.showProducts.onCreated(() => {
  var handle = Meteor.subscribe("products");
  //not working: var handle = this.subscribe("products");
  //not working: var handle = Template.instance().subscribe("products");

  Tracker.autorun(() => {
  //not working: this.autorun

    const isReady = Meteor.ready();
    //not working: this.subscriptionsReady()

    if(isReady){
      const products = Products.find().fetch();
      Session.set("prods", products);
    }
  });
});

If I use "this.subscribe", I got:

Uncaught TypeError: _this.subscribe is not a function

If I use "Template.instance()", I got:

Cannot read property 'subscriptionsReady' of null


Solution

  • If you use an arrow function, then the value of this which Meteor tries to pass in is lost. Instead use a regular anonymous function (function () { ... }).

    You should then use this.autorun rather than Tracker.autorun. This will ensure that the autorun is cleaned up when the template disappears, and will allow Template.instance to work inside the autorun.