2017-06-01 47 views
0

我在這裏跟着教程第一最新數據,至信:http://www.meteorpedia.com/read/Infinite_Scrolling,其結果如預期通過本教程的作者,即無限滾動顯示第一數據(舊)收集到最後(最新),從上到下。爲了實現無限滾動的Meteorjs,顯示

問題是:我想要實現無限滾動的地方在新聞源中,就像在Facebook中發現的那樣,它顯示來自集合的最新(最新)數據,當您向下滾動,舊數據將被添加。

我試着使用createdAt:-1對數據進行排序倒退,但一個有趣的事情發生了:

在刷新時,新聞源將顯示前3箇舊數據(因爲我把3爲限),並然後當我向下滾動,另外3組數據(更新不最新)將在TOP舊數據的追加,並且這種模式繼續,直到數據完全加載在屏幕上。我想實現的是類似Facebook的資訊供稿即新聞源顯示最新/近期數據在頂部,並作爲用戶向下滾動,較舊的數據被調用,並添加到客戶端。作爲下面提供的代碼:

statusBox.html(客戶端)

<template name="statusBox"> 
    {{#each newsfeedList}} 

    ..HTML template goes here.. 

    {{/each}} 
    {{#if moreResults}} 
     <div id="showMoreResults" class="text-center" style="margin-left: 25px;"> 
      <span class="loading"><i class="fa fa-spinner fa-pulse" aria-hidden="true"></i></span> 
     </div> 
    {{/if}} 
</template> 

publish.js(服務器)

Meteor.publish('status', function(limit){ 
    return Status.find({}, {limit:limit}); 
}); 

statusBox.js(客戶端)

newsfeed_increment = 3; 
Session.setDefault('newsfeedLimit', newsfeed_increment); 
Deps.autorun(function(){ 
    Meteor.subscribe('status', Session.get('newsfeedLimit')); 
}); 

Template.statusBox.helpers({ 
    //Merging few collections into one template helper: https://stackoverflow.com/questions/21296712/merging-collections-in-meteor 
    newsfeedList: function(){ 
    return Status.find({},{sort:{createdAt:-1}}); 
    }, 

    ... 

    //Reference for infinitescrolling: http://www.meteorpedia.com/read/Infinite_Scrolling 
    moreResults: function() { 
    // If, once the subscription is ready, we have less rows than we 
    // asked for, we've got all the rows in the collection. 
    return !(Status.find().count() < Session.get("newsfeedLimit")); 
    } 
}); 

// whenever #showMoreResults becomes visible, retrieve more results 
function showMoreVisible() { 
    var threshold, target = $("#showMoreResults"); 
    if (!target.length) return; 

    threshold = $(window).scrollTop() + $(window).height() - target.height(); 

    if (target.offset().top < threshold) { 
     if (!target.data("visible")) { 
      // console.log("target became visible (inside viewable area)"); 
      target.data("visible", true); 
      Session.set("newsfeedLimit", 
       Session.get("newsfeedLimit") + newsfeed_increment); 
     } 
    } else { 
     if (target.data("visible")) { 
      // console.log("target became invisible (below viewable arae)"); 
      target.data("visible", false); 
     } 
    } 
} 

// run the above func every time the user scrolls 
$(window).scroll(showMoreVisible); 

其結果是: 後滾動 enter image description here

'狀態' 輸入分別爲1,2: enter image description here

結果 之前滾動,3,4,5,6順序。注意新增設箱4,5,6,對箱1,2,3的頂掉的圖片

回答

1

您需要在您的結果發佈功能

publish.js排序(服務器)

Meteor.publish('status', function(limit){ 
    return Status.find({}, {limit:limit, sort: {createdAt: -1}}); 
}); 
+0

漂亮!這解決了問題!謝謝@jamider! –