wyc
wyc

Reputation: 55343

How to properly stop Meteor Tracker.autorun?

I have the following:

Meteor.startup(function() {
  var computation = Tracker.autorun(function() {
    var currentChapter;
    currentChapter = Chapters.findOne({
      _id: currentChapterId
    });
    if (currentChapter) {
      if (currentChapter.title) {
        $("#input-title").val(currentChapter.title);
      } else {
        $("#input-title").val("");
      }
      if (currentChapter.content) {
        $("#input-content").html(currentChapter.content);
      } else {
        $("#input-content").html("");
      }
    }
    return computation.stop();
  });
});

Right now I get:

Exception from Tracker afterFlush function: Cannot call method 'stop' of undefined TypeError: Cannot call method 'stop' of undefined

What I want to do is to stop the computation once currentChapter is true. What am I doing wrong?

Upvotes: 3

Views: 3884

Answers (1)

richsilv
richsilv

Reputation: 8013

Two things:

1 - Your autorun function gets a handle to the computation passed to it, so you can stop it like so:

Meteor.startup(function() {
  var computation = Tracker.autorun(function(thisComp) {
    var currentChapter;
    currentChapter = Chapters.findOne({
      _id: currentChapterId
    });
    if (currentChapter) {
      if (currentChapter.title) {
        $("#input-title").val(currentChapter.title);
      } else {
        $("#input-title").val("");
      }
      if (currentChapter.content) {
        $("#input-content").html(currentChapter.content);
      } else {
        $("#input-content").html("");
      }
      thisComp.stop();
    }
  });
});

2 - In your code, the computation would be stopped at the end of the first run regardless - you should be stopping it within the if (currentChapter) block.

Upvotes: 5

Related Questions