在客户端加载页面时从服务器方法获取响应 - Meteor

时间:2016-07-26 04:25:26

标签: javascript meteor

我有一个20秒计时器,可在我的Meteor服务器上无限期运行。当用户的客户端连接时,有没有办法从服务器上的Timer方法获取响应?基本上我想要实现的是所有连接的用户能够看到在他们的客户端上运行的相同计时器。

所以它很简短......我希望客户端获取在服务器上不断运行的方法的输出,然后将响应输出到客户端。这可能吗?

这是我在服务器上运行的计时器代码。

Meteor.methods({

  runTimer: function() {

    var running = false;
    var seconds = 20000; // (1 sec = 1000)
    var then; // Timer start time

    // ------------------------------------
    // Evaluate and route
    // ------------------------------------

    function router() {
      if (!running) {
        run();
      }
    };

    // ------------------------------------
    // Run the timer
    // ------------------------------------

    function run() {
      running = true;
      then = Date.now() + seconds;
      var interval = setInterval(function(){
        var time = parseTime(then-Date.now());
        if (time[0] > 0) {
          console.log(time[0] + '.' + time[1]);
        } else {
          console.log('0.00');
          running = false;
          clearInterval(interval);
          router();
        }
      }, 51);
    };

    // ------------------------------------
    // Parse time in MS for output
    // ------------------------------------

    function parseTime(elapsed) {
      // Array of time multiples [sec, decimal]
      var d = [1000,10];
      var time = [];
      var i = 0;
        while (i < d.length) {
          var t = Math.floor(elapsed/d[i]);
          // Remove parsed time for next iteration
          elapsed -= t*d[i];
          t = (i > 0 && t < 10) ? '0' + t : t;
          time.push(t);
          i++;
        } 
      return time;
    };

    router();

  }
});

1 个答案:

答案 0 :(得分:2)

是的,这绝对是可能的,而Meteor-way将使用mongo / DDP / minimongo关系来实现它。

换句话说,将输出写入集合,将其发布到客户端,Meteor将确保客户始终可以使用最新输出。

所以在你的代码中,除非我弄错了,我想你想把这一行输出给客户?

console.log(time[0] + '.' + time[1]);

创建一个集合:

Timestamp = new Mongo.Collection('timestamp')

发布(或使用自动发布):

Meteor.publish("timestamp", function() {
  return Timestamp.find();
}

在服务器上插入/更新文档(您只需要一个):

Timestamp.upsert({_id: 1}, {$set: {timestamp: time[0] + '.' + time[1]}});

在客户端上,阅读它。

Timestamp.findOne({_id: 1});