meteormeteor-tracker

Meteor tracker skips unexpectedly


I am following a tutorial about Tracker and seeing an unexpected behavior.

Here, I am using a getter and a setter to see that Tracker.autorun() is called whenever I call the setter.

if (Meteor.isClient) {
  var favoriteFood = 'Apples';
  var favoriteFoodDep = new Tracker.Dependency;

  var getFavoriteFood = function () {
    favoriteFoodDep.depend();
    return favoriteFood;
  };

  var setFavoriteFood = function (newValue) {
    favoriteFood = newValue;
    favoriteFoodDep.changed();
  };

  var handle = Tracker.autorun (function () {
    console.log("your favorite food is " + getFavoriteFood());
  });

  setFavoriteFood("Mangos");
  setFavoriteFood("Bananas");
  setFavoriteFood("Cheese");
}

When I open my browser console, I expect to see

Your favorite food is Apples
Your favorite food is Mangos
Your favorite food is Bananas
Your favorite food is Cheese

But All I see is the first and the last one, no matter how many calls I make for setFavoriteFood().

Your favorite food is Apples
Your favorite food is Cheese

Why is this happening?


Solution

  • I would guess that there is a race condition here. Because it executes the lines

    setFavoriteFood("Mangos");
    setFavoriteFood("Bananas");
    setFavoriteFood("Cheese");
    

    .. so quickly, by the time the getter re-runs the invalidated computation, the set value is "Cheese".

    To test this, consider running the following:

    setFavoriteFood("Mangos");
    window.setTimeout(function() { 
      setFavoriteFood("Bananas");
    }, 1000);
    window.setTimeout(function() { 
      setFavoriteFood("Cheese");
    }, 2000);
    

    I suspect that it will log all 4 to the console. Report back and let me know!