1

我正在关注有关 Tracker 的教程并看到意外行为。

在这里,我使用 getter 和 setter 来查看Tracker.autorun()每当我调用 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");
}

当我打开浏览器控制台时,我希望看到

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

但我看到的只是第一个和最后一个,不管我打了多少电话setFavoriteFood()

Your favorite food is Apples
Your favorite food is Cheese

为什么会这样?

4

1 回答 1

1

我猜这里有一个竞争条件。因为它执行行

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

.. 如此之快,当 getter 重新运行无效计算时,设置值为“Cheese”。

要对此进行测试,请考虑运行以下命令:

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

我怀疑它会将所有 4 个记录到控制台。回来报告,让我知道!

于 2015-07-16T09:08:59.797 回答