Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting which reactive query was triggered

Tags:

meteor

I have an probably not so unique issue of having a complicated meteor app.

I have several actions which are causing parts of the page to refresh which really aren't needed. But I'm having trouble locating which find() (or multiple find()'s ) is the one being triggered. I know the Collection in question, just not which find().

I could use observeChanges on every find I use, but that would be a lot of extra code.

Is there an easy way to see what is being triggered and by what?

Thanks!

like image 448
Ricochet Avatar asked Mar 15 '13 00:03

Ricochet


1 Answers

Here is a render logging function you might find useful. It logs the number of times each template is rendered to the console. You know if a template is re-rendered after initial page load, it's because a reactive data source that it relies on has changed. Either this reactive data source could have been accessed in a helper method, or the template is a list item (i.e. inside an {{#each ...}} block helper) and a list item was added/moved/removed/changed. Also keep in mind that child templates call their parent's rendered callback when the child is rendered or re-rendered. So, this might confuse you into thinking the parent has actually been taken off the DOM and put back, but that's not true.

So, you can call this function at the end of your client code to see the render counts:

  function logRenders () {
    _.each(Template, function (template, name) {
      var oldRender = template.rendered;
      var counter = 0;

      template.rendered = function () {
        console.log(name, "render count: ", ++counter);
        oldRender && oldRender.apply(this, arguments);
      };
    });
  }

EDIT: Here is a way to wrap the find cursor to log all changes to a cursor to the console. I just wrote a similar function to this for a new package I'm working on called reactive-vision. Hopefully released soon.

var wrappedFind = Meteor.Collection.prototype.find;

Meteor.Collection.prototype.find = function () {
  var cursor = wrappedFind.apply(this, arguments);
  var collectionName = this._name;

  cursor.observeChanges({
    added: function (id, fields) {
      console.log(collectionName, 'added', id, fields);
    },

    changed: function (id, fields) {
      console.log(collectionName, 'changed', id, fields);
    },

    movedBefore: function (id, before) {
      console.log(collectionName, 'movedBefore', id, before);
    },

    removed: function (id) {
      console.log(collectionName, 'removed', id);
    }
  });

  return cursor;
};
like image 194
cmather Avatar answered Oct 29 '22 05:10

cmather