How can i accomplish reactive dates

2020-03-31 04:15发布

I am creating list of messages that shows how long ago the message was sent.

Screenshot

This is my messages collection

Messages = new Mongo.Collection('messages');
Messages.attachSchema(new SimpleSchema({
    created: {
        type: Date
    },
    text: {
        type: String
    }

}));

this my my layout

{{#each messages}}

            <li class="message">
                    <span class="message-text">{{text}}</span>
                    <span class="message-date">{{timeAgo created}}</span>
            </li>

{{/each}}

This is my helper

UI.registerHelper('timeAgo', function (context, options) {
    if (context) {
        return moment(context).fromNow();

    }
});

How can i make it so that my helper updates each minute? Right now it is not reactive unless I enter a new message or refresh the page.

UPDATE

Meteor-livestap does exactly this .

标签: meteor
1条回答
我欲成王,谁敢阻挡
2楼-- · 2020-03-31 04:45

Change your helper to this:

Template.registerHelper('timeAgo', function (context, options) {
    Session.get("time");
    if (context) {
        return moment(context).fromNow();
    }
});

Meteor.setInterval(function() {
    Session.set("time", new Date().getTime());
}, 60000);

What this does is change Session.get("time") every minute, and forces your helper to recalculate. This should ensure the time stays reactive every minute.

查看更多
登录 后发表回答