Simple Clock in Meteor.js or how to reload Templates?

冷暖自知 提交于 2019-12-12 03:46:03

问题


Hey guys I#m trying with Templates in meteor.js, but how can I reload them after a given time? , for example i want to have a Template called "time" wich has to reload every second to show the current time, also a template "date" wich has to reload every minute, because evry minute the date can change, or an calendar wich has to reload the .ics every 5 minute or so, to be always accurate.

my current code looks like that:

<body>
    <!-- TOP -->
    <div class="top left">{{> time }}</div>
    <div class="top mid"></div>
    <div class="top right">{{> date }}</div> 

</body>

<template name="time">
<div>{{ clock }}</div>
</template>

<template name="date">
<div>{{ date }}</div> 
</template>

the js:

if (Meteor.isClient) {


    Template.time.helpers({
        clock: function () {
            var currentTime = new Date();
            var currentHours = currentTime.getHours();
            var currentMinutes = currentTime.getMinutes();
            var currentSeconds = currentTime.getSeconds();
            currentHours = ( currentHours < 10 ? "0" : "" ) + currentHours;
            currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
            currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;
            return currentHours + ":" + currentMinutes + ":" + currentSeconds;
        }

    });

    Tempate.date.helpers({
        date: function () {
            var month = ["Januar", "Februar", "März", "April", "Mai", "Juni", "July", "August", "September", "October", "November", "Dezember"];
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();
            return d + " " + month[m] + " " + y;
        }
    });

}

please help me improve my knowledge!

-Tim4497


回答1:


The simplest way to reload a template is to provide and change a reactive data source. In your case, this could be the clock value.

var clock = new ReactiveVar(new Date());

Template.time.onCreated(function() {
  Meteor.setInterval(function() {
    clock.set(new Date());
  }, 1000);
});

Template.time.helpers({
  clock: function() {
    var currentTime = clock.get();
    ... 
  },
});


来源:https://stackoverflow.com/questions/36626845/simple-clock-in-meteor-js-or-how-to-reload-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!