Is it better to use an observer or a helper?


#1

I am wondering: theoritically, if a helper runs whenever data changes, isn’t it more efficient to create observers? Eg:

Template['User.profile'].onCreated(function () {
  this.user = new ReactiveVar(false);
  this.observers = [];

  const userObserver = Meteor.users.find({
    _id: Router.current().params._id
  }).observe({
    added: (doc) => {
      const profileObs = Profiles.find(doc.profile).observe({
        added: (profile) => {
          this.user.set(_.extend(this.user.get(), {
            profile: profile
          }));
        },
        changed: (profile) => {
          this.user.set(_.extend(this.user.get(), {
            profile: profile
          }));
        }
      });
      this.observers.push(profileObs);
    }
  });
  this.observers.push(userObserver);
});

Template['User.profile'].onDestroyed(function () {
  this.observers.forEach((obs) => obs.stop());
});

Wouldn’t this be faster and look more elegant?


#2

What is this code trying to accomplish?

It is super hard to tell from that code, which implies for me that it might not be a good pattern.


#3

Essentially, take a data structure like this (from Meteor.users).

{
  _id: '1234',
  emails: [{
    address: 'fake@fake.org',
    verified: true
  }],
  profile: '5678'
}

So then it will create a few observers on every foreign key, and update the reactive var when any of them change


#4

I don’t think this is actually worthwhile. Even if it were more efficient, I doubt your app’s performance would be bottlenecked by this situation.