Backbone JS Pagination

backbone.js

I have been trying out backbone JS with rails and really like the way it organises the frontend. I have implemented a pagination solution similar to the one here https://gist.github.com/705733

I'm just wondering what the role of a collection is and how it should work with paginated results. Currently, it seems that when I fetch new objects from the database they override what's in the current collection. However, I could use {add: true} to add to current collection. This would then make pagination more difficult. And how about caching the result? Should i create a new collection for every page?

If anyone has done this or knows how to go about it would be of great help.

Best Answer

If your objective is to query & display items when a page is requested, you could do something like (pseudocode):

pages = {}


// when page N is needed
function fetch_page(n) {
 if (!pages[n]) {
    pages[n] = new ItemsCollection({page: n})
    pages[n].fetch();
 }     
}

So you keep a collection for each page.

If you also need a collection of all the items fetched so far, just keep one - and add fetched items to it every time you get them from the server.

Related Topic