Reputation: 1996
I want to implement a helper in my template that will display the time since a particular timestamp.
Template.postItem.helpers({
timeSinceString: function(timestamp) {
return moment(timestamp).fromNow();
}
});
This works fine when it loads, but it doesn't update unless the template is reloaded. This is understandable because the fromNow()
function isn't being tracked. How can I make sure that what the user sees is kept up-to-date?
Some examples:
Upvotes: 0
Views: 423
Reputation: 20226
The remcoder:chronos package provides a very useful way to do exactly this. It defines a reactive time variable that updates itself.
Note: the default update interval is one second. I found that in practice this could suck up serious cpu cycles when many time variables are being displayed. For things that are changing rapidly (like a file upload progress meter) I use one second. For slower moving things I use 20 minutes.
Upvotes: 0
Reputation: 36900
I take care of this using the mizzao:timesync
package (which I wrote) in combination with moment.js, which generates those specific strings.
mizzao:timesync
is very useful since it allows you to use server time on the client by computing an NTP-style offset, so times are accurate even if the client time is wrong. It also efficiently groups together reactive timers for updating all timestamps on the screen.
An example is part of the mizzao:user-status
demo: http://user-status.meteor.com/
Upvotes: 1
Reputation: 1996
I found this package which made it super super simple: https://atmospherejs.com/copleykj/livestamp
Upvotes: 1
Reputation: 11
Load a function on rendered that updates a session variable:
Template.postItem.rendered(function() {
setInterval(function() {
Session.set('currentTime', moment());
}, 1000); // Replace 1000 with your level of time detail
});
Template.postItem.helpers({
timeSinceString: function(timestamp) {
return Session.get('currentTime').from(moment(timestamp));
}
});
Upvotes: 0