Information about autorun function

Currently reading about FlowRouter. Faced with example with autorun function and can’t find good explanation. Also want to understand what object ‘this’ will be. Please help with useful links.

Template.blogPost.onCreated(function() { var self = this; self.autorun(function() { var postId = FlowRouter.getParam('postId'); self.subscribe('singlePost', postId); }); });

Tracker.autorun(…) allows converting a piece of code into reactive code when the source data it relays on changes.

According to the Meteor documentation, .onCreated is a Template method, so “this” is bound to a template instance object that is unique to this inclusion of the template and remains across re-renderings… not sure how in the code you pasted can do .autorun(…). I’d like to know too.

Thank you, it was really helpful. Few minutes ago have found nice link about autorun and realization of it

Also the following simple code can help you understand better what Tracker.autorun(…) does:

Meteor.startup(function() {
  Tracker.autorun(function() {
    console.log('There are ' + Posts.find().count() + ' posts');

In this case, Tracker.autorun() is making the console to automatically display the “There are X posts” message whenever the posts collection changes, where X is the number of posts in the collection. This is pretty cool since it saves you lots of lines of code.


If you invoke autorun on a template instance, the autorun will automatically be stopped when the template is destroyed.

Btw nowadays you can just do

Template.blogPost.onCreated(function () {
    this.autorun(() => {
        const postId = FlowRouter.getParam('postId');
        this.subscribe('singlePost', postId);  

But which object does “this” in that context represent? The template instance? or the tracker?

this.autorun -> this refers to the template instance
Then the ES2015 arrow function notation binds the parent scope, so you don’t have to do the var self = this dance.

But what I don’t understand is that if .autorun is a method of Tracker, how can you access it from the template instance (self).

Check out this line from the blaze package from meteor core:

1 Like

Got it now, thanks for your help.