简体   繁体   中英

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

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();
  },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM