Using reactive variables in anonymous functions


#1

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);
    }
});

#2

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


#3

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);
    }
});

#4

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:


#5

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.


#6

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


#7

Which version of meteor do you use?


#8

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