繁体   English   中英

如何使用新的Firebase(2016)实现无限滚动?

[英]How to implement Infinite Scrolling with the new Firebase (2016)?

题:

如何使用javascript(和node.js)在Firebase中实现高效的无限滚动?


我检查了什么:

使用Firebase实现无限滚动?

问题:老火山^

使用AngularJs和Firebase进行无限滚动


代码来自: 使用AngularJs和Firebase进行无限滚动

“首先,我建议在你的Firebase中创建一个索引。对于这个答案,我创建了这个:

{
   "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这种方法,无论你的数据有多大,它的速度都很快。“

(回答于2015年10月26日15:02)

(作者:Jobsamuel)


问题

在该解决方案中,每当滚动到达屏幕高度的末尾时,将加载n个帖子。

根据屏幕尺寸,这意味着在某些时候会加载比所需更多的帖子(屏幕高度仅包含2个帖子,这意味着每当我们到达屏幕高度的末尾时,将加载3个以上的帖子。例如= 5)。

这意味着每次我们到达滚动高度结束时,将加载3*NumberOfTimesScrollHeightHasBeenPassed比所需更多的帖子。


MY CURRENT CODE(一次加载所有帖子,无限滚动):

var express = require("express");
var router = express.Router();

var firebase = require("firebase");

router.get('/index', function(req, res, next) {

    var pageRef = firebase.database().ref("posts/page");

    pageRef.once('value', function(snapshot){
        var page = [];
        global.page_name = "page";
        snapshot.forEach(function(childSnapshot){
            var key = childSnapshot.key;
            var childData = childSnapshot.val();
            page.push({
                id: key,
                title: childData.title,
                image: childData.image
            });
        });
        res.render('page/index',{page: page});
    });
});

这是无限分页的完整代码。

createPromiseCallback函数用于支持promise和callback。

function createPromiseCallback() {
  var cb;
  var promise = new Promise(function (resolve, reject) {
      cb = function (err, data) {
          if (err) return reject(err);
          return resolve(data);
      };
  });
  cb.promise = promise;
  return cb;
}

函数getPaginatedFeed实现了实际的分页

function getPaginatedFeed(endpoint, pageSize, earliestEntryId, cb) {
  cb = cb || createPromiseCallback();

 var ref = database.ref(endpoint);
  if (earliestEntryId) {
    ref = ref.orderByKey().endAt(earliestEntryId);
  }
  ref.limitToLast(pageSize + 1).once('value').then(data => {
    var entries = data.val() || {};

    var nextPage = null;
    const entryIds = Object.keys(entries);
    if (entryIds.length > pageSize) {
        delete entries[entryIds[0]];
        const nextPageStartingId = entryIds.shift();
        nextPage = function (cb) {
            return getPaginatedFeed(endpoint, pageSize, nextPageStartingId,                     cb);
        };
    }
    var res = { entries: entries, nextPage: nextPage };
    cb(null, res);
  });
  return cb.promise;
}

以下是如何使用getPaginatedFeed函数

var endpoint = '/posts';
var pageSize = 2;
var nextPage = null;
var dataChunk = null;
getPaginatedFeed(endpoint, pageSize).then(function (data) {
    dataChunk = data.entries;
    nextPage = data.nextPage;

    //if nexPage is null means there are no more pages left
    if (!nextPage) return;

    //Getting second page
    nextPage().then(function (secondpageData) {
        dataChunk = data.entries;
        nextPage = data.nextPage;
        //Getting third page
        if (!nextPage) return;

        nextPage().then(function (secondpageData) {
            dataChunk = data.entries;
            nextPage = data.nextPage;
            //You can call as long as your nextPage is not null, which means as long as you have data left
        });
    });

});

怎么样的问题放在屏幕上有多少项,你可以给出这样的解决方案,每个帖子给出固定的x高度,如果需要更多空间,在帖子底部放置“阅读更多”链接,这将显示缺失用户点击时的一部分。 在这种情况下,您可以在屏幕上保留固定的项目数。 此外,您可以检查屏幕分辨率,以便放置更多或更少的项目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM