【发布时间】:2012-04-27 22:34:22
【问题描述】:
我有一个客户端 JS 应用程序,它需要加载一个模板来显示每个项目。假设它们是笔记。
问题出在异步部分。我不能让模板只加载一次。每次笔记调用render 函数时都会加载。
这里有一些代码:
var notes = [ {}, {}, {} ] // Some Note objects
notes.forEach( function( note ) {
render( note )
}
// Have some variable to hold the template
var template
// Now on the render function
function render( note ) {
// First, if the template exists, go straight to the next function
if ( template ) {
// The display function takes care of appending the note
// to the body after applying datas on the template
display( note )
}
else {
// loadTemplate just loads the template in an ajax request
// and executes the callback with the template as argument
loadTemplate( function( data ) {
// I fill in the template variable
template = data
// And I display the note since the template is available
display( note )
} )
}
}
所以在这种情况下,它会加载三倍的模板,即使有一个检查来防止这种情况。我猜这是因为这三个模板直接进入了 else,但是我该如何防止呢?
我不想使用同步 ajax 加载,因为这会冻结浏览器。
编辑:最后,我使用了@Managu 的解决方案,稍作修改。
我没有使用他的循环,而是使用了以下更优雅的方法:
while ( backlog.length ) {
display( backlog.shift() )
}
【问题讨论】:
-
.lodaTemplate怎么知道要加载什么模板? -
因为这个应用程序中现在只有一个模板可以加载。
标签: javascript ajax templates