Ruby-on-rails – backbone.js pagination

backbone.jspaginationruby-on-rails

I am beginning to use Backbone and am trying to transition my Rails backend's html templates to javascript templates.

One thing I thought using backbone would be more advantageous is its concept of Models and Collections.
So say, I have 100 records and am paginating these records to 10 per page, normally, without quite a bit of javascript work, one can hardly expect a cached, ajax, one-page pagination experience. meaning, say, I landed on page one and now click page two, page two requests the next 10 records ajax'ly, and if I then click page one, I won't be making any more request to the server because it was there.

I haven't had any code written up but can anyone tell me how I can append the ajax requested newly arrived data to the existing collection for pagination?

For instance, remember Backbone's documentation say that your first load of the page should really contain bootstrapped data instead of making a second trip to fetch them. So

var projects_data = <%= @projects.to_json.html_safe %>;
var projects = new Cafe.Collections.ProjectsCollection();
var projects.reset(projects_data);

Now my projects variable contains, say, the first 10 records, and I someone retreive another round of 10, say, I save these newly arrived 10 in the variable

var projects_data_new = ...

Can I append them to the existing "projects" collection?

Or is this not the design pattern encouraged in Backbone in the case of pagination?

Best Answer

In backbone 0.5 and up, when you call fetch(), it is possible to specify that you wish to add rather than replace the dataset present on the client: fetch({add: true}). This will append new objects to the existing projects collection. You will still have to handle pagination presentation issues on your end.

The collection also only gets the JSON objects to add/fetch after they have been run through Backbone.Collection.parse(), which you can override to do things like "along with the projects, give me a count of all objects on the server, and return only the projects to the add/fetch." You can then use this metadata to correctly show how many pages the user can page through. If you want to be really clever, you can use the collection as a sparse array (my experience is that this is fine for collections of less than 10,000 items on a standard desktop or laptop, but not a tablet), and let the user flip through the pages arbitrarily, fetching the filler as needed.

Related Topic