Jason Chen
Jason Chen

Reputation: 2577

Meteor reactive dates?

My code is like so:

Template.doodad.onRendered(function(){
var day1 = moment().format("ddd");
var day2 = moment().add(1,'d').format("ddd");
var day3 = moment().add(2,'d').format("ddd");
});

At the moment I am calling this via jQuery like so (under the same onRendered function):

$('#day1').text(day1);
$('#day2').text(day2);
$('#day3').text(day3);

And my HTML:

<template name="doodad">
<div id="day1"></div>
<div id="day2"></div>
<div id="day3"></div>
</template>

Naturally this isn't reactive, and I want to make sure that the information updates as the data changes. I have been looking for tools to accomplish this, and while chronos has something to the effect, the documentation doesn't say how to add following days (tomorrow, day after, etc).

I end up typing something like return Chronos.currentTime().add(1,'d'); which does not work.

What would be the ideal method for adding new days onto a template?

Upvotes: 0

Views: 63

Answers (1)

user3374348
user3374348

Reputation: 4101

In Meteor you usually shouldn't use jQuery to set the content of the page. This will be more complicated if you want to make it reactive. Rather use template helpers, which are automatically reactive.

<template name="doodad">
    <div>{{day1}}</div>
    <div>{{day2}}</div>
    <div>{{day3}}</div>
</template>
Template.doodad.helpers({
    day1() {
        return Chronos.liveMoment().format("ddd")
    },
    day2() {
        return Chronos.liveMoment().add(1, "d").format("ddd")
    },
    /* etc */
});

Note the use of Chronos.liveMoment which is like currentTime but returns a Moment rather than a Date.

Upvotes: 1

Related Questions