Y.DataTable.Paginator Class
Defines a Y.DataTable class extension to add capability to support a Paginator View-Model and allow paging of actively displayed data within the DT instance.
Works with either client-side pagination (i.e. local data, usually in form of JS Array) or in conjunction with remote server-side pagination, via either DataSource or ModelSync.REST.
Allows for dealing with sorted data, wherein the local data is sorted in place, and in the case of remote data the "sortBy" attribute is passed to the remote server.
Usage
var dtable = new Y.DataTable({
columns: [ 'firstName','lastName','state','age', 'grade' ],
data: enrollment.records,
scrollable: 'y',
height: '450px',
sortBy: [{lastName:'asc'}, {grade:-1}],
paginator: new PaginatorView({
model: new PaginatorModel({itemsPerPage:50, page:3}),
container: '#pagContA'
}),
resizePaginator: true
});
Client OR Server Pagination
Pagination can either be done solely on the "client", or from a remote "server". The attribute paginationSource is set to either of these strings. The trivial case is where the data is coming locally (i.e. in a JS array) and the user requests "client" pagination. Likewise when pagination occurs solely on a remote device, "server" is very straightforward. This module also provides a middle-path where the initial payload is obtained from a remote source, and then after loading, pagination is to be done on the "client" (see below).
A determination of whether the source of data
is either "local" data (i.e. a Javascript Array or Y.ModelList), or is
provided from a server (either DataSource or ModelSync.REST) is performed within the method _afterDataReset.
For server-side pagination, the OUTGOING request must include (as a minimum); page
and itemsPerPage
querystring
parameters (all others, including sortBy
are optional). Likewise, the INCOMING (returned response) must include as "meta-data" at
least totalItems
, plus any other PaginatorModel attributes. The key item within the returned response is totalItems'. If the returned
response does not contain
totalItems` metadata the PaginatorView will not be shown!.
We have provided an attribute serverPaginationMap as an object hash to translate both outgoing querystring parameter names and incoming (response returned) parameter names in order to match what is expected by the PaginatorModel. Please see this attribute or the examples for how to utilize this map for your use case.
Loading the "data" For a Page
Once the "source of data" is known, the method processPageRequest fires on a pageChange
.
For the case of "client" pagination, an internal buffer _mlistArray is set to hold all of the data. Each page request in this circumstance involves using simply Array slicing methods from the buffer. (See method paginatorLocalRequest for details)
The case of "remote data" (from a server) is actually more straightforward. For the case of ModelSync.REST remote data the current "pagination state" is processed through the serverPaginationMap hash (to convert to queryString format) and the ModelList.load() method is called. For the case of a DataSource, a similar approach is used where the requestStringTemplate is read, processed through the serverPaginationMap hash and a datasource.load() request is fired. (See methods paginatorMLRequest and paginatorDSRequestfor details)
This extension DOES NOT "cache" pages for remote data, it simply inserts the full returned data into the DT. So as a consequence, a pagination state change for remote data involves a simple request sent to the server source (either DataSource or ModelSync.REST) and the response results are loaded in the DT as in any other "response".
Loading the "initial data" remotely - then using "client" Pagination
A recent revision to this module now allows for the initial payload of data that constitutes the entire "dataset" to be loaded from a remote source (by the standard DataSource or ModelSync.REST methods).
By setting the paginationSource attribute to "client", this module proceeds with paginating the DataTable as if the data was initially set within the "data" property.
Sorting
This module supports sorting for both client and server side Pagination. Note that sorting for "server-side" is required to be accomplished by the remote server; the "sortBy" settings are passed in a remote page request.
For client-side Pagination the task is a more complex. We utilize an internal buffer to store the client-side data, so therefore the requested "sorting" is accomplished internally within method paginatorSortLocalData. Basic "client-side" sorting is supported in this method (limited to one sort key at a time). Implementers may override this method for more complex sorting needs.
Item Index
Methods
- _afterDataAdd
- _afterDataRemove
- _afterDataReset
- _afterDSResponse
- _afterMLResponse
- _afterRemoteResponse
- _afterSortByChange
- _afterSortPaginator
- _afterSyncUI
- _defPagMap
- _defPagState
- _gefPagState
- _initSortFn
- _notifyRender
- _pageChangeListener
- _sefPagState
- _setLocalData
- _setPaginator
- _setPagMap
- _srvPagMapObj
- _syncPaginatorSize
- _totalItemsListener
- addLocalData
- addRemoteData
- destructor
- getLocalData
- initializer
- paginatorDSRequest
- paginatorLocalRequest
- paginatorMLRequest
- paginatorSortLocalData
- processPageRequest
- refreshPaginator
- removeLocalData
- removeRemoteData
- resetLocalData
- resizePaginator
Properties
- _evtHandlesPag static
- _mlistArray static
- _pagDataSrc static
- paginator
- pagModel
Attributes
Methods
_afterDataAdd
-
o
Listener method that is called after the DataTable's data "add" event fires
Parameters:
-
o
ObjectEvent payload from ModelList's "add" event
_afterDataRemove
-
o
Over-ridable method to call after the DataTable's data "remove" event fires
Parameters:
-
o
ObjectEvent payload from ModelList.remove
_afterDataReset
-
o
A primary method for initially determining the origin of the "data" for paginating. DataTable calls "this.data.reset()" many times, most importantly at the very beginning before and before any remote responses have been received.
We use this fact to set an initial "type" of data origin (either 'mlist', 'ds' or 'local') to represent a ModelSync.REST origin, DataSource or just locally assigned data (default).
Then after the initial typing, listeners are set for the appropriate remote source of data, or for local data the assigned "data" attribute is used as the initial data.
After this method is first completed,
Parameters:
-
o
ObjectEvent object from the Model.reset event
_afterDSResponse
-
e
Method fires after DataTable/DataSource plugin fires it's "response" event, which includes the response object, including {results:, meta:} properties.
Parameters:
-
e
ObjectEvent object from DataSource's "response" event
_afterMLResponse
-
resp
Method fires after custom ModelSync.REST "load" action fires a user-defined "response" event. This can be implemented by extending ModelSync.REST by adding .parse() method which fires a custom "response" event including {results:, meta:} properties.
Usage Note: The user is REQUIRED to provide a custom "response" event in the ModelList parse overridden function in order for this to work properly.
Parameters:
-
resp
ObjectIncludes results and meta properties
-
resp
StringOriginal raw response argument received into ModelList "parse" method
-
parsed
ObjectParsed raw response object after conversion (typically via JSON)
-
results
ArrayArray of result Objects
-
meta
ObjectObject including properties mapped to include pagination properties
-
_afterRemoteResponse
-
o
-
rsource
Method fires after the "response" event from DataSource OR after the custom ModelList fires a REQUIRED user-defined "response" event. (typically a custom ModelList's .parse() method is over-ridden to provide the custom "response" event including {results:, meta:} properties.
Usage Note: The user is REQUIRED to provide a custom "response" event in the ModelList parse function in order for this to work properly.
Parameters:
-
o
ObjectIncludes results and meta properties passed in via "response" custom event;
-
results
ArrayArray of result Objects
-
meta
ObjectObject including properties mapped to include pagination properties
-
-
rsource
StringSource of response, either 'ds' or 'mlist'
_afterSortByChange
()
private
This is an OVERRIDE of the dt-scroll afterSortByChange event, which in the case of pagination needs to be amended to remove the ModelList comparator and sort method.
Added by T.Smith on 1/13/2013 to resolve sorting error on remote sortBy pagination (Thanks to blicksky on GitHub for raising this issue)
_afterSortPaginator
()
private
Listener that fires after the DT "sort" event processes. The Paginator must be reset to the currently selected new "page", based on the sorting criteria.
For remote sources this is easy, just send another remote page request.
For local data source it is more complex, as we have to deal with sorting the full local data array ...
_afterSyncUI
()
private
Method called to ensure that the _afterDataReset method is called, specifically for the case where a DataSource is used (which is hard to track when it is plugged in ...)
_defPagMap
()
Object
private
Default 'valueFn' function setting for the ATTR serverPaginationMap
, where
the defaults are simply the member names.
Returns:
_defPagState
()
Object
private
Sets default for the "paginationState" DataTable attribute complex object as an
object with all of PaginatorModel ATTRS and the sortBy
setting.
Returns:
_gefPagState
()
Object
private
Getter for the "paginationState" DataTable attribute complex object.
Returns:
_initSortFn
()
private
PATCH : This is an override of the DT _initSortFn from DT to help with a sorting problem Added by T.Smith on 1/13/2013 to resolve sorting error on remote sortBy pagination (Thanks to blicksky on GitHub for raising this issue)
_notifyRender
()
private
A method that fires after the DataTable renderView
method completes, that is approximately when
the DataTable has finished rendering.
_pageChangeListener
-
o
Listener that fires when the Model's 'pageChange' fires, this extracts the current page from the state object and then makes the appropriate processPageRequest call.
Parameters:
-
o
ObjectChange event facade for the PaginatorModel 'pageChange' event
_sefPagState
-
val
Sets default for the "paginationState" DataTable attribute complex object.
Parameters:
-
val
ObjectPagination state complex object settings
Returns:
_setLocalData
-
o
Method that stores the "local" data in an internal buffer within the _mlistArray static property. The _mlistArray is stored as a simple JS Array type (for speed), and is used to select current "pages" by Array slicing methods.
If the argument "o" is provided, it will be used as the new dataset for local data, if it is not set, then the current DT "data" attribute is used.
On a "sort" event, the buffer needs to be sorted first, then sliced for paging.
Parameters:
-
o
Array | ModelListOptional data to set as full local dataset
_setPaginator
-
val
This is a setter for the 'paginator' attribute, primarily to set the public property paginator
to the
attribute value.
Parameters:
-
val
PaginatorView | ViewThe PaginatorView instance to set
Returns:
_setPagMap
-
val
Setter method for the serverPaginationMap
attribute, which can be used to
merge the "default" object with the user-supplied object.
Parameters:
-
val
ObjectObject hash to serve as the attribute setting
Returns:
_srvPagMapObj
-
prop
-
dir
Helper method that searches the 'serverPaginationMap' ATTR and returns the requested property, including if it is nested as "toServer" or "fromServer" subattribute. ( Used in processPageRequest )
Parameters:
-
prop
StringProperty name to search for (expected matches in PaginatorModel ATTRS)
-
dir
StringDirectional (optional), either "to" (matches toServer) or "from" (matches fromServer)
Returns:
Example:
_srvPagMapObj("itemsPerPage") { itemsPerPage : 'numPageRecords' } { itemsPerPage : {toServer:'pageRows', fromServer:'pageRecordCount' }
_syncPaginatorSize
()
private
Method to adjust the CSS width of the paginator container and set it to the width of the underlying DT.
Reworked this to reset width to "yui3-datatable-columns", i.e. the THEAD element for both scrollable and non-scrollable to get around a 2px mismatch.
Returns:
_totalItemsListener
-
Change
A listener that monitors the "totalItems" attribute of the Paginator Model and if a zero list of items is returns it fires the "paginatorZeroItems" custom event.
Parameters:
-
Change
Objectevent facade from the PaginatorModel 'totalItemsChange' event
addLocalData
-
o
-
pgIndex
Helper method that responds to DT's "data:add" event (via .addRow/addRows), by adding the new record (in o.newVal) to the internal buffer and refreshing the Paginator UI.
NOTE: This only applies to FOR LOCAL DATA ONLY, for client-side pagination
Implementers are welcome to override this method with their own !!
Parameters:
-
o
ObjectEvent object from the ModelList.add event
-
pgIndex
NumberCalculated absolute index of the record within the entire dataset
addRemoteData
-
o
-
pgIndex
Overridable method that fires for server-side pagination when a data item is added via either "data:add" or .addRow.
It is up to implementers to either override this method or provide a mechanism (why not than ModelSync.REST!) to respond to the provided event.
Parameters:
-
o
ObjectChange event payload object from ModelList's .add method
-
pgIndex
NumberCalculated absolute index of the record within the entire dataset
destructor
()
protected
Destructor to clean up listener event handlers and the internal storage buffer.
getLocalData
()
Array
public
Method to return the entire internal buffer array used for client-side pagination. Note: This only applies to client-side pagination
Returns:
initializer
()
protected
chainable
This initializer sets up the listeners related to the original DataTable instance, to the PaginatorModel changes and related to the underlying "data" attribute the DT is based upon.
Returns:
paginatorDSRequest
-
requestString
Overrideable method to send the Pagination request to the DataSource.
By default the constructed requestString
is sent, but implementers can override this method to
include additional information in their remote request.
Parameters:
-
requestString
StringDataSource remote request string sent via DataTable.datasource load method
paginatorLocalRequest
-
url_obj
-
itemIndexStart
-
itemIndexEnd
Overrideable method to handle a Pagination request when using "local" data. This method takes care of slicing and resetting the "local data" array and re-syncing the DataTable.
Parameters:
-
url_obj
Object -
itemIndexStart
NumberCalculated ending index for this page number
-
itemIndexEnd
NumberCalculated ending index for this page number
paginatorMLRequest
-
url_object
Overrideable method to send the Pagination request to the ModelList for the "load" request. The default method simply passes the url_object (created/populated within method processPageRequest) to the ModelList's "load" method (assuming ModelSync.REST or other handling is provided).
Implementers are free to override this method to incorporate their own remote request.
Parameters:
-
url_object
ObjectThe pagination URL request object passed to the ModelList's sync layer
paginatorSortLocalData
()
public
Method that sorts the buffered local data (in _mlistArray) after a DataTable sort event is fired.
TODO: ONLY WORKS FOR single column sort presently and for "known" sorting methods (i.e. string, number, date)
Implementers can override this method to incorporate more advanced sorting
processPageRequest
-
page_no
-
pag_state
Primary workhorse method that is fired when the Paginator "page" changes, and returns a new subset of data for the DT (local data) or sends a new request to a remote source to populate the DT (remote data)
Parameters:
-
page_no
IntegerCurrent page number to change to
-
pag_state
ObjectPagination state object (this is NOT populated in local .. non-server type pagination) including;
-
indexStart
IntegerStarting index returned from server response
-
numRecs
IntegerCount of records returned from the response
-
Returns:
refreshPaginator
()
public
Utility method that fires a request for the currently active page, effectively "refreshing" the Paginator UI
removeLocalData
-
o
-
pgIndex
Helper method that responds to DT's "data:remove" event (invoked by .removeRow), by adding the new record (in o.newVal) to the internal buffer and refreshing the Paginator UI.
NOTE: This only applies to FOR LOCAL DATA ONLY, for client-side pagination
Implementers are welcome to override this method with their own !!
Parameters:
-
o
ObjectEvent object from the ModelList.remove event
-
pgIndex
NumberCalculated absolute index of the record within the entire dataset
removeRemoteData
-
o
-
pgIndex
Overridable method that fires for server-side pagination when a data item is deleted via either "data:remove" or .removeRow.
It is up to implementers to either override this method or provide a mechanism (why not than ModelSync.REST!) to respond to the provided event.
Parameters:
-
o
ObjectChange event payload object from ModelList's .remove method
-
pgIndex
NumberCalculated absolute index of the record within the entire dataset
resetLocalData
-
data
Method to re-initialize the original entire dataset when used with "client" pagination.
Parameters:
-
data
Array | ModelListData to be reset to ... either as a JS Array or a Y.ModelList
Returns:
resizePaginator
()
public
Method to sync the container for the paginator View with the underlying DataTable 'table' element.
Unfortunately, there isn't a distinct, definitive 'render' complete event due to DT's complex rendering, so I use a timer function to attempt a resize.
Properties
_evtHandlesPag
Array
protected
static
Array to hold Event handles to allow for cleanup in the destructor
Default: null
_mlistArray
Array
protected
static
Holder for the "original" un-paged data that the DataTable was based upon.
This property is stored as an Array, from the original "data" ModelList, only used for case of "local" data, is sliced as needed to re-set each data Page.
Populated in method _afterDataReset
Default: null
_pagDataSrc
String
protected
static
Placeholder for a text flag indicating the original provider of "data" for this DataTable, this is set initially in method _afterDataReset.
Set to either 'local', 'ds' or 'mlist' in method _afterDataReset
Populated in _afterDataReset. Utilized in processPageRequest
Default: null
paginator
Y.PaginatorView | View
public
A convenience property holder for the DataTable's "paginator" attribute (the Paginator-View instance).
Default: null
pagModel
Y.PaginatorModel | Model
public
A convenience property holder for the Paginator-View's Model attribute.
Default: null
Attributes
paginationSource
String
A flag to indicate if client-side pagination or server-side pagination is desired. Specifically, this attribute determines whether Page Requests are sent remotely or are handled internally.
Recognized settings are "client" (the default) or "server".
Note: In cases where the initial payload of data is obtained from a DS or ModelSyncREST server, but after data is received the user desires "client-side" pagination, this would be set to "client".
Default: 'client'
paginationState
Object
Attribute to track the full pagination state (i.e. the PaginatorModel) attributes all in one object.
Also includes the sortBy
property internally.
Default: unset
paginator
Y.View
Adds a paginator view (specifically Y.PaginatorView) instance to the DataTable.
Default: null
paginatorResize
Boolean
Flag to indicate if the Paginator container should be re-sized to the DataTable size after rendering is complete.
This attribute works best with a "bar" type of Paginator that is intended to look integral with a DataTable.
Default: false
requestStringTemplate
String
(SERVER DataSource only!) Includes the request queryString for a DataSource request (only!), which contains the pagination replacement strings to be appended to the DataSource's "source" string.
Default: ""
Example:
requestStringTemplate: "?currentPage={page}&pageRows={itemsPerPage}&sorting={sortBy}"
Note, the replacement parameters within this template should match the settings from the PaginatorModel attributes.
In cases where your server expects differing query parameters, you can utilize ATTR serverPaginationMap.
serverPaginationMap
Object
Defines a hash to convert expected PaginatorModel attributes to outgoing request queryString or returned (incoming response) meta data back to PaginatorModel attributes.
Example:
serverPaginationMap : {
totalItems : 'totalRows',
page : {toServer:'requestedPage', fromServer:'returnedPageNo'},
itemIndexStart: 'startRecord',
itemsPerPage: 'numPageRows'
}
// would map to an outgoing request of (for url:/data/orders) ;
/data/orders/{cust_no}?requestedPage={requestedPage}&numPageRows={numPageRows}
// for a JSON response of ...
{ "reply":"ok", "totalRows":478, "returnedPageNo":17, "startRecord":340, "numPageRows":20,
"results":[ {...} 20 total rows returned {...}] }
For default value, see _defPagMap
Events
afterDataAdd
Event fired when the DataTable's "data:add" event is fired, that includes ModelList.add's event payload.
This event could be used by implementers to handle refreshing of the local data. (not presently implemented)
Event Payload:
-
obj
Object -
oPayload
ObjectEvent payload from ModelList.add
-
pagIndex
NumberCalculated absolute index of the record within the entire dataset
afterDataRemove
Event fired when the DataTable's "data:remove" event is fired, that includes the ModelList.remove's event payload.
This event could be used by implementers to handle refreshing of the local data. (not presently implemented)
Event Payload:
-
obj
Object -
oPayload
ObjectEvent payload from ModelList.remove
-
pagIndex
NumberCalculated absolute index of the record within the entire dataset
pageUpdate
Fires after the DataTable-Paginator updates the page data and/or sends the remote request for more data
Event Payload:
-
pagStatus
Objectcontaining following;
-
pag_state
ObjectOf Paginator Model
getAttrs()
as an Object -
view
ViewInstance of the Paginator View
-
paginatorResize
Event fired after the _syncPaginatorSize method is called (requires ATTR paginatorResize) to be set true
paginatorZeroItems
Event fired when the "totalItems" setting of the Paginator Model is set to zero, due to a null response froma remote request or a null Array or ModelList being set.
render
Fires after the DataTable 'renderView' event fires