23

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.

BonsaiOak
  • 27,741
  • 7
  • 30
  • 54

1 Answers1

27

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.

Tarang
  • 75,157
  • 39
  • 215
  • 276
  • 1
    In other words, `Tracker.autorun` works with anything that can register a dependency, but `observeChanges` are more specific hooks that only work with mongo cursors. – BonsaiOak Dec 24 '14 at 15:41
  • @BonsaiOak Yes, Tracker.autorun is the magical reps one that will re-run the entire method on every dependency change registered in it's method & observeChanges are very specific javascriptey event hooks to database changes to specific queries – Tarang Dec 24 '14 at 16:02