Reputation: 10217
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
Upvotes: 0
Views: 466
Reputation: 8013
The problem is that you're passing the onCreated
handler an arrow function, which does not allow binding of this
(reference). As a result, Meteor is unable to correctly bind the template instance it has just created, and your subscriptions (and various other things) will fail.
The fix is just to pass onCreated
a traditional JS function:
Template.showProducts.onCreated(function () {
...
Upvotes: 2
Reputation: 4101
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.
Upvotes: 2