Pages

Wednesday, May 4, 2016

Learning Meteor.js [Part 12]: Add infinite paging

Sending the whole collection of ingredients at load time will not scale, so the next thing to do is to add paging to the list. I saw many paging packages available, but since the feature would eventually grow to support searching as well, I decided to roll my own. First thing is to change the publication to accept a limit:
Meteor.publish('ingredients', (limit) => {
    return Ingredients.find({}, {
        sort: { name: 1 },
        limit: limit
    });
});

Now the template needs to send the limit when subscribing to the collection, and it needs to re-run the subscription whenever a "load more" button is clicked. This is where the magic of 'autorun' and 'ReactiveVar' comes into play:
Template.ingredientsListPart.onCreated(() => {
    var instance = this;

    instance.limit = new ReactiveVar(5);

    instance.autorun(function() {
        var limit = instance.limit.get();

        instance.subscribe('ingredients', limit);
    });
});

If you are familiar with Knockout, think of ReactiveVar as a knockout observable and autorun as a computed. Whenever the limit changes, it will cause the autorun function to re-evaluate. All that is left is to wire up the button to load more:
Template.ingredientsListPart.events({
    'click .ingredients-load-more': function(event, instance) {
        event.preventDefault();
        var newLimit = instance.limit.get() + 5;
        instance.limit.set(newLimit);
    }
});

And with that paging is enabled. The code shown here has been edited for brevity, you can checkout this tag for the full working solution or view the live demo.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.