How to periodically update a variable using meteor

大兔子大兔子 提交于 2019-11-27 18:32:51

问题


I have a session variable that I want to update with a fixed periodicity. Say, I want this variable to be increased by 1 every 60 seconds.

It seems to me that the best place for doing this is inside the helpers section of the relevant template. I first tried to do this using setInterval as described here, but that didn't work (the function just didn't seem to repeat).

I then tried what I thought would be a straightforward solution, but this also doesn't work. See below. The helper variable 'currentPosition' is supposed to return the current minute of the day (plus an offset). However, it only does this when the template is first called and when the session variable 'offset' is changed in a function that's defined in the 'events' section, which responds to a click on a particular div (a 'next' button).

    currentPosition: function () {
        var d = new Date();
        var h = d.getHours();
        var m = d.getMinutes();
        var w = h * 60 + m;

        Session.set("position", w + Session.get("offset"));

        return Session.get("position");
    },

I would think that the above helper would actively update the value for 'currentPosition' every minute. Yet it does not.

So, my question is, how can I have a session variable change every, say, 60 seconds, increasing it by, say, 1, while the new value of the session variable is reflected within the app, when the variable is adjusted.

(If there's a straightforward and completely different solution which works in meteor, I'm not aware of it, so do point it out to me if I'm missing something obvious.)


回答1:


Although you are using a reactive variable, it only gets set once - when the helper is first called. Therefore it doesn't run again. You need a function outside of the helper to set variable for you. Remember one important rule - helpers should never have side effects.

Here's a complete working example of how to create a timer:

html

<body>
  {{> timer}}
</body>

<template name="timer">
  <p>Total Seconds: {{seconds}}</p>
</template>

js

Template.timer.helpers({
  seconds: function() {
    return Template.instance().seconds.get();
  }
});

Template.timer.created = function() {
  var self = this;
  this.seconds = new ReactiveVar(0);

  this.handle = Meteor.setInterval((function() {
    self.seconds.set(self.seconds.get() + 1);
  }), 1000);
};

Template.timer.destroyed = function() {
  Meteor.clearInterval(this.handle);
};


来源:https://stackoverflow.com/questions/27412743/how-to-periodically-update-a-variable-using-meteor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!