Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Momentjs in meteor- reactivity?

Have been using https://github.com/acreeger/meteor-moment in meteor and it works well, however is there a way to make the output of moment reactive so that it counts up "3 seconds ago", "4 seconds ago", etc?

like image 693
user1048175 Avatar asked Aug 14 '14 06:08

user1048175


1 Answers

Rather than using a new Session variable for each individual timer, I would create a single Tracker.Dependency which is flagged for changes every second (or perhaps every 10 seconds), then depend on this whenever you want to depend on the current time.

var timeTick = new Tracker.Dependency();
Meteor.setInterval(function () {
  timeTick.changed();
}, 1000);

fromNowReactive = function (mmt) {
  timeTick.depend();
  return mmt.fromNow();
}

Template.example.helpers({
  example: function () {
    return fromNowReactive(moment().startOf('hour'));
  }
});

This is the approach taken by mizzao:timesync, which is a useful package you can use if those fromNows are based on server-side timestamps. One reason to not use client-generate timestamps is that these may be out of sync, resulting in strings like 5 seconds from now for a post that was just made. mizzao:timesync allows server-generated timestamps to be used everywhere, and also groups different reactivity intervals together efficiently.

like image 143
user3374348 Avatar answered Sep 18 '22 00:09

user3374348