如何对从firebase获得的数据实现无限滚动。到目前为止,我发现了一个angularjs directive,它的效果非常好,但是我很难用fireable实现它,因为firebase会在一个请求中返回所有数据,这不是我想要的。
答案 0 :(得分:19)
几周前,我创建了一个JS函数,允许在my app中无限滚动。
首先,当用户访问网站时显示一组数据:
// Add a callback that is triggered for each message.
var n = 25; // Step size for messages display.
$(window).load(function() {
lastMessagesQuery = messagesRef.limit(n);
lastMessagesQuery.on('child_added', function (snapshot) {
var message = snapshot.val();
$('<div/>').text(message.text).prependTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
});
$('#messagesDiv').fadeTo(1000, 1);
});
然后,使无限滚动成为可能的功能:
// Pagination.
var i = 0; // Record variable.
function moreMessages () {
i += n; // Record pagination updates.
moreMessagesQuery = messagesRef; // Firebase reference.
moreMessagesQuery.on('value', function (snapshot) {
var data = snapshot.exportVal(); // Fetch all data from Firebase as an Object.
var keys = Object.keys(data).reverse(); // Due to the Keys are ordered from the oldest to the newest, it nessesary to change its sequence in order to display Firebase data snapshots properly.
var total_keys = Object.keys(data).length;
var k = keys[i]; // Key from where to start counting. Be careful what Key you pick.
if (i < total_keys) { // Stop displaying messages when it reach the last one.
lastMessagesQuery = messagesRef.endAt(null, k).limit(n); // Messages from a Key to the oldest.
lastMessagesQuery.on('child_added', function (snapshot) {
var message = snapshot.val();
$('<div/>').text(message.text).appendTo($('#messagesDiv')).hide().fadeIn(1000); // Add set of messages (from the oldest to the newest) at the end of #messagesDiv.
});
}
});
}
最后,无限滚动:
// Load more messages when scroll reach the bottom.
$(window).scroll(function() {
if (window.scrollY == document.body.scrollHeight - window.innerHeight) {
moreMessages();
}
});
它适用于小型数据集。我希望这可以帮助您解决问题(或者给您更多想法)。
2015年10月更新
Firebase自我原来的回复以来有所增长,这意味着现在只需使用Javascript API即可轻松实现无限滚动:
首先,我建议您使用Firebase中的create an Index。对于这个答案,我创建了这个:
{
"rules": {
".read": true,
".write": false,
"messages": {
".indexOn": "id"
}
}
}
然后,让我们用Firebase做一些魔术:
// @fb: your Firebase.
// @data: messages, users, products... the dataset you want to do something with.
// @_start: min ID where you want to start fetching your data.
// @_end: max ID where you want to start fetching your data.
// @_n: Step size. In other words, how much data you want to fetch from Firebase.
var fb = new Firebase('https://<YOUR-FIREBASE-APP>.firebaseio.com/');
var data = [];
var _start = 0;
var _end = 9;
var _n = 10;
var getDataset = function() {
fb.orderByChild('id').startAt(_start).endAt(_end).limitToLast(_n).on("child_added", function(dataSnapshot) {
data.push(dataSnapshot.val());
});
_start = _start + _n;
_end = _end + _n;
}
最后,更好的无限滚动(没有jQuery):
window.addEventListener('scroll', function() {
if (window.scrollY === document.body.scrollHeight - window.innerHeight) {
getDataset();
}
});
我在React使用这种方法,无论你的数据有多大,它的速度都很快。