javascript - 如何延迟 meteor 中变量的显示?

标签 javascript html meteor meteor-collections

我正在编写一个应用程序,它根据集合计数显示估计的等待时间。我遇到的问题是,当页面加载或刷新时,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>

最佳答案

最直接的方法是在数据准备好之前不渲染 View (或至少 View 的相关部分)。两种主要方法是等待订阅准备就绪,或者等到获得所需的数据值。

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

假设您的订阅与您的模板绑定(bind),您可以像这样等待订阅准备就绪:

<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>

关于javascript - 如何延迟 meteor 中变量的显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43509240/

相关文章:

javascript - 我希望我的操作能够更改它所附加的 DOM 元素

javascript - 添加相同的属性:value pair to multiple objects in array

jquery - 在 jquery 中显示的子菜单

javascript - 如何等待用户对 Meteor AutoForm 提交的响应?

javascript - 将变量传递给 mongo 修饰符

javascript - 2 个表单,只有一个提交按钮 $_POST 方法

用于人类友好的相对日期格式的 Javascript 库

android - Java 到安卓?

jquery - 沙箱/将 HTML 代码限制在 DIV 标记中

javascript - meteor 路线 dispatch 从未发出警告