Momentjs不会更新时间.fromNow()

时间:2014-12-28 14:48:31

标签: meteor

当我加载页面时,一切正常,但是:为什么momentjs不会更新时间?
如果我插入了一个新帖子,那么momentjs几分钟之前就不会用更新 文本

这就是我正在做的事。

我添加了momentjs:moment

注册帮助者

UI.registerHelper('timeAgo', function(datetime) {
    return moment(datetime).fromNow();
});

在模板中

<template name="postItem">
    <li>
      {{text}} - {{timeAgo createdAt}}
    </li>
  {{/if}}
</template>

输出

Hi! - a few seconds ago
Hello! - 23 minutes ago    

3 个答案:

答案 0 :(得分:6)

日期不是反应变量,因此在时差发生变化时不会刷新。

你可以通过强制它重新计算每分钟(或自定义间隔)来使其成为反应性的:

UI.registerHelper('timeAgo', function(datetime) {
    Session.get('time');
    return moment(datetime).fromNow();
});

setInterval(function() {
    Session.set("time", new Date())
}, 60000); //Every minute

这会强制帮助者每分钟重绘一次值。

答案 1 :(得分:2)

来自文档http://docs.meteor.com/#/full/reactivity

以下只是反应源

These Meteor functions run your code as a reactive computation:

Templates
Tracker.autorun
Blaze.render and Blaze.renderWithData


And the reactive data sources that can trigger changes are:

Session variables
Database queries on Collections
Meteor.status
The ready() method on a subscription handle
Meteor.user
Meteor.userId
Meteor.loggingIn



In addition, the following functions which return an object with a stop method, if called from a reactive computation, are stopped when the computation is rerun or stopped:

Tracker.autorun (nested)
Meteor.subscribe
observe() and observeChanges() on cursors

在您的示例中,您只是显示值(日期),

就像显示一些名称一样,你没有显示反应源,

如果显示反应源,则在值更改时将自动更改。

如果您想创建自己的反应源,请查看此处http://docs.meteor.com/#/full/reactivevar_pkg

修改

来到解决方案

试试这个包https://atmospherejs.com/copleykj/livestamp

我个人虽然没有亲自使用它。试一试。

答案 2 :(得分:0)

您需要了解重新启动的工作原理。没有反应值变化,因此没有重新计算。最简单的解决方案是让时间反应迅速。请参阅此答案:How can i accomplish reactive dates