javascriptmeteormeteor-helper

Meteor.js: How to avoid useless refresh/computation/re-render with dot notation


I'm needing a way to avoid useless computations; In reactive functions, I have a reactive object, I just need one property, but if one other of this object change, all the function is recalculated:

Template.registerHelper('name', function() {
    console.log("running");
    return Meteor.user().profile.name;
});

(In html

<body><p>My name: {{name}}</p></body>

)

Now let change your age:

Meteor.users.update({_id:Meteor.userId()},{$set:{"profile.age":20}});

You guess what you see in your console(for the second time...)

running               x2

but it should run only once because the name haven't changed

Why it's important ? In my application I have complex calculs, and user online/idle status is changing easily


Solution

  • The computation is rerun whenever the value of used reactive function changes. In your case, the reactive function is Meteor.user(), so whenever result of that method changes, rerun is triggered.

    To limit reruns to where it's really necessary, you need to use (or create) a reactive function that will return exactly the value you want to track and nothing more. For example:

    var prop = new ReactiveVar();
    
    Template.template.onRendered(function() {
      this.autorun(function() {
        prop.set(Meteor.user().profile.name);
      });
    });
    
    Template.template.helpers({
      hlpr: function() {
        console.log("RERUN!!!");
        return prop.get();
      },
    });