2013-03-05 58 views
8

我正在为游戏创建一个简单的倒数计时器。我正在使用CoffeeScript和Meteor。我有一个带有{{time}}表达式的Handlebars“Timer”模板。流星JS中的简单定时器

下面是代码:

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 

上面的代码只是给我的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 

回答

12

如果你想更新你需要使用Session使其反应,否则模板系统将不知道何时在UI更新车把上的价值。你也传递了一个处理函数来处理这个句柄,而不是定时器的值。我使用了Session来传递这些数据到handlebars中。

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" 

而且在万一别人的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"); 
    }); 
} 

从本质上说,你告诉Session的时间价值,其更新时,它告诉模板系统更新的时间值重绘。

+0

谢谢Akshat。工作很好。 – ppedrazzi 2013-03-05 18:29:40