Meteor .depends() method



我正在阅读《发现流星》这本书,我被第137页的例子卡住了

var _currentLikeCount = 0;
var _currentLikeCountListeners = new Deps.Dependency();

currentLikeCount = function() {
_currentLikeCountListeners.depend();
return currentLikeCount;
}
Meteor.setInterval(function() {
 var postId;
  if (Meteor.user() && postId = Session.get('currentPostId')) {
   getFacebookLikeCount(Meteor.user(), Posts.find(postId),
    function(err, count) {
  if (!err && count !== _currentLikeCount) {
   _currentLikeCount = count;
   _currentLikeCountListeners.changed();
 }
});
}
}, 5 * 1000);

我很难理解"Deps.Dependency()"one_answers"depend()"在这段代码中做了什么。这段代码展示了什么类型的功能?这本书或多或少地掩盖了这一点,我很难找到一个解释,让send在文档中

Meteor中的东西是响应式的——这意味着当数据中的值发生变化时,所有依赖于该值的东西都会重新计算自己。

要使其成为可能,必须知道它依赖于哪个值。这可以通过设置Dependencies来跟踪。所以换句话说,如果你想让事情自动重新计算,依赖关系是你需要使用的底层机制。

你发布的代码中有三行很重要:

var _currentLikeCountListeners = new Deps.Dependency();

这将创建一个新的依赖对象,用于跟踪_currentLikeCount的更改。

_currentLikeCountListeners.depend();

此方法用于响应式函数,使该函数侦听依赖项。因此,每当依赖项发生变化时,函数将被重新计算。注意,并不是所有的函数都是响应式的——它需要被称为"响应式计算"。一开始不要担心,只要注意模板帮助器是可以的。

_currentLikeCountListeners.changed();

这是触发重新计算的实际行

最新更新