本文介绍了流星`Deps.autorun` vs`Collection.observe`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Deps.autorunCollection.observe来使第三方窗口小部件与动态Meteor.Collection保持同步之间的优缺点是什么.

What are the pros/cons between using Deps.autorun or Collection.observe to keep a third-party widget in sync with a reactive Meteor.Collection.

例如,我正在使用jsTree直观地显示存储在MongoDB中的目录树.我正在使用此代码使其具有响应性:

For example, I am using jsTree to visually show a directory tree that I have stored in my MongoDB. I'm using this code to make it reactive:

// automatically reload the fileTree if the data changes
FileTree.find().observeChanges({
  added: function() {
    $.jstree.reference('#fileTree').refresh();
  },
  changed: function() {
    $.jstree.reference('#fileTree').refresh();
  },
  removed: function() {
    $.jstree.reference('#fileTree').refresh();
  }
});

使用此方法与Deps.autorun调用(看起来像这样)的利弊是什么:(未测试)

What are the pros/cons of using this method vs a Deps.autorun call that would look something like this: (untested)

Deps.autorun(function() {
  jsonData = FileTree.find().fetch();
  $.jstree.reference('#fileTree')({'core': {'data': jsonData} });
});

这只是一个例子.我问的是一般情况下的利弊,而不是针对此特定用例.

This is just an example. I'm asking about the pros/cons in general, not for this specific use case.

推荐答案

Deps.autorun,现在Tracker.autorun是一个反应式计算块.而watchChanges提供了对某些更改的回调.

Deps.autorun, now Tracker.autorun is a reactive computation block. Whereas the observeChanges provides a callback to when something changes.

当您使用Deps.autorun时,function() {...}中的整个块将在每次以任何方式(更新,删除或插入)或任何其他方式改变反应变量或文档时重新运行反应变量的变化.

When you use Deps.autorun, the entire block in function() {...}, will re-run every time a reactive variable, or document changes, in any way at all (that is updated, removed or inserted), or any other reactive variable change.

obtainChanges回调进行了更精细的调整,并根据查询触发要添加,更改或删除的回调.

The observeChanges callbacks are more fine tuned, and fire the callbacks for added, changed or removed depending on the query.

根据上面的代码,实际上两者是相同的.如果在Deps.autorun块中有更多的反应式变量,则observeChanges这样做会更有效.

Based on your code above, in effect both are the same. If you had more reactive variables in the Deps.autorun block then the observeChanges way of doing it would be more efficient.

通常,第一种样式效率更高,但是当您的代码位于上方时,它们几乎相同,并且取决于您的偏好.

In general the first style is more efficient, but as your code stands above they're both nearly the same and it depends on your preference.

这篇关于流星`Deps.autorun` vs`Collection.observe`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 01:11