我有一个由多个页面和一个主页组成的网络应用程序。在 Meteor 中开发此 Web 应用程序时,我将页面分为模板。 Web 应用程序应在一段时间内显示不同的页面,这意味着页面 A 应显示 60 秒,然后继续显示页面 B 大约 75 秒,依此类推。
在 meteor 中,我构建了一个由页眉和页脚以及可更改的模板持有者组成的主页。所以基本上主页看起来像这样:
<template name='main'>
{{>header}}
{{>templateHolder}}
{{>footer}}
</template>
并且页面被转换为模板,即templateA
等。这些模板应根据Session对象的更新替换templateHolder
,这也基于一些计时(以秒为单位),将使用 setTimeout
JS 函数执行。
一切正常,但我注意到每个页面的时间安排都困惑了。当我单独测试模板
时,它们工作正常。我怀疑 setTimeout 的异步调用在某种程度上相互冲突。
这是定期更改模板的 JS 代码。
Template.main.templateHolder = function(){
var appIndex = Session.get('currentAppIndex');
switch(appIndex){
case 'A':
return Template['templateA'];
} //....and so on... with other templates
}
Template.main.created = function() {
//Query each pages display time and load it into sessions
// etc...........
Session.set('currentAppIndex',0); //Initialize the first page
setTimeout(nextPage,0);
}
function nextPage() {
//Bunch of line of codes that retrieve time param from settings and calculate
//Also some simple alogrithm to get next templates.. etc
//Update the session index object so that it reactively updates the templateHolder
setTimeout(nextPage,currPageDisplayTime); //currPageDisplayTime is the pages time of display in milliseconds.
}
我不确定我的方法是否正确,但它成功地显示了模板并更改了它们。唯一的问题是时间安排不正确。动态更改模板的最佳方法是什么?将来是否容易出现任何错误?
最佳答案
我已经找到了这种错误行为的原因。我该如何解决这些问题?
- 我把JS
alert
每当模板中发生超时时。 - 此外,
alert
每当 session 对象更新时。
模板渲染的流程应该是这样的template A (60 secs) --> template B (75secs)--> template A
(这是一个循环)。我注意到在显示 template B
期间,alert
我放入 template A
着火了!这意味着即使一次只显示一个模板,创建的模板仍然在幕后健康地运行。无论它被指定做什么,它仍然会继续该过程。
这让我意识到,如果两个模板同时存在,我无法使用相同的 session 对象,因为它们都会更新相同的内容。结果我标准化了模板中 session 对象的使用;例如我使用 Session.set('itemIndex',index)
迭代每个模板中的集合,但由于模板意外地使用了同一个对象,因此它们同时更新数据。
所以JS setTimeout
按预期工作。问题在于共享 session 对象。
TL;DR 模板在未显示/更改时不会被破坏。这可以通过手动销毁它或使用不同的对象来避免。
P/S:仍在研究如何在创建模板后销毁模板。
关于javascript - meteor 动态渲染模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24340644/