I think you have to use a timer if you want your template to update reactively, the Session
variable though, could be avoided using ReactiveVar
, but it gets a little tricky when you want to access template instance-scoped variables from child templates.
client/views/world/world.js
Template.world.created=function(){
// we will store the current time using a template instance scoped ReactiveVar
this.now=new ReactiveVar(Date.now());
// use a timer to update the current time every second
this.timer=Meteor.setInterval(_.bind(function(){
this.now.set(Date.now());
},this),1000);
};
Template.world.destroyed=function(){
// clean up on destroy
Meteor.clearInterval(this.timer);
};
Template.world.helpers({
inFiveSecondsFromNow:function(){
return Date.now()+5000;
}
});
client/views/wordl/world.html
<template name="world">
{{> bunny timeToDie=inFiveSecondsFromNow}}
</template>
client/views/bunny/bunny.js
Template.bunny.helpers({
alive:function(){
// the "tricky" part (and it doesn't get better with nesting)
var world=Template.instance().view.parentView.parentView._templateInstance;
return this.timeToDie>=world.now.get();
}
});
client/views/bunny/bunny.html
<template name="bunny">
{{#if alive}}
Your bunny is alive.
{{else}}
Your bunny is dead !
{{/if}}
</template>
When rendered, the world template example will display "Your bunny is alive." for 5 seconds then "Your bunny is dead !".
If your app is simple, I think the Session
variable + global timer is probably OK, the benefits from this example is that we scope both the reactive var and the timer to a template instance, so in case of a large complex single page-app, the Session
is not polluted and the timer only executes when we render the world template.