Meteor JS中的简单计时器

ppe*_*zzi 8 meteor

我正在为游戏创建一个简单的倒数计时器.我正在使用CoffeeScript和Meteor.我有一个带有{{time}}表达式的Handlebars"Timer"模板.

这是代码:

clock = 10

timeLeft = () ->
    if clock > 0
        clock--
    else
        "That's All Folks"
        Meteor.clearInterval(interval)

interval = Meteor.setInterval(timeLeft, 1000)

if Meteor.isClient
    Template.timer.time = interval
Run Code Online (Sandbox Code Playgroud)

上面的代码只给我一个静态显示8或6而不是倒数计时器.

如果我添加一些console.log语句,我可以看到它在终端中的设计工作.

clock = 10

timeLeft = () ->
    if clock > 0
        clock--
        console.log clock
    else
        console.log "That's All Folks"
        Meteor.clearInterval(interval)

interval = Meteor.setInterval(timeLeft, 1000)

if Meteor.isClient
    Template.timer.time = interval
Run Code Online (Sandbox Code Playgroud)

Aks*_*hat 12

如果你想更新手柄中的值,你需要使用它Session以使其具有反应性,否则模板系统将不知道何时在ui中更新它.您还为模板传递了句柄而不是计时器值.

使用下面的内容,我习惯Session将这些数据传递给车把.

clock = 10
timeLeft = ->
  if clock > 0
    clock--
    Session.set "time", clock
    console.log clock
  else
    console.log "That's All Folks"
    Meteor.clearInterval interval

interval = Meteor.setInterval(timeLeft, 1000)
if Meteor.isClient
  Template.timer.time = ->
    Session.get "time"
Run Code Online (Sandbox Code Playgroud)

还有javascript,以防其他人想要这个:

var clock = 10;

var timeLeft = function() {
  if (clock > 0) {
    clock--;
    Session.set("time", clock);
    return console.log(clock);
  } else {
    console.log("That's All Folks");
    return Meteor.clearInterval(interval);
  }
};

var interval = Meteor.setInterval(timeLeft, 1000);

if (Meteor.isClient) {
  Template.registerHelper("time", function() {
    return Session.get("time");
  });
}
Run Code Online (Sandbox Code Playgroud)

本质上,您告诉Session时间值,并且当它更新时,它告诉模板系统使用更新的时间值重绘.