我有一個客戶端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)
})
}
}
所以在這種情況下,它會加載模板的三倍,即使有檢查,以防止這一點。我想這是因爲三個模板直接進入其他模塊,但我怎麼能夠防止這種情況呢?
我不想使用sync ajax加載,因爲這會凍結瀏覽器。
編輯:最後,我用@ Managu的解決方案稍作修改。
而不是使用自己的循環,我用以下,更優雅:
while (backlog.length) {
display(backlog.shift())
}
'.lodaTemplate'如何知道要加載的模板? – Esailija 2012-04-27 22:50:40
因爲現在只有一個模板需要在這個應用中加載。 – 2012-04-27 22:51:31