implement Infinite Scrolling on click of button in Meteor

100 views Asked by At

From publication i am setting an argument called limit. and this is my controller

MainPageController = BaseController.extend({

findOptions: function() {
return {sort: {createdAt: 1}};
},

waitOn: function() {
return Meteor.subscribe("allCars",5,this.findOptions());
},

data: function(){
 return {cars: Cars.find({},this.findOptions() )};
}
});

in my Template i have a button on click of which i want to load the next 5 records. my helpers are in different file. how can i implement this infinite scrolling. please help

Publication

Meteor.publish('allcars', function(limit){
return Jobs.find({}, {limit: limit});
});

then i am setting a default session variable for it

Template.jobsList.onCreated(function(){
    Session.setDefault("carsLimit",5);
});

after this in the helper i am very confused and its a whole lot of mess i have done.

and this is my template

<div class="col s12">
  <ul class="cars-list">
    {{#each allCars}}
    <li>
      {{> carItem}}
   </li>
   {{/each}}
  </ul>
1

There are 1 answers

11
SylvainB On BEST ANSWER

Meteorpedia has a piece on infinite scrolling which is, in my opinion, the simplest implementation for infinite scrolling in meteor. It's dead simple.

In your case (pressing a button) it would be even simpler, as you have no need to listen to scrolling events. Just increment the itemsLimit session variable every time your button is pressed. (no need for a showMoreVisible() function in your case)

Template.jobsList.events({
  'click #showMoreResults': function (e, t) {
    Session.set("carsLimit",
            Session.get("carsLimit") + 5);
  }
});

Template.jobsList.helpers({
  'moreResults': function() {
    return !(Cars.find().count() < Session.get("carsLimit"));
  }
});

Template.jobsList.onRendered(function(){
  Session.set("carsLimit",5);
  this.autorun(function () {
    Meteor.subscribe("allCars", Session.get('carsLimit'));
  });
});

And on your template:

<div class="col s12">
  <ul class="cars-list">
    {{#each allCars}}
    <li>
      {{> carItem}}
   </li>
   {{/each}}
   {{#if moreResults}}
   <li id="showMoreResults">More cars!</li>
   {{/if}}
  </ul>