Hendrik Vlaanderen Hendrik Vlaanderen - 2 months ago 5x
Javascript Question

Parse.com: How to paginate results from a Parse.Query?

Currently, I am querying results with the Javascript Parse.Object.extend, and templating these results in a list with underscoreJS.

Here is the code that queries the Parse Object and adds the objects to a Underscore template.

var Assignment = Parse.Object.extend("Assignments");
var query = new Parse.Query(Assignment);

success: function(results) {
var tableTemplate = $("#list-template").html();

error: function(error) {
alert("Error: " + error.code + " " + error.message);

And this is the Underscore template.

<script type="text/html" id='list-template'>
<% _.each(results,function(result){ %>
<li id="list-group-item">
<h4 class="list-group-item-heading"><%= result.get("Title") %></h4>
<p class="list-group-item-text"><%= result.get("Content") %></p>
<p class="list-group-item-text"><%= result.get("Categories") %></p>
<% }) %>


However, I do not understand how to paginate the results in Parse and Underscore.

I've tried the backbone paginator, but I am not great with Backbone, and I just don't understand how to combine it with the Parse queries.

If I have to use another templating solution, or another pagination solution besides backbone paginator, it is also fine. Anything will be helpful, I am quite stuck with this pagination.


Parse.com has skip() and limit(), somehow this is said to be useful, but I don't know how to implement it.


Here's just an abstracted example of pagination. The concept should be illustrated and you can adjust it to fit your specific situation.

// Set the current page number usually zero works great to start
// This is an arbitrary ex. but this value will come from your page (e.g. link etc.)
var page = 0;

// How much you want on a page
var displayLimit = 50;

// Get the count on a collection
var count;
myCollection.count().then(function(result){ count = result; });

// Your query
var Assignment = Parse.Object.extend("Assignments");
var query = new Parse.Query(Assignment);
query.skip(page * displayLimit);
// So with this above code, on page 0, you will get 50 results and skip 0 records.
// If your page var is 1, you'll skip the first 50 and get 50 results starting at 51
// So on so forth...

So your links can have the page data encoded in it somehow in that when you click on it, your function will know what page to jump to and grab the appropriate ones. The concept is the same for next / prev. On Next you just do a page++ and on Prev you can do a page--.

Hope this helps.


If you want to do something like displaying Assignments 51-100 of 237 you'd need to do a .count() to get the total number of records before hand.

To get the start number it's simply something like (page * displayLimit) + 1 To get the end number just keep in mind that if you're on the last page, you might not have a full 50 records or whatever your displayLimit is.