2013-03-05 66 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