2017-09-03 24 views
1

我目前正在開發一個涉及更新HTML的項目,具體取決於Firebase是否在數據庫中找到資源。下面是代碼片段:如何使用Firebase對HTML執行異步更新

for(var i = 0; i<collection.length; i++){ 
    //Get the player 
    var player = collection[i]; 

    //Create a new table row 
    var row = document.createElement("TR"); 
    row.id = player.Id; 

    //Add the player profile pic 
    var imgNode = document.createElement("TD"); 
    var img = document.createElement("IMG"); 
    var photo = "https://usatftw.files.wordpress.com/2014/10/nfl_logo_new2.jpg?w=1000&h=750"; 
    playerbase.orderByKey().equalTo(player.Id).on('child_added', function(snap){ 

     photo = snap.val(); 

    }); 

    img.setAttribute("src", photo); 
    img.setAttribute("width", "55px"); 
    img.setAttribute("height", "55px"); 
    imgNode.appendChild(img); 
    imgNode.className = "player-photo"; 
    row.appendChild(imgNode); 

    ... //Some more td is added below 

的問題是,每一個單列使用最初分配給照片的默認圖像,因爲火力通話時間過長和火力結束前imgNode已經追加到該行。我不是最有經驗的JavaScript程序員,但你會如何解決這樣的問題,以便更新到行中檢索資源?我需要使用Promise還是異步/等待?

回答

1

你需要改變你的代碼的整理了一下:

//Get the player 
var player = collection[i]; 

//Create a new table row 
var row = document.createElement("TR"); 
row.id = player.Id; 

//Add the player profile pic 
var imgNode = document.createElement("TD"); 
var img = document.createElement("IMG"); 
var photo = "https://usatftw.files.wordpress.com/2014/10/nfl_logo_new2.jpg?w=1000&h=750"; 
img.setAttribute("src", photo); 
playerbase.orderByKey().equalTo(player.Id).on('child_added', (function(currentImage){ 
    return function(snap) { 
     currentImage.setAttribute("src", snap.val()); 
    } 
})(img)); 


img.setAttribute("width", "55px"); 
img.setAttribute("height", "55px"); 
imgNode.appendChild(img); 
imgNode.className = "player-photo"; 
row.appendChild(imgNode); 

現在讓我試着解釋這裏發生了什麼。不要在回調函數中設置一個變量,這顯然不起作用,而是保存對每個圖像對象的引用。發生回調時,它具有正確的對象來操作並更改狀態。

這到底是怎麼回事?
在你的循環中,你創建了很多圖像。將它們想象爲img1,img2,img3 ... imgN
現在對於每個圖像我們都有一個回調函數:cb1,cb2,cb3 ... cbN
但回調可能不會按順序返回。所以它可能是cb3,cb1,cb2 ...
我們所做的是創建一個新功能。該功能將綁定到IMG1 CB1,IMG2到CB2等

由於火力地堡API仍然期望接收功能的一個參數,返回它:

return function(snap) { 
    currentImage.setAttribute("src", snap.val()); 
} 

但現在當前圖像總是糾正回調圖像。

+0

哇這個作品漂亮。在這種情況下,如果它與照片不同,你是否會關心解釋currentImage究竟是什麼? – JBurk94

+0

這很複雜,所以我會用解釋來更新我的答案。 –