Meteor.js:如何避免使用点符号进行无用的刷新/计算/重新渲染

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

本文关键字:无用 刷新 计算 新渲染 符号 js 何避免 Meteor      更新时间:2024-06-08

我需要一种方法来避免无用的计算;在反应函数中,我有一个反应对象,我只需要一个属性,但如果这个对象的另一个属性发生变化,所有函数都会重新计算:

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

(在html 中

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

)

现在让我们改变你的年龄:

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

你猜你在控制台上看到了什么(第二次…)

running               x2

但它应该只运行一次,因为名称没有更改

为什么它很重要?在我的应用程序中,我有复杂的计算,用户在线/空闲状态很容易改变

只要所用反应函数的值发生变化,就会重新运行计算。在您的情况下,反应函数是Meteor.user(),所以每当该方法的结果发生变化时,都会触发重新运行。

为了将重新运行限制在真正需要的地方,您需要使用(或创建)一个反应函数,该函数将返回您想要跟踪的值,仅此而已。例如:

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