One very common task many Backbone developers are faced with is rendering paginated data. For example, you might have a search page that can return hundreds of results, but you only want to show the first twenty results. To do this, you essentially need two Collection
classes: one for all of the results and the other for the results being displayed. However, switching between the two can be tricky, and you may not actually want to fetch hundreds of results at once. Instead, you might just want to fetch the first twenty, but still be able to know how many total results are available so that you can display that information to your users.
Backbone Paginator (https://github.com/backbone-paginator/backbone.paginator) is a specialized Collection
class created expressly for this purpose. Backbone Paginator was originally two separate libraries, but these libraries have since merged making Backbone Paginator the primary tool for handling paginated data in Backbone.
Backbone Paginator can be used in one of the following three modes:
To use Backbone Paginator, you simply extend its PageableCollection
class to create your own pageable Collection
class, as follows:
var BookResults = Backbone.PageableCollection.extend({ model: BookResult, queryParams: { currentPage: 'selected_page', pageSize: 'num_records' }, state: { firstPage: 0, currentPage: 5, totalRecords: 500 }, url: 'www.example.com/api/book_search_results' });
As you can see a PageableCollection
class is very similar to a normal Collection
class: It has the model
and url
properties, can be extended, and so on. However, it also has two special properties.
The first of these properties is queryParams
, which tells PageableCollection
how to interpret the pagination information in your server's response, in much the same way that a parse
method normally tells Backbone how to interpret your server's response. The second property is state
, which PageableCollection
uses to keep track of which page of results the user is currently on, how many results there are in a page, and so on.
The full Backbone Paginator library has several other options for both queryParams
and state
, as well as a set of pagination methods such as getPage
(for moving to a specific page of results) or setSorting
(for changing how the results are sorted). If you want to implement a paginated view yourself, you can find full documentation of Backbone Paginator on its GitHub page. However, as it turns out, you may not want to create your own View
of paginated data at all, because there's already a very powerful existing one that you can leverage instead: BackGrid.
18.220.179.153