如何延迟流星中变量的显示?

How to delay showing of variable in meteor?

我正在编写一个应用程序,它根据收集的计数显示估计的等待时间。我遇到的问题是当页面加载或刷新时显示 waitTime,但它首先显示 0,然后在大约一秒后显示基于计数的实际 waitTime。我假设这与变量在从集合中获取计数时被延迟有关,因此它显示初始计数 0,然后获取实际计数并显示 waitTime?

有没有办法让它在加载或刷新时只显示确切的等待时间?

js:

Template.home.helpers({
waitTime: function() {
    var totalCount = Students.find().count();
    var hour = totalCount/4;

    if(totalCount < 4){
        return 15*totalCount + " minutes"
    }else if(totalCount >= 4 && totalCount%4 == 0){
        return hour + " hour(s)";
    }else if(totalCount >= 4 && totalCount%4 == 1){
        hour = hour - .25;
        return hour + " hour(s)" + " 15 minutes";
    }else if(totalCount >= 4 && totalCount%4 == 2){
        hour = hour - .5;
        return hour + " hour(s)" + " 30 minutes";
    }else if(totalCount >= 4 && totalCount%4 == 3){
        hour = hour - .75;
        return hour + " hour(s)" + " 45 minutes";
    }
  }
});

Html:

<template name= "home">
<body>
    <h2 id="insert">Approximate Wait Time: {{waitTime}}</h2>
    <div class="col-lg-6 col-lg-offset-3">
        <!-- Quick form from autoform package creates sign in form and populates collection with data-->
        {{>quickForm id="studentForm" collection="Students" type="insert" template="bootstrap3-horizontal" label-class="col-sm-3" input-col-class="col-sm-9"}}
    </div>
</body>
</template>
var totalCount = Students.find().count();

第一次加载页面的时候,meteor的reactivity还没有建立,所以count一直是0,导致显示0。需要检查是否已经订阅,并且然后显示页面

Template.home.created = function() {
  this.loading = new ReactiveVar(true) 
  let subHandler = Meteor.subscribe('your-publication-name')
  this.loading.set(!subHandler.ready())
}

然后在您的模板助手中,检查 loading 是否为真,return 加载文本或某物,否则 return 结果

像这样

waitTime: function() {
  if (Template.instance().loading.get()) return "Loading";

  // the rest of the code
}

最直接的方法是在数据准备好之前不呈现视图(或至少视图的相关部分)。两种主要方法是等待订阅准备就绪,或者等到您拥有所需的数据值。

后者会很困难,因为据我所知,0 是一个可能的值。所以我建议前者。

假设您的订阅已绑定到您的模板,您可以像这样等待订阅准备就绪:

<template name= "home">
<body>
    {{#if Template.subscriptionsReady}}
    <h2 id="insert">Approximate Wait Time: {{waitTime}}</h2>
    <div class="col-lg-6 col-lg-offset-3">
        <!-- Quick form from autoform package creates sign in form and populates collection with data-->
        {{>quickForm id="studentForm" collection="Students" type="insert" template="bootstrap3-horizontal" label-class="col-sm-3" input-col-class="col-sm-9"}}
    </div>
    {{else}}
      Loading...
    {{/if}}
</body>
</template>