2014-09-12 50 views
0

我有一個模板幫手取決於當前時間:如何失效時間模板依賴

Template.bunny.alive = function() { 
    if (this.time_to_die < new Date().getTime()) 
    return true; 
    else 
    return false; 
}; 

如何讓流星重新繪製在當前時間的推移time_to_die模板?

<template name="bunny"> 
{{if alive }} 
    Your bunny is alive. 
{{/if}} 
</template> 

編輯>

可能的解決方法是使用一個會話變量並存儲在比如說10秒的時間間隔,其被更新的時間。 所以

Session.setDefault("current_time", new Date().getTime()); 

Meteor.setInterval(function() { 
    Session.set("current_time", new Date().getTime()); 
}, 10000); 

然後,我可以只使用Session.get( 「CURRENT_TIME」)在我的助手,使他們很好地反應...

感覺還挺kludgey關係嗎?

回答

2

使用一個無功變量來指示生命狀態,並使用一個計時器在其死時更改(僅)。

Template.world.created = function(){ 
    self = this 
    self.isAlive = new ReactiveVar(true) 
    setTimeout(function(){ 
     self.isAlive.set(false) 
    }, self.time_to_die-Date.now()) 
} 

Template.bunny.alive = function() { 
    return Template.instance().isAlive.get() 
} 
+0

很高興有一個超時很聰明。如果你有很多類似的模板,這兩個解決方案都有很多額外的代碼。如果兔子在將來死得太遠,會爆發(溢出setTimeout)。我可能會去基於會話的解決方案,因爲在我的實際情況下,準確度可能是〜1分鐘,並不重要。儘管你認爲你的解決方案可能是最好的。 – jms301 2014-09-12 20:46:37

+0

順便說一下'self = this'的目的是什麼? – jms301 2014-09-12 20:49:48

+0

「溢出setTimeout」?不知道你的意思,但無論你在想什麼,我都不認爲這是你需要擔心的。在傳遞給'setTimeout'的函數內部,self用於訪問模板實例。 'created'函數內的'this'指向模板實例,但函數內部的'this'傳遞給'setTimeout',因此不是通過'self'來引用它。 – 2014-09-13 06:57:56

1

我想你,如果你希望你的模板被動更新,則Session變量雖然可以使用ReactiveVar避免使用定時器,但是當你要訪問從子模板實例範圍的變量,它變得有點棘手模板。

client/views/world/world.js

Template.world.created=function(){ 
    // we will store the current time using a template instance scoped ReactiveVar 
    this.now=new ReactiveVar(Date.now()); 
    // use a timer to update the current time every second 
    this.timer=Meteor.setInterval(_.bind(function(){ 
    this.now.set(Date.now()); 
    },this),1000); 
}; 

Template.world.destroyed=function(){ 
    // clean up on destroy 
    Meteor.clearInterval(this.timer); 
}; 

Template.world.helpers({ 
    inFiveSecondsFromNow:function(){ 
    return Date.now()+5000; 
    } 
}); 

client/views/wordl/world.html

<template name="world"> 
    {{> bunny timeToDie=inFiveSecondsFromNow}} 
</template> 

client/views/bunny/bunny.js

Template.bunny.helpers({ 
    alive:function(){ 
    // the "tricky" part (and it doesn't get better with nesting) 
    var world=Template.instance().view.parentView.parentView._templateInstance; 
    return this.timeToDie>=world.now.get(); 
    } 
}); 

client/views/bunny/bunny.html

<template name="bunny"> 
    {{#if alive}} 
    Your bunny is alive. 
    {{else}} 
    Your bunny is dead ! 
    {{/if}} 
</template> 

呈現時,世界模板示例將顯示「您的兔子是活着的。」持續5秒,然後「你的兔子死了!」。

如果你的應用很簡單,我認爲Session變量+全局定時器可能是好的,這個例子的好處是我們將反應變量和定時器都定義爲一個模板實例,所以如果一個大型複雜單頁面應用程序,Session沒有污染,只有當我們渲染世界模板時,計時器纔會執行。

+0

編輯:移動世界模板中的反應變量,並評論使用OP「全球」的解決方案。 – saimeunt 2014-09-12 18:02:54