DataTable Class
A Widget for displaying tabular data. Before feature modules are use()
d,
this class is functionally equivalent to DataTable.Base. However, feature
modules can modify this class in non-destructive ways, expanding the API and
functionality.
This is the primary DataTable class. Out of the box, it provides the ability to dynamically generate an HTML table from a set of column configurations and row data. But feature module inclusion can add table sorting, pagintaion, highlighting, selection, and more.
// Basic use
var table = new Y.DataTable({
columns: ['firstName', 'lastName', 'age'],
data: [
{ firstName: 'Frank', lastName: 'Zappa', age: 71 },
{ firstName: 'Frank', lastName: 'Lloyd Wright', age: 144 },
{ firstName: 'Albert', lastName: 'Einstein', age: 132 },
...
]
});
table.render('#in-here');
// Table with loaded features.
// The functionality of this table would require additional modules be use()d,
// but the feature APIs are aggregated onto Y.DataTable.
// (Snippet is for illustration. Not all features are available today.)
var table = new Y.DataTable({
columns: [
{ type: 'checkbox', defaultChecked: true },
{ key: 'firstName', sortable: true, resizable: true },
{ key: 'lastName', sortable: true },
{ key: 'role', formatter: toRoleName }
],
data: {
source: 'http://myserver.com/service/json',
type: 'json',
schema: {
resultListLocator: 'results.users',
fields: [
'username',
'firstName',
'lastName',
{ key: 'role', type: 'number' }
]
}
},
recordType: UserModel,
pagedData: {
location: 'footer',
pageSizes: [20, 50, 'all'],
rowsPerPage: 20,
pageLinks: 5
},
editable: true,
filterable: true
});
Item Index
Methods
- _addVirtualScrollbar
- _afterColumnsChange
- _afterContentChange
- _afterMessageColumnsChange
- _afterMessageDataChange
- _afterScrollableChange
- _afterScrollHeightChange
- _afterShowMessagesChange
- _afterSortByChange
- _afterSortDataChange
- _afterSortRecordChange
- _bindMessageUI
- _bindScrollUI
- _bindSortUI
- _calcScrollHeight
- _createColumnGroup
- _createRecordClass
- _createTable
- _createTBody
- _createTFoot
- _createTHead
- _createXScrollNode
- _createYScrollNode
- _defAddColumnFn
- _defModifyColumnFn
- _defMoveColumnFn
- _defRemoveColumnFn
- _defRenderBodyFn
- _defRenderFooterFn
- _defRenderHeaderFn
- _defRenderTableFn
- _defSortFn
- _fixColumnWidths
- _getColumns
- _getColumnset
- _getData
- _getSortBy
- _initColumns
- _initData
- _initEvents
- _initMessageNode
- _initMessageStrings
- _initRecordType
- _initSortFn
- _initSortStrings
- _initViewConfig
- _mergeXScrollContent
- _mergeYScrollContent
- _onUITriggerSort
- _parseColumns
- _parseSortable
- _removeHeaderScrollPadding
- _renderSortable
- _setColumnMap
- _setColumnset
- _setColumnWidth
- _setData
- _setDisplayColumns
- _setHeaderScrollPadding
- _setRecordset
- _setRecordType
- _setScrollable
- _setScrollProperties
- _setSortBy
- _setYScrollColWidths
- _sortComparator
- _splitXScrollContent
- _splitYScrollContent
- _syncMessageUI
- _syncScrollUI
- _syncVirtualScroll
- _uiSetCaption
- _uiSetColumns
- _uiSetMessage
- _uiSetScrollable
- _uiSetSortable
- _uiSetSummary
- _uiSetWidth
- _validateSortable
- _validateSortBy
- _validateView
- addColumn
- addRow
- addRows
- bindUI
- delegate
- destructor
- getCell
- getColumn
- getRow
- hideMessage
- initializer
- initializer
- initializer
- initializer
- initializer
- modifyColumn
- modifyRow
- moveColumn
- removeColumn
- removeRow
- renderUI
- scrollTo
- setColumnWidth
- showMessage
- sort
- syncUI
- toggleSort
Properties
- _bodyConfig
- _CAPTION_TABLE_TEMPLATE
- _columnMap
- _displayColumns
- _footerConfig
- _headerConfig
- _messageNode
- _SCROLLBAR_TEMPLATE
- _sortable
- _sortBy
- _tableNode
- _viewConfig
- _X_SCROLLER_TEMPLATE
- _xScroll
- _xScrollNode
- _Y_SCROLLER_TEMPLATE
- _yScroll
- _yScrollNode
- body
- CAPTION_TEMPLATE
- COL_TEMPLATE
- COLGROUP_TEMPLATE
- data
- foot
- head
- MESSAGE_TEMPLATE
- SORTABLE_HEADER_TEMPLATE
- TABLE_TEMPLATE
- TBODY_TEMPLATE
- TFOOT_TEMPLATE
- THEAD_TEMPLATE
Attributes
Methods
_addVirtualScrollbar
()
protected
Creates a vertical scrollbar absolutely positioned over the right edge of the
_xScrollNode
to relay scrolling to the _xScrollNode
(masked) below.
Without this, the _yScrollNode
's scrollbar would not be visible until the
_xScrollNode
was scrolled to the far right.
_afterColumnsChange
-
e
Updates the _columnMap
property in response to changes in the columns
attribute.
Parameters:
-
e
EventFacadeThe
columnsChange
event object
_afterContentChange
-
e
Relays changes in the table structure or content to trigger a reflow of the scrolling setup.
Parameters:
-
e
EventFacadeThe relevant change event (ignored)
_afterMessageColumnsChange
-
e
Updates the colspan of the <td>
used to display the messages.
Parameters:
-
e
EventFacadeThe columnsChange event
_afterMessageDataChange
-
e
Relays to _uiSetMessage
to hide or show the message node.
Parameters:
-
e
EventFacadeThe dataChange event
_afterScrollableChange
-
e
Reacts to changes in the scrollable
attribute by updating the _xScroll
and _yScroll
properties and syncing the scrolling structure accordingly.
Parameters:
-
e
EventFacadeThe relevant change event (ignored)
_afterScrollHeightChange
-
e
Syncs the scrolling structure if the table is configured to scroll vertically.
Parameters:
-
e
EventFacadeThe relevant change event (ignored)
_afterShowMessagesChange
-
e
Removes the message node if showMessages
is false
, or relays to
_uiSetMessage
if true
.
Parameters:
-
e
EventFacadeThe showMessagesChange event
_afterSortByChange
-
e
Sorts the data
ModelList based on the new sortBy
configuration.
Parameters:
-
e
EventFacadeThe
sortByChange
event
_afterSortDataChange
-
e
Applies the sorting logic to the new ModelList if the newVal
is a new
ModelList.
Parameters:
-
e
EventFacadethe
dataChange
event
_afterSortRecordChange
-
e
Checks if any of the fields in the modified record are fields that are
currently being sorted by, and if so, resorts the data
ModelList.
Parameters:
-
e
EventFacadeThe Model's
change
event
_bindMessageUI
()
protected
Binds the events necessary to keep the message node in sync with the current table and configuration state.
_bindScrollUI
()
protected
Attaches internal subscriptions to keep the scrolling structure up to date
with changes in the table's data
, columns
, caption
, or height
. The
width
is taken care of already.
This executes after the table's native bindUI
method.
_bindSortUI
()
protected
Subscribes to state changes that warrant updating the UI, and adds the click handler for triggering the sort operation from the UI.
_calcScrollHeight
()
protected
Calculates the height of the div containing the vertically scrolling rows.
The height is produced by subtracting the offsetHeight
of the scrolling
<div>
from the clientHeight
of the contentBox
.
_createColumnGroup
()
protected
Renders the table's <colgroup>
and populates the _colgroupNode
property.
_createRecordClass
-
attrs
Creates a Model subclass from an array of attribute names or an object of
attribute definitions. This is used to generate a class suitable to
represent the data passed to the data
attribute if no recordType
is
set.
Parameters:
-
attrs
String | ObjectNames assigned to the Model subclass's
ATTRS
or its entireATTRS
definition object
Returns:
_createTable
()
Node
protected
Creates the <table>
.
Returns:
<table>
node
_createTBody
()
protected
Creates a <tbody>
node from the TBODY_TEMPLATE
.
_createTFoot
()
protected
Creates a <tfoot>
node from the TFOOT_TEMPLATE
.
_createTHead
()
protected
Creates a <thead>
node from the THEAD_TEMPLATE
.
_createXScrollNode
()
protected
Populates the _xScrollNode
property by creating the <div>
Node described
by the _X_SCROLLER_TEMPLATE
.
_createYScrollNode
()
protected
Populates the _yScrollNode
property by creating the <div>
Node described
by the _Y_SCROLLER_TEMPLATE
.
_defAddColumnFn
-
e
Default function for the addColumn
event.
Inserts the specified column at the provided index.
Parameters:
-
e
EventFacadeThe
addColumn
event-
column
ObjectThe new column definition object
-
index
Number | NumberThe array index to insert the new column
-
_defModifyColumnFn
-
e
Default function for the modifyColumn
event.
Mixes the new column properties into the specified column definition.
Parameters:
-
e
EventFacadeThe
modifyColumn
event-
column
Object | String | Number | NumberThe column definition object or identifier
-
newColumnDef
ObjectThe properties to assign to the column
-
_defMoveColumnFn
-
e
Default function for the moveColumn
event.
Removes the specified column from its current location and inserts it at the specified array index (may be an array of indexes for nested headers).
Parameters:
-
e
EventFacadeThe
moveColumn
event-
column
Object | String | Number | NumberThe column definition object or identifier
-
index
ObjectThe destination index to move to
-
_defRemoveColumnFn
-
e
Default function for the removeColumn
event.
Splices the specified column from its containing columns array.
Parameters:
-
e
EventFacadeThe
removeColumn
event-
column
Object | String | Number | NumberThe column definition object or identifier
-
_defRenderBodyFn
-
e
Calls render()
on the bodyView
class instance and inserts the view's
container into the <table>
.
Assigns the instance's body
property from e.view
and the _tbodyNode
from the view's container
attribute.
Parameters:
-
e
EventFacadeThe renderBody event
_defRenderHeaderFn
-
e
Calls render()
on the headerView
class instance and inserts the view's
container into the <table>
.
Assigns the instance's head
property from e.view
and the _theadNode
from the view's container
attribute.
Parameters:
-
e
EventFacadeThe renderHeader event
_defRenderTableFn
-
e
Renders the <table>
, <caption>
, and <colgroup>
.
Assigns the generated table to the _tableNode
property.
Parameters:
-
e
EventFacadeThe renderTable event
_defSortFn
-
e
Sets the sortBy
attribute from the sort
event's e.sortBy
value.
Parameters:
-
e
EventFacadeThe
sort
event
_fixColumnWidths
()
protected
Assigns style widths to all columns based on their current offsetWidth
s.
This faciliates creating a clone of the <colgroup>
so column widths are
the same after the table is split in to header and data tables.
_getColumns
-
columns
-
name
The getter for the columns
attribute. Returns the array of column
configuration objects if instance.get('columns')
is called, or the
specific column object if instance.get('columns.columnKey')
is called.
Parameters:
-
columns
ObjectThe full array of column objects
-
name
StringThe attribute name requested (e.g. 'columns' or 'columns.foo');
_getColumnset
-
ignored
-
name
Relays the get()
request for the deprecated columnset
attribute to the
columns
attribute.
THIS BREAKS BACKWARD COMPATIBILITY. 3.4.1 and prior implementations will
expect a Columnset instance returned from get('columnset')
.
Parameters:
-
ignored
ObjectThe current value stored in the
columnset
state -
name
StringThe attribute name requested (e.g. 'columnset' or 'columnset.foo');
_getData
-
val
The getter for the data
attribute. Returns the ModelList stored in the
data
property. If the ModelList is not yet set, it returns the current
raw data (presumably an empty array or undefined
).
Parameters:
-
val
Object | ModelListThe current data stored in the attribute
_getSortBy
-
val
-
detail
Getter for the sortBy
attribute.
Supports the special subattribute "sortBy.state" to get a normalized JSON version of the current sort state. Otherwise, returns the last assigned value.
For example:
var table = new Y.DataTable({
columns: [ ... ],
data: [ ... ],
sortBy: 'username'
});
table.get('sortBy'); // 'username'
table.get('sortBy.state'); // { key: 'username', dir: 1 }
table.sort(['lastName', { firstName: "desc" }]);
table.get('sortBy'); // ['lastName', { firstName: "desc" }]
table.get('sortBy.state'); // [{ key: "lastName", dir: 1 }, { key: "firstName", dir: -1 }]
Parameters:
-
val
String | String | Object | ObjectThe current sortBy value
-
detail
StringString passed to
get(HERE)
. to parse subattributes
_initColumns
()
protected
Initializes the _columnMap
property from the configured columns
attribute. If columns
is not set, but recordType
is, it uses the
ATTRS
of that class. If neither are set, it temporarily falls back to an
empty array. _initRecordType
will call back into this method if it finds
the columnMap
empty.
_initData
()
protected
Initializes the instance's data
property from the value of the data
attribute. If the attribute value is a ModelList, it is assigned directly
to this.data
. If it is an array, a ModelList is created, its model
property is set to the configured recordType
class, and it is seeded with
the array data. This ModelList is then assigned to this.data
.
_initEvents
()
protected
Publishes core events.
_initMessageNode
()
protected
Creates the _messageNode
property from the configured MESSAGE_TEMPLATE
and inserts it before the <table>
's <tbody>
node.
_initMessageStrings
()
protected
Add the messaging related strings to the strings
map.
_initRecordType
()
protected
If the recordType
attribute is not set, this method attempts to set a
default value.
It tries the following methods to determine a default:
- If the
data
attribute is set with a ModelList with amodel
property, that class is used. - If the
data
attribute is set with a non-empty ModelList, theconstructor
of the first item is used. - If the
data
attribute is set with a non-empty array and the first item is a Base subclass, its constructor is used. - If the
data
attribute is set with a non-empty array a custom Model subclass is generated using the keys of the first item as itsATTRS
. - If the
_columnMap
property has keys, a custom Model subclass is generated using those keys as itsATTRS
.
Of none of those are successful, it subscribes to the change events for
columns
, recordType
, and data
to try again.
If defaulting the recordType
and the current _columnMap
property is
empty, it will call _initColumns
.
_initSortFn
()
protected
Creates a _compare
function for the data
ModelList to allow custom
sorting by multiple fields.
_initSortStrings
()
protected
Add the sort related strings to the strings
map.
_initViewConfig
()
protected
Initializes the _viewConfig
, _headerConfig
, _bodyConfig
, and
_footerConfig
properties with the configuration objects that will be
passed to the constructors of the headerView
, bodyView
, and
footerView
.
Extensions can add to the config objects to deliver custom parameters at
view instantiation. _viewConfig
is used as the prototype of the other
three config objects, so properties added here will be inherited by all
configs.
_mergeXScrollContent
()
protected
Merges the caption and content tables back into one table if they are split.
_mergeYScrollContent
()
protected
Merges the header and data tables back into one table if they are split.
_onUITriggerSort
-
e
Fires the sort
event in response to user clicks on sortable column
headers.
Parameters:
-
e
DOMEventFacadeThe
click
event
_parseColumns
-
columns
Iterates the array of column configurations to capture all columns with a
key
property. Columns that are represented as strings will be replaced
with objects with the string assigned as the key
property. If a column
has a children
property, it will be iterated, adding any nested column
keys to the returned map. There is no limit to the levels of nesting.
All columns are assigned a _yuid
stamp and _id
property corresponding
to the column's configured name
or key
property with any spaces
replaced with dashes. If the same name
or key
appears in multiple
columns, subsequent appearances will have their _id
appended with an
incrementing number (e.g. if column "foo" is included in the columns
attribute twice, the first will get _id
of "foo", and the second an _id
of "foo1").
The result is an object map with column keys as the property name and the corresponding column object as the associated value.
Parameters:
-
columns
Object | StringThe array of column names or configuration objects to scan
_parseSortable
()
protected
Normalizes the possible input values for the sortable
attribute, storing
the results in the _sortable
property.
_removeHeaderScrollPadding
()
protected
Removes the additional padding added to the last cells in each header row to allow the scrollbar to fit below.
_renderSortable
()
protected
Initial application of the sortable UI.
_setColumnMap
-
columns
Assigns the _columnMap
property with the parsed results of the array of
column definitions passed.
Parameters:
-
columns
Object | Stringthe raw column configuration objects or key names
_setColumnset
-
val
Relays attribute assignments of the deprecated columnset
attribute to the
columns
attribute. If a Columnset is object is passed, its basic object
structure is mined.
Parameters:
-
val
Array | ColumnsetThe columnset value to relay
_setColumnWidth
-
colIndex
-
width
Sets a columns's <col>
element width style. This is needed to get around
browser rendering differences.
The colIndex corresponds to the item index of the <col>
in the table's
<colgroup>
.
To unset the width, pass a falsy value for the width
.
Parameters:
-
colIndex
NumberThe display column index
-
width
Number | StringThe desired width
_setData
()
protected
Accepts an object with each
and getAttrs
(preferably a ModelList or
subclass) or an array of data objects. If an array is passes, it will
create a ModelList to wrap the data. In doing so, it will set the created
ModelList's model
property to the class in the recordType
attribute,
which will be defaulted if not yet set.
If the data
property is already set with a ModelList, passing an array as
the value will call the ModelList's reset()
method with that array rather
than replacing the stored ModelList wholesale.
Any non-ModelList-ish and non-array value is invalid.
_setDisplayColumns
-
columns
Stores an array of columns intended for display in the _displayColumns
property. This method assumes that if a column configuration object does
not have children, it is a display column.
Parameters:
-
columns
ObjectColumn config array to extract display columns from
_setHeaderScrollPadding
()
protected
Adds additional padding to the current amount of right padding on each row's last cell to account for the width of the scrollbar below.
_setRecordset
-
val
Relays the value assigned to the deprecated recordset
attribute to the
data
attribute. If a Recordset instance is passed, the raw object data
will be culled from it.
Parameters:
-
val
Object | RecordsetThe recordset value to relay
_setRecordType
-
val
Accepts a Base subclass (preferably a Model subclass). Alternately, it will
generate a custom Model subclass from an array of attribute names or an
object defining attributes and their respective configurations (it is
assigned as the ATTRS
of the new class).
Any other value is invalid.
Parameters:
-
val
Function | String | ObjectThe Model subclass, array of attribute names, or the
ATTRS
definition for a custom model subclass
Returns:
_setScrollable
-
val
Accepts (case insensitive) values "x", "y", "xy", true
, and false
.
true
is translated to "xy" and upper case values are converted to lower
case. All other values are invalid.
Parameters:
-
val
String | BooleaIncoming value for the
scrollable
attribute
Returns:
_setScrollProperties
()
protected
Assigns the _xScroll
and _yScroll
properties to true if an
appropriate value is set in the scrollable
attribute and the height
and/or width
is set.
_setSortBy
()
protected
Parses the current sortBy
attribute into a normalized structure for the
data
ModelList's _compare
method. Also updates the column
configurations' sortDir
properties.
_setYScrollColWidths
()
protected
Clones the fixed (see _fixColumnWidths
method) <colgroup>
for use by the
table in the vertical scrolling container. The last column's width is reduced
by the width of the scrollbar (which is offset by additional padding on the
last header cell(s) in the header table - see _setHeaderScrollPadding
).
_sortComparator
-
item
Replacement comparator
for the data
ModelList that defers sorting logic
to the _compare
method. The deferral is accomplished by returning this
.
Parameters:
-
item
ModelThe record being evaluated for sort position
Returns:
_splitXScrollContent
()
protected
Splits the data table from its caption if it has one and wraps the table in
a horizontally scrollable container <div>
.
_splitYScrollContent
()
protected
Splits the unified table with headers and data into two tables, the latter
contained within a vertically scrollable container <div>
.
_syncMessageUI
()
protected
Synchronizes the message UI with the table state.
_syncScrollUI
()
protected
Splits or merges the table for X and Y scrolling depending on the current widget state. If the table needs to be split, but is already, does nothing.
_syncVirtualScroll
-
e
-
details
Keeps the _yScrollNode
scroll position in sync with the _scrollbarNode
in an "xy" scroll configuration.
Parameters:
-
e
DOMEventFacadeThe scroll event
-
details
Objectsubscription details, including which of the two scrolling elements is being scrolled
_uiSetCaption
-
htmlContent
Creates, removes, or updates the table's <caption>
element per the input
value. Empty values result in the caption being removed.
Parameters:
-
htmlContent
HTMLThe content to populate the table caption
_uiSetColumns
()
protected
Populates the table's <colgroup>
with a <col>
per item in the columns
attribute without children. It is assumed that these are the columns that
have data cells renderered for them.
_uiSetMessage
-
e
Calls hideMessage
or showMessage
as appropriate based on the presence of
records in the data
ModelList.
This is called when data
is reset or records are added or removed. Also,
if the showMessages
attribute is updated. In either case, if the
triggering event has a message
property on the EventFacade, it will be
passed to showMessage
(if appropriate). If no such property is on the
facade, the emptyMessage
will be used (see the strings).
Parameters:
-
e
EventFacadeThe columnsChange event
_uiSetScrollable
()
protected
Assigns the appropriate class to the boundingBox
to identify the DataTable
as horizontally scrolling, vertically scrolling, or both (adds both classes).
Classes added are "yui3-datatable-scrollable-x" or "...-y"
_uiSetSortable
()
protected
Applies the appropriate classes to the boundingBox
and column headers to
indicate sort state and sortability.
Also currently wraps the header content of sortable columns in a <div>
liner to give a CSS anchor for sort indicators.
_uiSetSummary
()
protected
Updates the table's summary
attribute with the input value.
_uiSetWidth
-
width
Overrides the default Widget _uiSetWidth
to assign the width to either
the table or the contentBox
(for horizontal scrolling) in addition to the
native behavior of setting the width of the boundingBox
.
Parameters:
-
width
String | NumberCSS width value or number of pixels
_validateSortable
-
val
Allows values true
, false
, "auto", or arrays of column names through.
Parameters:
-
val
AnyThe input value to
set("sortable", VAL)
Returns:
_validateSortBy
-
val
Allows strings, arrays of strings, objects, or arrays of objects.
Parameters:
-
val
String | String | Object | ObjectThe new
sortBy
value
Returns:
_validateView
()
protected
Verifies the input value is a function with a render
method on its
prototype. null
is also accepted to remove the default View.
addColumn
-
config
-
[index]
Adds the column configuration to the DataTable's columns
configuration.
If the index
parameter is supplied, it is injected at that index. If the
table has nested headers, inject a subcolumn by passing an array of indexes
to identify the new column's final location.
The index
parameter is required if adding a nested column.
This method is a convienience method for fetching the DataTable's columns
attribute, updating it, and calling
table.set('columns', _updatedColumnsDefs_)
For example:
// Becomes last column
table.addColumn('name');
// Inserted after the current second column, moving the current third column
// to index 4
table.addColumn({ key: 'price', formatter: currencyFormatter }, 2 );
// Insert a new column in a set of headers three rows deep. The index array
// translates to
// [ 2, -- in the third column's children
// 1, -- in the second child's children
// 3 ] -- as the fourth child column
table.addColumn({ key: 'age', sortable: true }, [ 2, 1, 3 ]);
Parameters:
-
config
Object | StringThe new column configuration object
-
[index]
Number | Number optionalthe insertion index
Returns:
addRow
-
data
-
[config]
-
[callback]
Adds a new record to the DataTable's data
ModelList. Record data can be
an object of field values or an instance of the DataTable's configured
recordType
class.
This relays all parameters to the data
ModelList's add
method.
If a configuration object is passed as a second argument, and that object
has sync: true
set, the underlying Model will be save()
d.
If the DataTable's autoSync
attribute is set to true
, the additional
argument is not needed.
If syncing and the last argument is a function, that function will be used
as a callback to the Model's save()
method.
Parameters:
-
data
ObjectThe data or Model instance for the new record
-
[config]
Object optionalConfiguration to pass along
-
[callback]
Function optionalCallback function for Model's
save()
-
err
Error | nullIf an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, err will be
null
. -
response
AnyThe server's response. This value will be passed to the
parse()
method, which is expected to parse it and return an attribute hash.
-
Returns:
addRows
-
data
-
[config]
-
[callback]
Adds an array of new records to the DataTable's data
ModelList. Record data
can be an array of objects containing field values or an array of instance of
the DataTable's configured recordType
class.
This relays all parameters to the data
ModelList's add
method.
Technically, this is an alias to addRow
, but please use the appropriately
named method for readability.
If a configuration object is passed as a second argument, and that object
has sync: true
set, the underlying Models will be save()
d.
If the DataTable's autoSync
attribute is set to true
, the additional
argument is not needed.
If syncing and the last argument is a function, that function will be used
as a callback to each Model's save()
method.
Parameters:
-
data
ObjectThe data or Model instances to add
-
[config]
Object optionalConfiguration to pass along
-
[callback]
Function optionalCallback function for each Model's
save()
-
err
Error | nullIf an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, err will be
null
. -
response
AnyThe server's response. This value will be passed to the
parse()
method, which is expected to parse it and return an attribute hash.
-
Returns:
bindUI
()
protected
Subscribes to attribute change events to update the UI.
delegate
-
type
-
fn
-
spec
-
context
-
args
Pass through to delegate()
called from the contentBox
.
Parameters:
-
type
Stringthe event type to delegate
-
fn
Functionthe callback function to execute. This function will be provided the event object for the delegated event.
-
spec
String | Functiona selector that must match the target of the event or a function to test target and its parents for a match
-
context
Objectoptional argument that specifies what 'this' refers to
-
args
Any multiple0..n additional arguments to pass on to the callback function. These arguments will be added after the event object.
Returns:
destructor
()
protected
Removes the click subscription from the header for sorting.
getCell
-
row
-
col
Returns the Node for a cell at the given coordinates.
Technically, this only relays to the bodyView
instance's getCell
method.
If the bodyView
doesn't have a getCell
method, undefined
is returned.
Parameters:
-
row
NumberIndex of the cell's containing row
-
col
NumberIndex of the cell's containing column
Returns:
getColumn
-
name
Gets the column configuration object for the given key, name, or index. For
nested columns, name
can be an array of indexes, each identifying the index
of that column in the respective parent's "children" array.
If you pass a column object, it will be returned.
For columns with keys, you can also fetch the column with
instance.get('columns.foo')
.
Parameters:
-
name
String | Number | NumberKey, "name", index, or index array to identify the column
Returns:
getRow
-
index
Returns the Node for a row at the given index.
Technically, this only relays to the bodyView
instance's getRow
method.
If the bodyView
doesn't have a getRow
method, undefined
is returned.
Parameters:
-
index
NumberIndex of the row in the data
<tbody>
Returns:
initializer
-
config
Sets up event handlers and AOP advice methods to bind the DataTable's natural behaviors with the scrolling APIs and state.
Parameters:
-
config
ObjectThe config object passed to the constructor (ignored)
initializer
()
protected
Hooks up to the rendering lifecycle to also render the <colgroup>
and
subscribe to columnChange
events.
initializer
()
protected
Merges in the message related strings and hooks into the rendering cycle to also render and bind the message node.
initializer
()
protected
Sets up the initial sort state and instance properties. Publishes events and subscribes to attribute change events to maintain internal state.
initializer
()
protected
Publishes the events used by the mutation methods:
- addColumn
- removeColumn
- modifyColumn
- moveColumn
modifyColumn
-
name
-
config
Updates an existing column definition. Fires the modifyColumn
event.
For example:
// Add a formatter to the existing 'price' column definition
table.modifyColumn('price', { formatter: currencyFormatter });
// Change the label on a header cell in a set of nested headers three rows
// deep. The index array translates to
// [ 2, -- in the third column's children
// 1, -- the second child
// 3 ] -- the fourth child column
table.modifyColumn([2, 1, 3], { label: 'Experience' });
Parameters:
-
name
String | Number | Number | ObjectThe column key, name, index, or current configuration object
-
config
ObjectThe new column configuration properties
Returns:
modifyRow
-
id
-
data
-
[config]
-
[callback]
Updates an existing record in the DataTable's data
ModelList. The record
can be provided explicitly or targeted by it's id
(see ModelList's
getById
method), clientId
, or index in the ModelList.
After locating the target Model, this relays the all other passed
arguments to the Model's setAttrs
method.
If a configuration object is passed as a second argument, and that object
has sync: true
set, the underlying Model will be save()
d.
If the DataTable's autoSync
attribute is set to true
, the additional
argument is not needed.
If syncing and the last argument is a function, that function will be used
as a callback to the Model's save()
method.
Parameters:
-
id
Object | String | NumberThe Model instance or identifier
-
data
ObjectNew data values for the Model
-
[config]
Object optionalConfiguration to pass along to
setAttrs()
-
[callback]
Function optionalCallback function for Model's
save()
-
err
Error | nullIf an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, err will be
null
. -
response
AnyThe server's response. This value will be passed to the
parse()
method, which is expected to parse it and return an attribute hash.
-
Returns:
moveColumn
-
name
-
index
Moves an existing column to a new location. Fires the moveColumn
event.
The destination index can be a number or array of numbers to place a column header in a nested header row.
Parameters:
-
name
String | Number | Number | ObjectThe column key, name, index, or current configuration object
-
index
Number | NumberThe destination index of the column
Returns:
removeColumn
-
name
Removes an existing column. Fires the removeColumn
event.
Parameters:
-
name
String | Number | Number | ObjectThe column key, name, index, or current configuration object
Returns:
removeRow
-
id
-
[config]
-
[callback]
Removes a record from the DataTable's data
ModelList. The record can be
provided explicitly or targeted by it's id
(see ModelList's getById
method), clientId
, or index in the ModelList.
After locating the target Model, this relays the Model and all other passed
arguments to the data
ModelList's remove
method.
If a configuration object is passed as a second argument, and that object
has sync: true
set, the underlying Model will be destroyed, passing
{ delete: true }
to trigger calling the Model's sync layer.
If the DataTable's autoSync
attribute is set to true
, the additional
argument is not needed.
If syncing and the last argument is a function, that function will be used
as a callback to the Model's destroy()
method.
Parameters:
-
id
Object | String | NumberThe Model instance or identifier
-
[config]
Object optionalConfiguration to pass along
-
[callback]
Function optionalCallback function for Model's
save()
-
err
Error | nullIf an error occurred or validation failed, this parameter will contain the error. If the sync operation succeeded, err will be
null
. -
response
AnyThe server's response. This value will be passed to the
parse()
method, which is expected to parse it and return an attribute hash.
-
Returns:
renderUI
()
protected
Builds the table and attaches it to the DOM. This requires the host class
to provide a contentBox
attribute. This is typically provided by Widget.
scrollTo
-
id
Scrolls a given row or cell into view if the table is scrolling. Pass the
clientId
of a Model from the DataTable's data
ModelList or its row
index to scroll to a row or a [row index, column index] array to scroll to
a cell. Alternately, to scroll to any element contained within the table's
scrolling areas, pass its ID, or the Node itself (though you could just as
well call node.scrollIntoView()
yourself, but hey, whatever).
Parameters:
-
id
String | Number | Number | NodeA row clientId, row index, cell coordinate array, id string, or Node
Returns:
setColumnWidth
-
id
-
width
Assigns the style width of the <col>
representing the column identifed by
id
and updates the column configuration.
Pass the empty string for width
to return a column to auto sizing.
This does not trigger a columnsChange
event today, but I can be convinced
that it should.
Parameters:
-
id
Number | String | ObjectThe column config object or key, name, or index of a column in the host's
_displayColumns
array. -
width
Number | StringCSS width value. Numbers are treated as pixels
Returns:
showMessage
-
message
Display the message node and set its content to message
. If there is a
localized strings
entry for the value of message
, that string will be
used.
Parameters:
-
message
StringThe message name or message itself to display
Returns:
sort
-
fields
-
[payload]
Sort the data in the data
ModelList and refresh the table with the new
order.
Acceptable values for fields
are key
strings or objects with a single
property, the column key
, with a value of 1, -1, "asc", or "desc". E.g.
{ username: 'asc' }
. String values are assumed to be ascending.
Example values would be:
"username"
- sort by the data'susername
field or thekey
associated to a column with thatname
.{ username: "desc" }
- sort byusername
in descending order. Alternately, use values "asc", 1 (same as "asc"), or -1 (same as "desc").["lastName", "firstName"]
- ascending sort bylastName
, but for records with the samelastName
, ascending subsort byfirstName
. Array can have as many items as you want.[{ lastName: -1 }, "firstName"]
- descending sort bylastName
, ascending subsort byfirstName
. Mixed types are ok.
Parameters:
-
fields
String | String | Object | ObjectThe field(s) to sort by
-
[payload]
Object optionalExtra
sort
event payload you want to send along
Returns:
syncUI
()
Updates the UI with the current attribute state.
toggleSort
-
fields
-
[payload]
Reverse the current sort direction of one or more fields currently being sorted by.
Pass the key
of the column or columns you want the sort order reversed
for.
Parameters:
-
fields
String | StringThe field(s) to reverse sort order for
-
[payload]
Object optionalExtra
sort
event payload you want to send along
Returns:
Properties
_bodyConfig
Object
protected
Configuration object passed to the class constructor in bodyView
during
render.
This property is set by the _initViewConfig
method at instantiation.
Default: undefined (initially unset)
_CAPTION_TABLE_TEMPLATE
HTML
protected
Template for the <table>
that is used to fix the caption in place when
the table is horizontally scrolling.
_columnMap
Object
protected
A map of column key to column configuration objects parsed from the
columns
attribute.
Default: undefined (initially unset)
_displayColumns
Object
protected
Contains column configuration objects for those columns believed to be intended for display in the <tbody>
. Populated by _setDisplayColumns
.
_headerConfig
Object
protected
Configuration object passed to the class constructor in headerView
during
render.
This property is set by the _initViewConfig
method at instantiation.
Default: undefined (initially unset)
_messageNode
Node
Node used to display messages from showMessage
.
_SCROLLBAR_TEMPLATE
HTML
protected
Template for the virtual scrollbar needed in "xy" scrolling setups.
_sortable
Object
protected
Array of column configuration objects of those columns that need UI setup for user interaction.
_sortBy
Object
protected
Array of column configuration objects for those columns that are currently being used to sort the data. Fake column objects are used for fields that are not rendered as columns.
_tableNode
Node
protected
The Node instance of the table containing the data rows. This is set when the table is rendered. It may also be set by progressive enhancement, though this extension does not provide the logic to parse from source.
Default: undefined (initially unset)
_viewConfig
Object
protected
Configuration object used as the prototype of _headerConfig
,
_bodyConfig
, and _footerConfig
. Add properties to this object if you
want them in all three of the other config objects.
This property is set by the _initViewConfig
method at instantiation.
Default: undefined (initially unset)
_X_SCROLLER_TEMPLATE
HTML
protected
Template for the <div>
that is used to contain the table when the table is
horizontally scrolling.
_xScroll
Boolean
private
Indicates horizontal table scrolling is enabled.
Default: undefined (not initially set)
_xScrollNode
Node
protected
Overflow Node used to contain the table headers and data in a horizontally scrolling table.
Default: undefined (not initially set)
_Y_SCROLLER_TEMPLATE
HTML
protected
Template for the <div>
that is used to contain the rows when the table is
vertically scrolling.
_yScroll
Boolean
private
Indicates vertical table scrolling is enabled.
Default: undefined (not initially set)
_yScrollNode
Node
protected
Overflow Node used to contain the data rows in a vertically scrolling table.
Default: undefined (not initially set)
body
Object
The object or instance of the class assigned to bodyView
that is
responsible for rendering and managing the table's <tbody>
(s) and its
content.
Default: undefined (initially unset)
CAPTION_TEMPLATE
HTML
The HTML template used to create the caption Node if the caption
attribute is set.
Default: '<caption class="{className}"/>'
COL_TEMPLATE
HTML
The HTML template used to create the table's <col>
s.
Default: '<col/>'
COLGROUP_TEMPLATE
HTML
The HTML template used to create the table's <colgroup>
.
Default: '<colgroup/>'
data
ModelList
The ModelList that manages the table's data.
Default: undefined (initially unset)
foot
Object
The object or instance of the class assigned to footerView
that is
responsible for rendering and managing the table's <tfoot>
and its
content.
Default: undefined (initially unset)
head
Object
The object or instance of the class assigned to headerView
that is
responsible for rendering and managing the table's <thead>
and its
content.
Default: undefined (initially unset)
MESSAGE_TEMPLATE
HTML
Template used to generate the node that will be used to report messages.
Default: <tbody class="{className}"><td class="{contentClass}" colspan="{colspan}"></td></tbody>
SORTABLE_HEADER_TEMPLATE
HTML
Template for the node that will wrap the header content for sortable columns.
TABLE_TEMPLATE
HTML
The HTML template used to create the table Node.
Default: '<table class="{className}"/>'
TBODY_TEMPLATE
HTML
HTML template used to create table's <tbody>
if configured with a
bodyView
.
Default: '<tbody class="{className}"/>'
TFOOT_TEMPLATE
HTML
Template used to create the table's <tfoot>
if configured with a
footerView
.
Default: '<tfoot class="{className}"/>'
THEAD_TEMPLATE
HTML
Template used to create the table's <thead>
if configured with a
headerView
.
Default: '<thead class="{className}"/>'
Attributes
autoSync
Boolean
Controls whether addRow
, removeRow
, and modifyRow
should trigger the
underlying Model's sync layer by default.
When true
, it is unnecessary to pass the "sync" configuration property to
those methods to trigger per-operation sync.
Default: false
bodyView
Function | Object
The class or object to use for rendering the <tbody>
or <tbody>
s and
all data row content for the table. This attribute is responsible for
populating the the instance's body
property.
If a class constructor (function) is passed, an instance of that clas will
be created at render()
time and assigned to this.body
. If an object is
passed, body
will be set immediately.
Valid objects or classes will have a render()
method, though it is
recommended that they be subclasses of Y.Base
or Y.View
. If the object
or class supports events, its addTarget()
method will be called to bubble
its events to this instance.
The core implementaion does not define a default bodyView
. Classes
built from this extension should define a default.
columns
Object | String
Columns to include in the rendered table.
If omitted, the attributes on the configured recordType
or the first item
in the data
collection will be used as a source.
This attribute takes an array of strings or objects (mixing the two is
fine). Each string or object is considered a column to be rendered.
Strings are converted to objects, so columns: ['first', 'last']
becomes
columns: [{ key: 'first' }, { key: 'last' }]
.
DataTable.Core only concerns itself with the key
property of columns.
All other properties are for use by the headerView
, bodyView
,
footerView
, and any class extensions or plugins on the final class or
instance. See the descriptions of the view classes and feature class
extensions and plugins for details on the specific properties they read or
add to column definitions.
Default: (from recordType
ATTRS or first item in the data
)
columnset
Object | Columnset
deprecated
Deprecated as of 3.5.0. Passes through to the columns
attribute.
If a Columnset object is passed, its raw object and array column data will be extracted for use.
WARNING: get('columnset')
will NOT return a Columnset instance as of
3.5.0. This is a break in backward compatibility.
data
ModelList | Object
The collection of data records to display. This attribute is a pass
through to a data
property, which is a ModelList instance.
If this attribute is passed a ModelList or subclass, it will be assigned to
the property directly. If an array of objects is passed, a new ModelList
will be created using the configured recordType
as its model
property
and seeded with the array.
Retrieving this attribute will return the ModelList stored in the data
property.
Default: new ModelList()
headerView
Function | Object
The class or object to use for rendering the <thead>
and column headers
for the table. This attribute is responsible for populating the the
instance's head
property.
If a class constructor (function) is passed, an instance of that clas will
be created at render()
time and assigned to this.head
. If an object is
passed, head
will be set immediately.
Valid objects or classes will have a render()
method, though it is
recommended that they be subclasses of Y.Base
or Y.View
. If the object
or class supports events, its addTarget()
method will be called to bubble
its events to this instance.
The core implementaion does not define a default headerView
. Classes
built from this extension should define a default.
recordset
Object | Recordset
deprecated
Deprecated as of 3.5.0. Passes through to the data
attribute.
WARNING: get('recordset')
will NOT return a Recordset instance as of
3.5.0. This is a break in backward compatibility.
recordType
Function
Model subclass to use as the model
for the ModelList stored in the data
attribute.
If not provided, it will try really hard to figure out what to use. The following attempts will be made to set a default value:
- If the
data
attribute is set with a ModelList instance and itsmodel
property is set, that will be used. - If the
data
attribute is set with a ModelList instance, and itsmodel
property is unset, but it is populated, theATTRS
of the `constructor of the first item will be used. - If the
data
attribute is set with a non-empty array, a Model subclass will be generated using the keys of the first item as itsATTRS
(see the_createRecordClass
method). - If the
columns
attribute is set, a Model subclass will be generated using the columns defined with akey
. This is least desirable because columns can be duplicated or nested in a way that's not parsable. - If neither
data
norcolumns
is set or populated, a change event subscriber will listen for the first to be changed and try all over again.
Default: (see description)
scrollable
String | Boolean
Activates or deactivates scrolling in the table. Acceptable values are:
false
- (default) Scrolling is disabled.true
or 'xy' - Ifheight
is set, vertical scrolling will be activated, ifwidth
is set, horizontal scrolling will be activated.- 'x' - Activate horizontal scrolling only. Requires the
width
attribute is also set. - 'y' - Activate vertical scrolling only. Requires the
height
attribute is also set.
showMessages
Boolean
Enables the display of messages in the table. Setting this to false will
prevent the message Node from being created and showMessage
from doing
anything.
Default: true
sortable
String | String | Boolean
Controls which column headers can trigger sorting by user clicks.
Acceptable values are:
- "auto" - (default) looks for
sortable: true
in the column configurations true
- all columns are enabled- `false - no UI sortable is enabled
- {String[]} - array of key names to give sortable headers
Default: "auto"
sortBy
String | String | Object | Object
The current sort configuration to maintain in the data.
Accepts column key
strings or objects with a single property, the column
key
, with a value of 1, -1, "asc", or "desc". E.g. { username: 'asc'
}
. String values are assumed to be ascending.
Example values would be:
"username"
- sort by the data'susername
field or thekey
associated to a column with thatname
.{ username: "desc" }
- sort byusername
in descending order. Alternately, use values "asc", 1 (same as "asc"), or -1 (same as "desc").["lastName", "firstName"]
- ascending sort bylastName
, but for records with the samelastName
, ascending subsort byfirstName
. Array can have as many items as you want.[{ lastName: -1 }, "firstName"]
- descending sort bylastName
, ascending subsort byfirstName
. Mixed types are ok.
Events
addColumn
Fired by the addColumn
method.
Event Payload:
-
column
ObjectThe new column definition object
-
index
Number | NumberThe array index to insert the new column
modifyColumn
Fired by the modifyColumn
method.
Event Payload:
-
column
Object | String | Number | NumberThe column definition object or identifier
-
newColumnDef
ObjectThe properties to assign to the column
moveColumn
Fired by the moveColumn
method.
Event Payload:
-
column
Object | String | Number | NumberThe column definition object or identifier
-
index
ObjectThe destination index to move to
removeColumn
Fired by the removeColumn
method.
Event Payload:
-
column
Object | String | Number | NumberThe column definition object or identifier