使用Firebase实现无限滚动? [英] 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); //将文章添加到< div>
});
我的代码当前加载了最后5个帖子,并将加载任何新帖子。不过,我也希望能够加载旧帖子。我有一个按钮,当点击将调用一个函数(我不确定如何实现)加载旧帖子。 如何检索这些较旧的帖子?
<箭头只是表示我想从底部开始检索帖子,到顶部)
您需要思考一下这样做。当您得到第一页的查询结果时,请记住结果中的第一项:
$ b $ pre $ firebaseRef.endAt() .limitToLast(5).on('child_added',function(childSnapshot,prevChildKey){
self.addChild(childSnapshot); //将帖子添加到< div>
});
尽管您无法通过Firebase索引访问子项目,但您可以存储项目的密钥并使用即开始下一个查询。
var firstKnownKey;
firebaseRef.orderByKey()。如果(!firstKnownKey){
firstKnownKey = childSnapshot.key;
self.addChild(childSnapshot); //将帖子添加到< div>
});
现在你有一个变量firstKnownKey,它有你见过的第一个键。为了得到前一批孩子,当你开始下一个查询时,你将这个值传递给 endAt()
:
firebaseRef.orderByKey()。endAt(firstKnownKey).limitToLast(5).on('child_added',function(childSnapshot,prevChildKey){
if(!firstKnownKey){
firstKnownKey = childSnapshot.key;
}
self.addChild(childSnapshot); //将文章添加到< div>
});
过去几天类似问题的解答:
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>
});
My code currently loads the last 5 posts and will load any new posts. However, I'd also like to be able to load older posts as well. I have a button that when clicked will call a function (that I'm unsure of how to implement) that loads older posts. How do I retrieve these older posts?
(The arrow just signifies that I want to retrieve posts starting from the bottom and working my way up to the top)
You need to think a bit backwards to do this. When you get the results for your query for the first page, remember the first item in the results:
firebaseRef.endAt().limitToLast(5).on('child_added', function(childSnapshot, prevChildKey) {
self.addChild(childSnapshot); // adds post to a <div>
});
While you cannot access child items by index with Firebase, you can store the key of an item and use that to start a next query.
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>
});
Now you have a variable firstKnownKey that has the first key you've ever seen. To get the previous batch of children, you pass that value in to endAt()
when you fire your next query:
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>
});
Answers to similar questions of the past few days:
这篇关于使用Firebase实现无限滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!