[英]Implementing Infinite Scrolling with Firebase?
var self = this;
var firebaseRef = new Firebase(baseUrl + '/sparks');
firebaseRef.limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
self.addChild(childSnapshot); // adds post to a <div>
});
我的代碼目前加載了最后5個帖子,並將加載任何新帖子。 但是,我也希望能夠加載舊帖子。 我有一個按鈕,當點擊它將調用一個功能(我不知道如何實現)加載舊帖子。 如何檢索這些舊帖子?
(箭頭只表示我想從底部開始檢索帖子並一直向上移動到頂部)
你需要稍微考慮一下這樣做。 當您獲得第一頁的查詢結果時,請記住結果中的第一項:
firebaseRef.endAt().limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
self.addChild(childSnapshot); // adds post to a <div>
});
雖然您無法通過Firebase索引訪問子項,但您可以存儲項的鍵並使用它來開始下一個查詢。
var firstKnownKey;
firebaseRef.orderByKey().limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
if (!firstKnownKey) {
firstKnownKey = childSnapshot.key;
}
self.addChild(childSnapshot); // adds post to a <div>
});
現在你有一個變量firstKnownKey,它有你見過的第一個鍵。 要獲取上一批子項,在endAt()
下一個查詢時將該值傳遞給endAt()
:
firebaseRef.orderByKey().endAt(firstKnownKey).limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
if (!firstKnownKey) {
firstKnownKey = childSnapshot.key;
}
self.addChild(childSnapshot); // adds post to a <div>
});
過去幾天類似問題的答案:
因為endAt()
是包容性的,所以每當我進行無限滾動時,最后一項都會重復,所以我對frank van puffen的回答做了一些修改。
我發起一個列表childrenVal
來存儲所有的值,另一個列表childrenKey
來存儲所有的鍵和一個var firstKnownKey
,就像frank van puffen sugests。
var childrenVal=[];
var childrenKey=[];
var firstKnownKey = "";
第一次進行查詢時,您將獲得最后5個元素:
getFirst(){
firebaseRef.orderByKey().limitToLast(5).once('value')
.then((snap)=>{
snap.forEach(childSnap => {
childrenVal.unshift(childSnap.val());
childrenKey.unshift(childSnap.key);
});
firstKnownKey = childrenKey[childrenKey.length-1];
});
}
在下一個查詢中,您不希望firstKnownKey
重復,因此我執行了以下功能:
exclude(key){
return key.substring(0, key.length - 1) + String.fromCharCode(key.charCodeAt(key.length - 1) - 1)
}
對於查詢本身,以下函數:
getNext() {
firebaseRef.orderByKey().endAt(exclude(firstKnownKey)).limitToLast(5).once('value')
.then((snap) => {
snap.forEach(childSnap => {
childrenVal.unshift(childSnap.val());
childrenKey.unshift(childSnap.key);
});
firstKnownKey = childrenKey[childrenKey.length - 1];
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.