Book Image

Building Single-page Web Apps with Meteor

By : Fabian Vogelsteller
Book Image

Building Single-page Web Apps with Meteor

By: Fabian Vogelsteller

Overview of this book

If you are a web developer with basic knowledge of JavaScript and want to take on Web 2.0, build real-time applications, or simply want to write a complete application using only JavaScript and HTML/CSS, this is the book for you. This book is based on Meteor 1.0.
Table of Contents (15 chapters)
14
Index

Using autorun in a template


Although it could be useful to use Tracker.autorun() globally in our app in some cases, it can become quickly hard to maintain those global reactive functions as our app grows.

Therefore, it is good practice to bind reactive functions to the templates for which they perform actions.

Luckily, Meteor offers a special version of Tracker.autorun() that is tied to a template instance and stops automatically when the template gets destroyed.

To make use of this, we can start the reactive function in the created() or rendered callback. To start, let's comment out our previous example from the main.js file so that we won't get two alert windows.

Open our home.js file and add the following lines of code:

Template.home.created = function(){

    this.autorun(function(){
        alert(Session.get('mySessionExample'));
    });
};

This will create the reactive function when the home template is created. When we go to the browser's console and set the mySessionExample session to...