Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 294
BonsaiOak Avatar asked Sep 23 '14 15:09

BonsaiOak


1 Answers

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.

like image 87
Tarang Avatar answered Nov 17 '22 20:11

Tarang