Meteor - Stop Tracker Autorun when Template is Destroyed (user leaves page)

3.8k views Asked by At

In my Meteor template, I have a function called ohlcInit() that is autorun when new data is available in Mongo:

Template.Live.rendered = function(){

  function ohlcInit() {
    // computations run here
  }

  Tracker.autorun(function() {
      ohlcInit();
  });
};

This works great while the user is on the page/template in which this is all defined, but as soon as the user navigates to another URL on the site and the template is destroyed, errors get thrown in the console:

Exception from Tracker recompute function: undefined is not a function TypeError: undefined is not a function at ohlcInit (http://localhost:3000/client/views/live/live.js?dd5fb618daf9ea9e233c37caaaa9ed200fe3e987:271:33) at http://localhost:3000/client/views/live/live.js?dd5fb618daf9ea9e233c37caaaa9ed200fe3e987:306:5 at Tracker.Computation._compute (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:288:36) at Tracker.Computation._recompute (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:302:14) at Tracker.flush (http://localhost:3000/packages/tracker.js?192a05cc46b867dadbe8bf90dd961f6f8fd1574f:430:14)

How do you safely stop/end the autorun computation when a user navigates away to a new URL/template?
I am using iron:router.

1

There are 1 answers

5
David Weldon On BEST ANSWER

Use the new Template.autorun function, which automatically cleans itself up after the template is destroyed. To use it inside of a rendered callback, just replace Tracker.autorun with this.autorun.