我想使用 Meteor.setInterval() 来更新时间模板,它不起作用 [英] I want to use Meteor.setInterval() to update a time-template, it doesnt work
问题描述
我想用 Meteor.setInterval 命令更新我的时间函数.
I want to update my time-function with the Meteor.setInterval-command.
这是我的 *.js 文件的样子:
This is how my *.js-file looks like:
function uhrzeit() {
var zeit = new Date();
var std = zeit.getHours();
var min = zeit.getMinutes();
return std + ":" + min;
};
if (Meteor.isClient) {
Template.uhr.zeit = function() {
Meteor.setInterval(uhrzeit, 1000); //Edit: Changed it to pass, not call the function.
return uhrzeit();
};
}
模板未更新.它会在我更新页面后显示实际时间,但不会定期更新.或者至少我没有改变 HTML 中的时间.
The template is not updated. It shows me the actual time once I update the page but doesn't update regularly. Or at least I doesnt change the time in HTML.
推荐答案
你的函数不是响应式的.您需要设置一个依赖项,确保您的数据函数依赖它并定期更新它.
Your function is not reactive. You need to set up a dependency, ensure your data function depend on it and update it periodically.
另外,数据函数也不是调用setInterval
的好地方.它可以被多次调用并创建许多间隔,这是不受欢迎的.created
更适合处理此类事情.
Also, data function is not a good place to call setInterval
. It can be called many times and create many intervals, which is undesired. created
is a better place for such things.
此外,请确保清除您创建的所有间隔.destroyed
是这样做的好地方.
Also, make sure to clear all intervals you create. destroyed
is a good place to do so.
代码:
if (Meteor.isClient) {
var zeitDep = new Deps.Dependency(); // !!!
var zeitValue;
var zeitInterval;
function uhrzeit() {
var zeit = new Date();
var std = zeit.getHours();
var min = zeit.getMinutes();
zeitValue = std + ":" + min;
zeitDep.changed(); // !!!
};
Template.uhr.created = function() {
uhrzeit(); /* Call it once so that we'll have an initial value */
zeitInterval = Meteor.setInterval(uhrzeit, 1000);
};
Template.uhr.zeit = function() {
zeitDep.depend(); // !!!
return zeitValue;
};
Template.uhr.destroyed = function() {
Meteor.clearInterval(zeitInterval);
};
}
这篇关于我想使用 Meteor.setInterval() 来更新时间模板,它不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!