简体   繁体   中英

Meteor Helpers - DOM Manipulation

// Works
var counter = 0;
    var myInterval = Meteor.setInterval(function(){
      counter++;
      var time = moment().hour(0).minute(0).second(counter).format('HH:mm:ss');
      console.log(time);
    }, 1000);

// Inside Helper - Does Not Work

Template.clockRunner.helpers({
  start: function () {
    var counter = 0;
    var time = moment().hour(0).minute(0).second(counter).format('HH:mm:ss');
    var myInterval = Meteor.setInterval(function(){
      counter++
    }, 1000);
    return time;
  },
})

The first version console logs the time in increments of 1 second. The Helper version displays "00:00:00" in the DOM, but does not increment, if I console log the time in helper it logs "00:00:00" every second.

I'm not sure if I'm misunderstanding the reactive nature of helpers or if I'm not seeing a minor mistake. Thanks in advance!

a helper is meant to provide data to a Blaze template; it won't get called unless invoked from a template.

that said, you should think of a helper as something that only provides data, it shouldn't "do anything." as a template renders, and as reactive data is processed, a helper may get called several times in unexpected ways.

i reckon you want your timer to be started in the onRendered() method; that is called once as a template is put on the screen. (there's a corresponding method that's called when the template is taken off the screen, so the timer can be stopped).

once your timer is started, you can write timer data to a reactive variable, and then a helper that returns a formatted version of that timer data. because it's in a reactive var, that will ensure your helper is re-invoked each time the timer ticks.

the last part is simply ensuring the Blaze template references the helper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM