Meteor `Deps.autorun` vs `Collection.observe`

一曲冷凌霜 提交于 2019-12-20 10:06:06

问题


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.

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

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.


回答1:


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

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.

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

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.



来源:https://stackoverflow.com/questions/25999324/meteor-deps-autorun-vs-collection-observe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!