noConflict

BROWSER ONLY

If you already have an object named PageableCollection attached to the Backbone module, you can use this to return a local reference to this PageableCollection class and reset the name PageableCollection to its previous definition.

// The left hand side gives you a reference to this // PageableCollection implementation, the right hand side // resets PageableCollection to your other PageableCollection. var PageableCollection = PageableCollection.noConflict();

noConflict(): PageableCollection
Returns
PageableCollection:

pageable:state:change

State change event. Fired when PageableCollection#state gets updated

pageable:state:change

PageableCollection

Drop-in replacement for Backbone.Collection. Supports server-side and client-side pagination and sorting. Client-side mode also support fully multi-directional synchronization of changes between pages.

new PageableCollection()

Extends Backbone.Collection

state

The container object to store all pagination states.

You can override the default state by extending this class or specifying them in an options hash to the constructor.

state
Properties
firstPage (number) : = 1 - The first page index. Set to 0 if your server API uses 0-based indices. You should only override this value during extension, initialization or reset by the server after fetching. This value should be read only at other times.
lastPage (number) : = null - The last page index. This value is read only and it's calculated based on whether firstPage is 0 or 1, during bootstrapping, fetching and resetting. Please don't change this value under any circumstances.
currentPage (number) : = null - The current page index. You should only override this value during extension, initialization or reset by the server after fetching. This value should be read only at other times. Can be a 0-based or 1-based index, depending on whether firstPage is 0 or 1. If left as default, it will be set to firstPage on initialization.
pageSize (number) : = 25 - How many records to show per page. This value is read only after initialization, if you want to change the page size after initialization, you must call PageableCollection#setPageSize.
totalPages (number) : = null - How many pages there are. This value is read only and it is calculated from totalRecords .
totalRecords (number) : = null - How many records there are. This value is required under server mode. This value is optional for client mode as the number will be the same as the number of models during bootstrapping and during fetching, either supplied by the server in the metadata, or calculated from the size of the response.
sortKey (string) : = null - The model attribute to use for sorting.
order (number) : = -1 - The order to use for sorting. Specify -1 for ascending order or 1 for descending order. If 0, no client side sorting will be done and the order query parameter will not be sent to the server during a fetch.

mode

mode
Properties
mode (string) : = "server" The mode of operations for this collection. "server" paginates on the server-side, "client" paginates on the client-side and "infinite" paginates on the server-side for APIs that do not support totalRecords .

queryParams

A translation map to convert PageableCollection state attributes to the query parameters accepted by your server API.

You can override the default state by extending this class or specifying them in options.queryParams object hash to the constructor.

queryParams
Properties
currentPage ((string | function (): string)) : = "page"
pageSize ((string | function (): string)) : = "per_page"
totalPages ((string | function (): string)) : = "total_pages"
totalRecords ((string | function (): string)) : = "total_entries"
sortKey ((string | function (): string)) : = "sort_by"
order ((string | function (): string)) : = "order"
directions (Object) : = {"-1": "asc", "1": "desc"} - A map for translating a PageableCollection#state.order constant to the ones your server API accepts.

constructor

Given a list of models or model attributues, bootstraps the full collection in client mode or infinite mode, or just the page you want in server mode.

If you want to initialize a collection to a different state than the default, you can specify them in options.state. Any state parameters supplied will be merged with the default. If you want to change the default mapping from PageableCollection#state keys to your server API's query parameter names, you can specifiy an object hash in option.queryParams. Likewise, any mapping provided will be merged with the default. Lastly, all Backbone.Collection constructor options are also accepted.

See:

new constructor(models: Array<Object>, options: Object)
Parameters
models (Array<Object>)
options (Object)
Name Description
options.comparator function (any, any): number If specified, this comparator is set to the current page under server mode, or the PageableCollection#fullCollection otherwise.
options.full boolean 0 If false and either a options.comparator or sortKey is defined, the comparator is attached to the current page. Default is true under client or infinite mode and the comparator will be attached to the PageableCollection#fullCollection.
options.state Object The state attributes overriding the defaults.
options.queryParam Object
Properties
fullCollection (Backbone.Collection) : CLIENT MODE ONLY This collection is the internal storage for the bootstrapped or fetched models. You can use this if you want to operate on all the pages.

_makeFullCollection

Makes a Backbone.Collection that contains all the pages.

_makeFullCollection(models: Array<(Object | Backbone.Model)>, options: Object): Backbone.Collection
Parameters
models (Array<(Object | Backbone.Model)>)
options (Object) Options for Backbone.Collection constructor.
Returns
Backbone.Collection:

_makeCollectionEventHandler

Factory method that returns a Backbone event handler that responses to the add, remove, reset, and the sort events. The returned event handler will synchronize the current page collection and the full collection's models.

_makeCollectionEventHandler(pageCol: PageableCollection, fullCol: Backbone.Collection): function (string, Backbone.Model, Backbone.Collection, Object)
Parameters
pageCol (PageableCollection)
fullCol (Backbone.Collection)
Returns
function (string, Backbone.Model, Backbone.Collection, Object): Collection event handler

_checkState

Sanity check this collection's pagination states. Only perform checks when all the required pagination state values are defined and not null. If totalPages is undefined or null, it is set to totalRecords / pageSize. lastPage is set according to whether firstPage is 0 or 1 when no error occurs.

_checkState(state: Object): Object
Parameters
state (Object)
Returns
Object: Returns the state object if no error was found.
Throws
  • TypeError: If totalRecords , pageSize , currentPage or firstPage is not a finite integer.
  • RangeError: If pageSize , currentPage or firstPage is out of bounds.

setPageSize

Change the page size of this collection.

Under most if not all circumstances, you should call this method to change the page size of a pageable collection because it will keep the pagination state sane. By default, the method will recalculate the current page number to one that will retain the current page's models when increasing the page size. When decreasing the page size, this method will retain the last models to the current page that will fit into the smaller page size.

If options.first is true, changing the page size will also reset the current page back to the first page instead of trying to be smart.

For server mode operations, changing the page size will trigger a PageableCollection#fetch and subsequently a reset event.

For client mode operations, changing the page size will reset the current page by recalculating the current page boundary on the client side.

If options.fetch is true, a fetch can be forced if the collection is in client mode.

setPageSize(pageSize: number, options: Object): (XMLHttpRequest | PageableCollection)
Parameters
pageSize (number) The new page size to set to PageableCollection#state.
options (Object) PageableCollection#fetch options.
Name Description
options.first boolean = false 0 Reset the current page number to the first page if true .
options.fetch boolean If true , force a fetch in client mode.
Returns
(XMLHttpRequest | PageableCollection): The XMLHttpRequest from fetch or this.
Throws

switchMode

Switching between client, server and infinite mode.

If switching from client to server mode, the #fullCollection is emptied first and then deleted and a fetch is immediately issued for the current page from the server. Pass false to options.fetch to skip fetching.

If switching to infinite mode, and if options.models is given for an array of models,PageableCollection#links will be populated with a URL per page, using the default URL for this collection.

If switching from server to client mode, all of the pages are immediately refetched. If you have too many pages, you can pass false to options.fetch to skip fetching.

If switching to any mode from infinite mode, thePageableCollection#links will be deleted.

switchMode(mode: ("server" | "client" | "infinite"), options: Object): (XMLHttpRequest | PageableCollection)
Parameters
mode (("server" | "client" | "infinite")) The mode to switch to.
options (Object)
Name Description
options.fetch boolean = true - If false , no fetching is done.
options.resetState boolean = true - If 'false', the state is not reset, but checked for sanity instead.
Returns
(XMLHttpRequest | PageableCollection): The XMLHttpRequest from fetch or this if options.fetch is false .

hasPreviousPage

hasPreviousPage(): boolean
Returns
boolean: true if this collection can page backward, false otherwise.

hasNextPage

hasNextPage(): boolean
Returns
boolean: true if this collection can page forward, false otherwise.

getFirstPage

Fetch the first page in server mode, or reset the current page of this collection to the first page in client or infinite mode.

getFirstPage(options: Object): (XMLHttpRequest | PageableCollection)
Parameters
options (Object) {@linkPageableCollection#getPage} options.
Returns
(XMLHttpRequest | PageableCollection): The XMLHttpRequest from fetch or this.

getPreviousPage

Fetch the previous page in server mode, or reset the current page of this collection to the previous page in client or infinite mode.

getPreviousPage(options: Object): (XMLHttpRequest | PageableCollection)
Parameters
options (Object) {@linkPageableCollection#getPage} options.
Returns
(XMLHttpRequest | PageableCollection): The XMLHttpRequest from fetch or this.

getNextPage

Fetch the next page in server mode, or reset the current page of this collection to the next page in client mode.

getNextPage(options: Object): (XMLHttpRequest | PageableCollection)
Parameters
options (Object) {@linkPageableCollection#getPage} options.
Returns
(XMLHttpRequest | PageableCollection): The XMLHttpRequest from fetch or this.

getLastPage

Fetch the last page in server mode, or reset the current page of this collection to the last page in client mode.

getLastPage(options: Object): (XMLHttpRequest | PageableCollection)
Parameters
options (Object) {@linkPageableCollection#getPage} options.
Returns
(XMLHttpRequest | PageableCollection): The XMLHttpRequest from fetch or this.

getPage

Given a page index, set PageableCollection#state.currentPage to that index. If this collection is in server mode, fetch the page using the updated state, otherwise, reset the current page of this collection to the page specified by index in client mode. If options.fetch is true, a fetch can be forced in client mode before resetting the current page. Under infinite mode, if the index is less than the current page, a reset is done as in client mode. If the index is greater than the current page number, a fetch is made with the results appended toPageableCollection#fullCollection. The current page will then be reset after fetching.

getPage(index: (number | string), options: Object): (XMLHttpRequest | PageableCollection)
Parameters
index ((number | string)) The page index to go to, or the page name to look up fromPageableCollection#links in infinite mode.
options (Object) {@linkPageableCollection#fetch} options or reset options for client mode when options.fetch is false .
Name Description
options.fetch boolean = false - If true, force a {@linkPageableCollection#fetch} in client mode.
Returns
(XMLHttpRequest | PageableCollection): The XMLHttpRequest from fetch or this.
Throws
  • TypeError: If index is not a finite integer under server or client mode, or does not yield a URL fromPageableCollection#links under infinite mode.
  • RangeError: If index is out of bounds.

getPageByOffset

Fetch the page for the provided item offset in server mode, or reset the current page of this collection to the page for the provided item offset in client mode.

getPageByOffset(offset: number, options: Object): (XMLHttpRequest | PageableCollection)
Parameters
offset (number)
options (Object) {@linkPageableCollection#getPage} options.
Returns
(XMLHttpRequest | PageableCollection): The XMLHttpRequest from fetch or this.

sync

Overidden to make getPage compatible with Zepto.

sync(method: string, model: (Backbone.Model | Backbone.Collection), options: Object): XMLHttpRequest
Parameters
method (string)
model ((Backbone.Model | Backbone.Collection))
options (Object)
Returns
XMLHttpRequest:

Parse pagination links from the server response. Only valid under infinite mode.

Given a response body and a XMLHttpRequest object, extract pagination links from them for infinite paging.

This default implementation parses the RFC 5988 Link header and extract 3 links from it - first, prev, next. Any subclasses overriding this method must return an object hash having only the keys above. However, simply returning a next link or an empty hash if there are no more links should be enough for most implementations.

parseLinks(resp: any, options: Object): Object
Parameters
resp (any) The deserialized response body.
options (Object)
Name Description
options.xhr XMLHttpRequest The XMLHttpRequest object for this response.
Returns
Object:

parse

Parse server response data.

This default implementation assumes the response data is in one of two structures:

[ {}, // Your new pagination state [{}, ...] // An array of JSON objects ]

Or,

[{}] // An array of JSON objects

The first structure is the preferred form because the pagination states may have been updated on the server side, sending them down again allows this collection to update its states. If the response has a pagination state object, it is checked for errors.

The second structure is the Backbone.Collection#parse default.

*Note:** this method has been further simplified since 1.1.7. While existingPageableCollection#parse implementations will continue to work, new code is encouraged to overridePageableCollection#parseState andPageableCollection#parseRecords instead.

parse(resp: Object, options: Object): Array<Object>
Parameters
resp (Object) The deserialized response data from the server.
options (Object) The options for the ajax request
Returns
Array<Object>: An array of model objects

parseState

Parse server response for server pagination state updates. Not applicable under infinite mode.

This default implementation first checks whether the response has any state object as documented inPageableCollection#parse. If it exists, a state object is returned by mapping the server state keys to this pageable collection instance's query parameter keys using queryParams.

It is NOT neccessary to return a full state object complete with all the mappings defined inPageableCollection#queryParams. Any state object resulted is merged with a copy of the current pageable collection state and checked for sanity before actually updating. Most of the time, simply providing a new totalRecords value is enough to trigger a full pagination state recalculation.

parseState: function (resp, queryParams, state, options) { return {totalRecords: resp.total_entries}; }

If you want to use header fields use:

parseState: function (resp, queryParams, state, options) { return {totalRecords: options.xhr.getResponseHeader("X-total")}; }

This method MUST return a new state object instead of directly modifying the PageableCollection#state object. The behavior of directly modifying PageableCollection#state is undefined.

parseState(resp: Object, queryParams: Object, state: Object, options: Object): Object
Parameters
resp (Object) The deserialized response data from the server.
queryParams (Object) A copy of PageableCollection#queryParams.
state (Object) A copy of PageableCollection#state.
options (Object) The options passed through from parse . (backbone >= 0.9.10 only)
Returns
Object: A new (partial) state object.

parseRecords

Parse server response for an array of model objects.

This default implementation first checks whether the response has any state object as documented inPageableCollection#parse. If it exists, the array of model objects is assumed to be the second element, otherwise the entire response is returned directly.

parseRecords(resp: Object, options: Object): Array<Object>
Parameters
resp (Object) The deserialized response data from the server.
options (Object) The options passed through from the parse . (backbone >= 0.9.10 only)
Returns
Array<Object>: An array of model objects

fetch

Fetch a page from the server in server mode, or all the pages in client mode. Under infinite mode, the current page is refetched by default and then reset.

The query string is constructed by translating the current pagination state to your server API query parameter usingPageableCollection#queryParams. The current page will reset after fetch.

fetch(options: Object): XMLHttpRequest
Parameters
options (Object) Accepts all Backbone.Collection#fetch options.
Returns
XMLHttpRequest:

_makeComparator

Convenient method for making a comparator sorted by a model attribute identified by sortKey and ordered by order.

Like a Backbone.Collection, a PageableCollection will maintain the current page in sorted order on the client side if a comparator is attached to it. If the collection is in client mode, you can attach a comparator toPageableCollection#fullCollection to have all the pages reflect the global sorting order by specifying an option full to true. You must call sort manually orPageableCollection#fullCollection.sort after calling this method to force a resort.

While you can use this method to sort the current page in server mode, the sorting order may not reflect the global sorting order due to the additions or removals of the records on the server since the last fetch. If you want the most updated page in a global sorting order, it is recommended that you set PageableCollection#state.sortKey and optionally PageableCollection#state.order, and then callPageableCollection#fetch.

_makeComparator(sortKey: string, order: number, sortValue: ((function (Backbone.Model, string): Object) | string)): function (Backbone.Model, string): number
Parameters
sortKey (string) = this.state.sortKey - See state.sortKey .
order (number) = this.state.order - See state.order .
sortValue (((function (Backbone.Model, string): Object) | string)) See PageableCollection#setSorting.
Returns
function (Backbone.Model, string): number: See Backbone.Collection.comparator .

setSorting

Adjusts the sorting for this pageable collection.

Given a sortKey and an order, sets state.sortKey and state.order. A comparator can be applied on the client side to sort in the order defined if options.side is "client". By default the comparator is applied to thePageableCollection#fullCollection. Set options.full to false to apply a comparator to the current page under any mode. Setting sortKey to null removes the comparator from both the current page and the full collection.

If a sortValue function is given, it will be passed the (model, sortKey) arguments and is used to extract a value from the model during comparison sorts. If sortValue is not given, model.get(sortKey) is used for sorting.

setSorting(sortKey: string, order: number, options: Object): PageableCollection
Parameters
sortKey (string) See state.sortKey .
order (number) =this.state.order - See state.order .
options (Object)
Name Description
options.side string By default, "client" if mode is "client" , "server" otherwise.
options.full boolean = true
options.sortValue ((function (Backbone.Model, string): Object) | string)
Returns
PageableCollection: this