Using reactive variables in anonymous functions

How can I use reactive template variables in an anonymous function within the template rendered function? (I want to keep it reactive).

Template.templateName.rendered = function() {
    function testFunction(){
        //Print the field 'title' associated with the current template
        console.log(this.data.title);
    }
});

If you want to make something reactive use Tracker.autorun. If your variable is reactive it will run again when it changes.

The answer turned out to be using Tracker.autorun, as suggested by @lucfranken (thank you!)

Template.templateName.rendered = function() {
   this.autorun(function(){
		title = Template.currentData().title;
   });

    function testFunction(){
        console.log(title);
    }
});

Since a helper is already reactive by itself this should also work:

Template.templateName.rendered = function() {
  var title = Template.currentData().title;
  function testFunction(){
    console.log(title);
  }
});

The reason your first one did not trigger reactivity is likely because it does not evaluate the function at all.

Edit: Do you run an old version? It’s called onRendered currently:

First it seems you are using an ancient version of meteor. The syntax should be Template.name.onRendered(callback). Second you don’t have to use Template.currentData() inside an onRendered/onCreated/onDestroyed callback, this.data is sufficient. And at last, in the your example this refers to the function scope not to the template scope, you’ll either have to var self = this in parent scope or use ES5 fat arrow functions.

@lucfranken - If I remove the autorun function, it is no longer reactive. It seems to be required.

Which version of meteor do you use?

Helpers run in a reactive context, but onRendered does not, hence the need for an autorun.

2 Likes