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

      

Now I am getting:

Exception from Tracker afterFlush: cannot call "stop" method from undefined TypeError: cannot call "stop" method from undefined

What I want to do is stop the computation once currentChapter

. What am I doing wrong?

+3


source to share


1 answer


Two things:

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



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 will stop at the end of the first run regardless - you have to stop it in a block if (currentChapter)

.

+4


source







All Articles