Momentjs in meteor- reactivity?

后端 未结 4 417
栀梦
栀梦 2021-01-12 16:12

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

相关标签:
4条回答
  • 2021-01-12 16:53

    Use setTimeout and Session to store your variable.

    Something like this (in your lib file):

    var updateTime = function () {
        var time = moment().startOf('hour').fromNow(); // 22 minutes ago
        Session.set('timeFromNow', time);
        setTimeout(updateTime, 60 * 1000); // 60 seconds
    });
    updateTime();
    

    Then, in your template:

    Template.t.timeFromNow = function () {
        return Session.get('timeFromNow');
    }
    

    When setTimeout triggered to update Session variable, the template is updated.

    0 讨论(0)
  • 2021-01-12 17:01

    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.

    0 讨论(0)
  • 2021-01-12 17:03

    Thanks for the replies everyone, I found a mrt package which does the job atmospherejs.com/package/livestamp

    0 讨论(0)
  • 2021-01-12 17:13

    You can now use the package copleykj:livestamp. (github | atmosphere)

    Install it like this:

    meteor add copleykj:livestamp
    

    It has a dependency on momentjs:moment so it will bring that along automatically. It installs a universal helper that is available anywhere and can be passed a date object.

    You can use it in a template like this:

    <li>Regular:   {{date}}          </li>
    <li>Livestamp: {{livestamp date}}</li>
    

    Here's a working demo in MeteorPad

    0 讨论(0)
提交回复
热议问题