How to reference a Template ReactiveVar from Tracker.autorun callback?

I want to use my ReactiveVar bar declared in Template.foo.created as a reactive data source in a Tracker that’s called even after bar assigned a value. In the context of the Tracker’s callback Template.instance().bar is null and thus I cannot get/set/track its value. I don’t want to use a Session variable for this purpose so how can I reference my Template instance variable from the Tracker? Also bonus: I have this same issue within Meteor.subscribe onReady callback. Will the solution for the first problem apply to this as well?

Template.foo.created = function() {
  this.bar = new ReactiveVar([]);
}

Template.foo.rendered = function() {
  Tracker.autorun(function() { 
    console.log(Template.instance().bar.get()); // Template.instance().bar is null
  });
}
Template.foo.onRendered(function () {
  this.autorun(() => { 
    console.log(this.bar.get()); // Template.instance().bar is null
  });
}
1 Like

Or create a constant for the template. Granted this approach is more verbose, but increases readability, IMHO.

Also, I think you should use Template.onRendered( callback ) rather than Template.rendered = callback

Template.foo.onCreated( function() {
  const template = this;
  template.bar = new ReactiveVar([]);
});

Template.foo.onRendered( function() {
  const template = this;
  template.autorun(function() { 
    console.log(template.bar.get());
  });
});

Also note how I tied the autorun to the template. This way the autorun is destroyed when the template is destroyed.

2 Likes