Component: ojListView

Oracle® JavaScript Extension Toolkit (JET)
3.2.0

E87541-01

QuickNav

Options


Binding Attributes
Context Objects
Sub-ID's

oj. ojListView extends oj.baseComponent

Version:
  • 3.2.0
Since:
  • 1.1.0

JET ListView Component

Description: The JET ListView enhances a HTML list element into a themable, WAI-ARIA compliant, mobile friendly component with advance interactive features.

Data

The JET ListView gets its data in three different ways. The first way is from a TableDataSource. There are several types of TableDataSource that are available out of the box:

  • oj.ArrayTableDataSource
  • oj.CollectionTableDataSource
  • oj.PagingTableDataSource

oj.ArrayTableDataSource - Use this when the underlying data is an array object or an observableArray. In the observableArray case, ListView will automatically react when items are added or removed from the array. See the documentation for oj.ArrayTableDataSource for more details on the available options.

oj.CollectionTableDataSource - Use this when oj.Collection is the model for the underlying data. Note that the ListView will automatically react to model event from the underlying oj.Collection. See the documentation for oj.CollectionTableDataSource for more details on the available options.

oj.PagingTableDataSource - Use this when the ListView is driven by an associating ojPagingControl. See the documentation for oj.PagingTableDataSource for more details on the available options.

The second way is from a TreeDataSource. This is typically used to display data that are logically categorized in groups. There are several types of TreeDataSource that are available out of the box:

  • oj.JsonTreeDataSource
  • oj.CollectionTreeDataSource

oj.JsonTreeDataSource - Use this when the underlying data is a JSON object. See the documentation for oj.JsonTreeDataSource for more details on the available options.

oj.CollectionTreeDataSource - Use this when oj.Collection is the model for each group of data. See the documentation for oj.CollectionTableDataSource for more details on the available options.

Finally, ListView also supports static HTML content as data. The structure of the content can be either flat or hierarhical.

Example of flat static content

<ul id="listView" data-bind="ojComponent: {component: 'ojListView'}">
  <li><a id="item1" href="#">Item 1</a></li>
  <li><a id="item2" href="#">Item 2</a></li>
  <li><a id="item3" href="#">Item 3</a></li>
</ul>

Example of hierarchical static content

<ul id="listView" data-bind="ojComponent: {component: 'ojListView'}">
  <li><a id="group1" href="#">Group 1</a>
    <ul>
      <li><a id="item1-1" href="#">Item 1-1</a></li>
      <li><a id="item1-2" href="#">Item 1-2</a></li>
    </ul>
  </li>
  <li><a id="group2" href="#">Group 2</a>
    <ul>
      <li><a id="item2-1" href="#">Item 2-1</a></li>
      <li><a id="item2-2" href="#">Item 2-2</a></li>
    </ul>
  </li>
</ul>

Touch End User Information

Target Gesture Action
List Item Tap Focus on the item. If selectionMode is enabled, selects the item as well.
Press & Hold Display context menu
Group Item Tap Expand or collapse the group item if drillMode is set to collapsible.
Press & Hold Display context menu

Keyboard End User Information

Target Key Action
List Item F2 Enters Actionable mode. This enables keyboard action on elements inside the item, including navigate between focusable elements inside the item.
Esc Exits Actionable mode.
Tab When in Actionable Mode, navigates to next focusable element within the item. If the last focusable element is reached, shift focus back to the first focusable element. When not in Actionable Mode, navigates to next focusable element on page (outside ListView).
Shift+Tab When in Actionable Mode, navigates to previous focusable element within the item. If the first focusable element is reached, shift focus back to the last focusable element. When not in Actionable Mode, navigates to previous focusable element on page (outside ListView).
DownArrow Move focus to the item below.
UpArrow Move focus to the item above.
LeftArrow When display in card layout, move focus to the item on the left.
RightArrow When display in card layout, move focus to the item on the right.
Shift+DownArrow Extend the selection to the item below.
Shift+UpArrow Extend the selection to the item above.
Shift+LeftArrow When display in card layout, extend the selection to the item on the left.
Shift+RightArrow When display in card layout, extend the selection to the item on the right.
Shift+F10 Launch the context menu if there is one associated with the current item.
Enter Selects the current item. No op if the item is already selected.
Space Toggles to select and deselect the current item. If previous items have been selected, deselects them and selects the current item.
Shift+Space Selects contiguous items from the last selected item to the current item.
Ctrl+Space Toggles to select and deselect the current item while maintaining previous selected items.
Ctrl+X Marks the selected items to move if dnd.reorder is enabled.
Ctrl+C Marks the selected items to copy if dnd.reorder is enabled.
Ctrl+V Paste the items that are marked to directly before the current item (or as the last item if the current item is a folder).
Group Item LeftArrow Collapse the current item if it is expanded and is collapsible. For non-hierarchical data, do nothing.
RightArrow Expand the current item if it has children and is expandable. For non-hierarchical data, do nothing.

Item Context

For all item options, developers can specify a function as the return value. The function takes a single argument, which is an object that contains contextual information about the particular item. This gives developers the flexibility to return different value depending on the context.

The context paramter contains the following keys:

Key Description
component A reference to the ListView widget constructor.
datasource A reference to the data source object. (Not available for static content)
index The index of the item, where 0 is the index of the first item. In the hierarchical case the index is relative to its parent.
key The key of the item.
data The data object for the item.
parentElement The list item element. The renderer can use this to directly append content.

If the data is hierarchical, the following additional contextual information are available:

Key Description
depth The depth of the item. The depth of the first level children under the invisible root is 1.
parentKey The key of the parent item. The parent key is null for root node.
leaf Whether the item is a leaf or a group item.

Accessibility

Application must ensure that the context menu is available and setup with the appropriate clipboard menu items so that keyboard-only users are able to reorder items just by using the keyboard.

Performance

Data Set Size

As a rule of thumb, it's recommended that applications limit the amount of data to display. Displaying large number of items in ListView makes it hard for user to find what they are looking for, but affects the load time and scrolling performance as well. If displaying large number of items is neccessary, use a paging control with ListView to limit the number of items to display at a time. Setting scrollPolicy to 'loadMoreOnScroll' will also reduce the number of items to display initially.

Item Content

ListView allows developers to specify arbitrary content inside its item. In order to minimize any negative effect on performance, you should avoid putting a large number of heavy-weight components inside because as you add more complexity to the structure, the effect will be multiplied because there can be many items in the ListView.

Expand All

While ListView provides a convenient way to initially expand all group items in the ListView, it might have an impact on the initial rendering performance since expanding each group item might cause a fetch from the server depending on the TreeDataSource. Other factors that could impact performance includes the depth of the tree, and the number of children in each level.

Animation

Applications can customize animations triggered by actions in ListView by either listening for animateStart/animateEnd events or overriding action specific style classes on the animated item. See the documentation of oj.AnimationUtils class for details.

The following are actions and their corresponding sass variables in which applications can use to customize animation effects.

Action Sass Variable Description
add $listViewAddAnimation When a new item is added to the oj.TableDataSource associated with ListView.
remove $listViewRemoveAnimation When an existing item is removed from the oj.TableDataSource associated with ListView.
update $listViewUpdateAnimation When an existing item is updated in the oj.TableDataSource associated with ListView.
expand $listViewExpandAnimation When user expands a group item.
collapse $listViewCollapseAnimation When user collapses a group item.
pointerUp $listViewPointerUpAnimation When user finish pressing an item (on touch).

Initializer

.ojListView()

Source:

Options

contextMenu :Element|Array.<Element>|string|jQuery|NodeList

Identifies the JET Menu that the component should launch as a context menu on right-click, Shift-F10, Press & Hold, or component-specific gesture. If specified, the browser's native context menu will be replaced by the specified JET Menu.

The value can be an HTML element, JQ selector, JQ object, NodeList, or array of elements. In all cases, the first indicated element is used.

To specify a JET context menu on a DOM element that is not a JET component, see the ojContextMenu binding.

To make the page semantically accurate from the outset, applications are encouraged to specify the context menu via the standard HTML5 syntax shown in the below example. When the component is initialized, the context menu thus specified will be set on the component.

There is no restriction on the order in which the JET Menu and the referencing component are initialized. However, when specifying the Menu via the HTML attribute, the referenced DOM element must be in the document at the time that the referencing component is initialized.

After create time, the contextMenu option should be set via this API, not by setting the DOM attribute.

The application can register a listener for the Menu's beforeOpen event. The listener can cancel the launch via event.preventDefault(), or it can customize the menu contents by editing the menu DOM directly, and then calling refresh() on the Menu.

To help determine whether it's appropriate to cancel the launch or customize the menu, the beforeOpen listener can use component API's to determine which table cell, chart item, etc., is the target of the context menu. See the JSDoc and demos of the individual components for details. Keep in mind that any such logic must work whether the context menu was launched via right-click, Shift-F10, Press & Hold, or component-specific touch gesture.

Default Value:
  • null
Inherited From:
Source:
Examples

Initialize a JET component with a context menu:

// via recommended HTML5 syntax:
<div id="myComponent" contextmenu="myMenu" data-bind="ojComponent: { ... }>

// via JET initializer (less preferred) :
// Foo is the component, e.g., InputText, InputNumber, Select, etc.
$( ".selector" ).ojFoo({ "contextMenu": "#myMenu" });

Get or set the contextMenu option, after initialization:

// getter
// Foo is the component, e.g., InputText, InputNumber, Select, etc.
var menu = $( ".selector" ).ojFoo( "option", "contextMenu" );

// setter
// Foo is the component, e.g., InputText, InputNumber, Select, etc.
$( ".selector" ).ojFoo( "option", "contextMenu", ".my-marker-class" );

Set a JET context menu on an ordinary HTML element:

<a href="#" id="myAnchor" contextmenu="myMenu" data-bind="ojContextMenu: {}">Some text

currentItem :Object

The current item. This is typically the item the user navigated to. Note that if current is set to an item that is currently not available (not fetched in highwater mark scrolling case or inside a collapsed parent node), then the value is ignored.
Default Value:
  • null
Source:
Examples

Get the current item:

$( ".selector" ).ojListView("option", "currentItem");

Set the current item on the ListView during initialization:

$(".selector").ojListView({"currentItem", "item2"});

data :oj.TableDataSource|oj.TreeDataSource

The data source for the ListView accepts either a oj.TableDataSource or oj.TreeDataSource. See the data source section in the introduction for out of the box data source types. If the data attribute is not specified, the child elements are used as content. If there's no content specified, then an empty list is rendered.
Default Value:
  • null
Source:
Examples

Initialize the ListView with a one-dimensional array:

$( ".selector" ).ojListView({ "data": new oj.ArrayTableDataSource([1,2,3])});

Initialize the ListView with an oj.Collection:

$( ".selector" ).ojListView({ "data": new oj.CollectionTableDataSource(collection)});

dnd

Enable drag and drop functionality.

JET provides support for HTML5 Drag and Drop events. Please refer to third party documentation on HTML5 Drag and Drop to learn how to use it.
Source:

dnd.drag :Object

Properties:
Name Type Description
items Object If this object is specified, listview will initiate drag operation when the user drags on either a drag handle, which is an element with oj-listview-drag-handle class, or selected items if no drag handle is set on the item.
Properties
Name Type Description
dataTypes string | Array.string (optional) The MIME types to use for the dragged data in the dataTransfer object. This can be a string if there is only one type, or an array of strings if multiple types are needed.

For example, if selected items of employee data are being dragged, dataTypes could be "application/employees+json". Drop targets can examine the data types and decide whether to accept the data. A text input may only accept "text" data type, while a chart for displaying employee data may be configured to accept the "application/employees+json" type.

For each type in the array, dataTransfer.setData will be called with the specified type and the JSON version of the selected item data as the value. The selected item data is an array of objects, with each object representing a model object from the underlying data source. For example, if the underlying data is an oj.Collection, then this would be a oj.Model object. Note that when static HTML is used, then the value would be the html string of the selected item.

This property is required unless the application calls setData itself in a dragStart callback function.
dragStart function (optional) A callback function that receives the "dragstart" event and context information as arguments:

function(event, ui)

Parameters:

event: The jQuery event object

ui: Context object with the following properties:
  • items: An array of objects, with each object representing the data of one selected item


This function can set its own data and drag image as needed. If dataTypes is specified, event.dataTransfer is already populated with the default data when this function is invoked. If dataTypes is not specified, this function must call event.dataTransfer.setData to set the data or else the drag operation will be cancelled. In either case, the drag image is set to an image of the dragged rows on the listview.
drag function (optional) A callback function that receives the "drag" event as argument:

function(event)

Parameters:

event: The jQuery event object
dragEnd function (optional) A callback function that receives the "dragend" event as argument:

function(event)

Parameters:

event: The jQuery event object
Default Value:
  • null
Source:
Example

Initialize the ListView such that only leaf items are focusable:

$( ".selector" ).ojListView({ "data":data, "dnd": {"drag": {"items": { "dataTypes": ["application/ojlistviewitems+json"],
                                                                       "dragEnd": handleDragEnd}}});

dnd.drop :Object

Properties:
Name Type Description
items Object An object that specifies callback functions to handle dropping items

Properties
Name Type Description
dataTypes string | Array.string A data type or an array of data types this component can accept.

This property is required unless dragEnter, dragOver, and drop callback functions are specified to handle the corresponding events.
dragEnter function (optional) A callback function that receives the "dragenter" event and context information as arguments:

function(event, ui)

Parameters:

event: The jQuery event object

ui: Context object with the following properties:
  • item: the item being entered


This function should return false to indicate the dragged data can be accepted or true otherwise. Any explict return value will be passed back to jQuery. Returning false will cause jQuery to call stopPropagation and preventDefault on the event, and calling preventDefault is required by HTML5 Drag and Drop to indicate acceptance of data.

If this function doesn't return a value, dataTypes will be matched against the drag data types to determine if the data is acceptable. If there is a match, event.preventDefault will be called to indicate that the data can be accepted.
dragOver function (optional) A callback function that receives the "dragover" event and context information as arguments:

function(event, ui)

Parameters:

event: The jQuery event object

ui: Context object with the following properties:
  • item: the item being dragged over


Similar to dragEnter, this function should return false to indicate the dragged data can be accepted or true otherwise. If this function doesn't return a value, dataTypes will be matched against the drag data types to determine if the data is acceptable.
dragLeave function (optional) A callback function that receives the "dragleave" event and context information as arguments:

function(event, ui) Parameters:

event: The jQuery event object

ui: Context object with the following properties:
  • item: the item that was last entered


drop function (required) A callback function that receives the "drop" event and context information as arguments:

function(event, ui)

Parameters:

event: The jQuery event object

ui: Context object with the following properties:
  • item: the item being dropped on
  • position: the drop position relative to the item being dropped on
  • reorder: true if the drop was a reorder in the same listview, false otherwise


This function should return false to indicate the dragged data is accepted or true otherwise.

If the application needs to look at the data for the item being dropped on, it can use the getDataForVisibleItem method.
Default Value:
  • null
Source:
Example

Initialize the ListView such that only leaf items are focusable:

$( ".selector" ).ojListView({ "data":data, "dnd": {"drop": {"items": { "dataTypes": ["application/ojlistviewitems+json"],
                                                                       "drop": handleDrop}}});

dnd.reorder :Object

The reorder option contains a subset of options for reordering items.
Source:

dnd.reorder.items :string

Enable or disable reordering the items within the same listview using drag and drop.

Specify 'enabled' to enable reordering. Setting the value 'disabled' or setting the "dnd" property to null (or omitting it), disables reordering support.
Default Value:
  • disabled
Source:
Example

Initialize the listview to enable item reorder:

$( ".selector" ).ojListView({ "data":data, "dnd" : {"reorder":{"items":"enabled"}}});

drillMode :string

Changes the expand and collapse operations on ListView. If "none" is specified, then the current expanded state is fixed and user cannot expand or collapse an item.
Supported Values:
Name Type Description
"collapsible" string group item can be expanded or collapsed by user.
"none" string the expand state of a group item cannot be changed by user.
Default Value:
  • collapsible
Source:
Example

Initialize the list view with a fixed expanded state:

$( ".selector" ).ojListView({ "drillMode": "none" });

expanded :Array.<Object>|string

Specifies which items in ListView should be expanded. Specifies "all" value to expand all items. Specifies an array of keys to expand specific items. The default value is "auto", which means that ListView will determine which items are expanded by default. Specifically, if drillMode is set to "none", then all items are expanded, any other values for drillMode will not cause any items to expand by default. Note that expanded does not return the currently expanded items. This only returns what is specified by default. To retrieve the keys of currently expanded items, use the getExpanded method.
Default Value:
  • []
Source:
Example

Initialize the list view with a fixed expanded state:

$( ".selector" ).ojListView({ "expanded": ["group1", "group2"] });

groupHeaderPosition

Specifies how the group header should be positioned. If "sticky" is specified, then the group header is fixed at the top of the ListView as the user scrolls.
Supported Values:
Name Type Description
"static" string The group header position updates as user scrolls.
"sticky" string this is the default. The group header is fixed at the top when user scrolls.
Default Value:
  • sticky
Source:

item

The item option contains a subset of options for items.
Source:

item.focusable :function(Object)|boolean

Whether the item is focusable. An item that is not focusable cannot be clicked on or navigated to. See itemContext in the introduction to see the object passed into the focusable function.
Default Value:
  • true
Source:
Example

Initialize the ListView such that only leaf items are focusable:

$( ".selector" ).ojListView({ "data":data, "item": { "focusable": function(itemContext) {
                                           return itemContext['leaf'];}}});

item.renderer :function(Object)|null

The renderer function that renders the content of the item. See itemContext in the introduction to see the object passed into the renderer function. The function returns either a String or a DOM element of the content inside the item. If the developer chooses to manipulate the list element directly, the function should return nothing. If no renderer is specified, ListView will treat the data as a String.
Default Value:
  • null
Source:
Examples

Initialize the ListView with a renderer:

$( ".selector" ).ojListView({ "data":data, "item": { "renderer": function(itemContext) {
                                           return itemContext['data'].get('FIRST_NAME');}}});

Get or set the renderer option, after initialization:

// set the renderer function
$( ".selector" ).ojListView( "option", "item.renderer", myFunction});

item.selectable :function(Object)|boolean

Whether the item is selectable. Note that if selectionMode is set to "none" this option is ignored. In addition, if focusable is set to false, then the selectable option is automatically overridden and set to false also. See itemContext in the introduction to see the object passed into the selectable function.
Default Value:
  • true
Source:
Example

Initialize the ListView such that the first 3 items are not selectable:

$( ".selector" ).ojListView({ "data":data, "item": { "selectable": function(itemContext) {
                                           return itemContext['index'] > 3;}}});

rootAttributes :Object

Attributes specified here will be set on the component's root DOM element at creation time. This is particularly useful for components like Dialog that wrap themselves in a new root element at creation time.

The supported attributes are id, which overwrites any existing value, and class and style, which are appended to the current class and style, if any.

Setting this option after component creation has no effect. At that time, the root element already exists, and can be accessed directly via the widget method, per the second example below.

Default Value:
  • null
Inherited From:
Source:
Examples

Initialize a JET component, specifying a set of attributes to be set on the component's root DOM element:

// Foo is the component, e.g., Menu, Button, InputText, InputNumber, Select, etc.
$( ".selector" ).ojFoo({ "rootAttributes": {
  "id": "myId",
  "style": "max-width:100%; color:blue;",
  "class": "my-class"
}});

After initialization, rootAttributes should not be used. It is not needed at that time, as attributes of the root DOM element can simply be set directly, using widget:

// Foo is the component, e.g., Menu, Button, InputText, InputNumber, Select, etc.
$( ".selector" ).ojFoo( "widget" ).css( "height", "100px" );
$( ".selector" ).ojFoo( "widget" ).addClass( "my-class" );

scrollPolicy :string|null

Specifies the mechanism used to scroll the data inside the list view. Possible values are: auto and loadMoreOnScroll. When loadMoreOnScroll is specified, additional data is fetched when the user scrolls to the bottom of the ListView. Note that currently this option is only available when TableDataSource is used.
Supported Values:
Name Type Description
"auto" string the behavior is determined by the component.
"loadMoreOnScroll" string additional data is fetched when the user scrolls to the bottom of the ListView.
Default Value:
  • auto
Source:
Example

Initialize the list view with a fixed expanded state:

$( ".selector" ).ojListView({ "scrollPolicy": "loadMoreOnScroll" });

scrollPolicyOptions :Object.<string, number>|null

scrollPolicy options.

The following options are supported:

  • fetchSize: Fetch size for scroll.
  • maxCount: Maximum rows which will be displayed before fetching more rows will be stopped.
  • scroller: The element which listview uses to determine the scroll position as well as the maximum scroll position where scroll to the end will trigger a fetch. If not specified then the widget element of listview is used.
When scrollPolicy is loadMoreOnScroll, the next block of rows is fetched when the user scrolls to the end of the list/scroller. The fetchSize option determines how many rows are fetched in each block. Note that currently this option is only available when TableDataSource is used.
Properties:
Name Type Description
fetchSize number the number of rows to fetch in each block of rows
maxCount number the maximum total number of rows to fetch
scroller Element | null the element which listview uses to determine the scroll position as well as the maximum scroll position. For example in a lot of mobile use cases where ListView occupies the entire screen, developers should set the scroller option to document.body
Default Value:
  • 500
Source:

scrollTop :number

The vertical scroll position of ListView.
Default Value:
  • 0
Source:
Example

Initialize the list view to a specific scroll position:

$( ".selector" ).ojListView({ "scrollTop": 100 });

selection :Array.<Object>

The current selections in the ListView. An empty array indicates nothing is selected.
Default Value:
  • []
Source:
Example

Initialize the list view with specific selection:

$( ".selector" ).ojListView({ "data":data, "selection": ["item1", "item2"] });

selectionMode :string

Specifies whether selection can be made and the cardinality of selection in the ListView. Selection is initially disabled, but setting the value to null will disable selection.
Supported Values:
Name Type Description
"none" string selection is disabled.
"single" string only one item can be selected at a time.
"multiple": string multiple items can be selected at the same time.
Default Value:
  • none
Source:
Example

Initialize the list view to enable multiple selection:

$( ".selector" ).ojListView({ "data":data, "selectionMode": "multiple" });

translations :Object

A collection of translated resources from the translation bundle, or null if this component has no resources. Resources may be accessed and overridden individually or collectively, as seen in the examples.

If this component has (or inherits) translations, their documentation immediately follows this doc entry.

Default Value:
  • an object containing all resources relevant to the component and all its superclasses, or null if none
Inherited From:
Source:
Examples

Initialize the component, overriding some translated resources. This syntax leaves the other translations intact at create time, but not if called after create time:

// Foo is InputDate, InputNumber, etc.
$( ".selector" ).ojFoo({ "translations": { someKey: "someValue",
                                           someOtherKey: "someOtherValue" } });

Get or set the translations option, after initialization:

// Get one.  (Foo is InputDate, InputNumber, etc.)
var value = $( ".selector" ).ojFoo( "option", "translations.someResourceKey" );

// Get all.  (Foo is InputDate, InputNumber, etc.)
var values = $( ".selector" ).ojFoo( "option", "translations" );

// Set one, leaving the others intact.  (Foo is InputDate, InputNumber, etc.)
$( ".selector" ).ojFoo( "option", "translations.someResourceKey", "someValue" );

// Set many.  Any existing resource keys not listed are lost.  (Foo is InputDate, InputNumber, etc.)
$( ".selector" ).ojFoo( "option", "translations", { someKey: "someValue",
                                                    someOtherKey: "someOtherValue" } );

translations.accessibleNavigateSkipItems :Object

Provides properties to customize the screen reader text when focus skips a number of items as a result of up/down arrow navigation in card layout mode.

Since:
  • 4.0.0
Source:

translations.accessibleReorderAfterItem :Object

Provides properties to customize the screen reader text when the tentative drop target is after a certain item.

Since:
  • 2.1.0
Source:

translations.accessibleReorderBeforeItem :Object

Provides properties to customize the screen reader text when the tentative drop target is before a certain item.

Since:
  • 2.1.0
Source:

translations.accessibleReorderInsideItem :Object

Provides properties to customize the screen reader text when the tentative drop target is inside a certain item.

Since:
  • 2.1.0
Source:

translations.accessibleReorderTouchInstructionText :Object

Provides properties to customize the screen reader touch instructional text for reordering items.

Since:
  • 2.1.0
Source:

translations.indexerCharacters :Object

Provides properties to customize the characters to display in the Indexer.

Since:
  • 1.2.0
Source:

translations.labelCopy :Object

Provides properties to customize the context menu copy label.

See the translations option for usage examples.

Since:
  • 2.1.0
Source:

translations.labelCut :Object

Provides properties to customize the context menu cut label.

See the translations option for usage examples.

Since:
  • 2.1.0
Source:

translations.labelPaste :Object

Provides properties to customize the context menu paste label.

See the translations option for usage examples.

Since:
  • 2.1.0
Source:

translations.labelPasteAfter :Object

Provides properties to customize the context menu paste after label.

See the translations option for usage examples.

Since:
  • 2.1.0
Source:

translations.labelPasteBefore :Object

Provides properties to customize the context menu paste before label.

See the translations option for usage examples.

Since:
  • 2.1.0
Source:

translations.msgFetchingData :Object

Provides properties to customize the message text used by ListView when waiting for data.

See the translations option for usage examples.

Since:
  • 1.1.0
Source:

translations.msgNoData :Object

Provides properties to customize the message text used by ListView when there are no items.

See the translations option for usage examples.

Since:
  • 1.1.0
Source:

Binding Attributes

Binding attributes are similar to component options, but are exposed only via the ojComponent binding.

item.template :string|null

The knockout template used to render the content of the item. This attribute is only exposed via the ojComponent binding, and is not a component option.
Default Value:
  • null
Source:
Example

Specify the template when initializing ListView:

// set the template
<ul id="listview" data-bind="ojComponent: {component: 'ojListView', data: dataSource, item: {template: 'my_template'}}"></ul>

Context Objects

Each context object contains, at minimum, a subId property, whose value is a string that identifies a particular DOM node in this component. It can have additional properties to further specify the desired node. See getContextByNode for more details.

Properties:
Name Type Description
subId string Sub-id string to identify a particular dom node.

Following are the valid subIds:

oj-listview-item

Context for the ojListView component's items.

Properties:
Name Type Description
index number the zero based item index relative to its parent
key Object the key of the item
parent Element the parent group item. Only available if item has a parent.
group boolean whether the item is a group.
Source:

Sub-ID's

Each subId locator object contains, at minimum, a subId property, whose value is a string that identifies a particular DOM node in this component. It can have additional properties to further specify the desired node. See getNodeBySubId and getSubIdByNode methods for more details.

Properties:
Name Type Description
subId string Sub-id string to identify a particular dom node.

Following are the valid subIds:

oj-listview-disclosure

Sub-ID for the ojListView component's disclosure icon in group items. See the getNodeBySubId method for details.

Source:
Example

Get the disclosure icon for the group item with key 'foo':

var node = $( ".selector" ).ojListView( "getNodeBySubId", {'subId': 'oj-listview-disclosure', 'key': 'foo'} );

oj-listview-icon

Sub-ID for the ojListView component's disclosure icon in group items. See the getNodeBySubId method for details.

Deprecated:
Source:
Example

Get the disclosure icon for the group item with key 'foo':

var node = $( ".selector" ).ojListView( "getNodeBySubId", {'subId': 'oj-listview-icon', 'key': 'foo'} );

Events

animateEnd

Triggered when the default animation of a particular action has ended. Note this event will not be triggered if application cancelled the default animation on animateStart.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
action Object the action that started the animation. See animation section for a list of actions.
element Object the target of animation.
Source:
Examples

Initialize the ListView with the animateEnd callback specified:

$( ".selector" ).ojListView({
    "animateEnd": function( event, ui ) {
    }
});

Bind an event listener to the ojanimateend event:

$( ".selector" ).on( "ojanimateend", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

animateStart

Triggered when the default animation of a particular action is about to start. The default animation can be cancelled by calling event.preventDefault.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
action Object the action that starts the animation. See animation section for a list of actions.
element Object the target of animation.
endCallback function if the event listener calls event.preventDefault to cancel the default animation, it must call the endCallback function when it finishes its own animation handling and when any custom animation ends.
Source:
Examples

Initialize the ListView with the animateStart callback specified:

$( ".selector" ).ojListView({
    "animateStart": function( event, ui ) {
        // call event.preventDefault to stop default animation
    }
});

Bind an event listener to the ojanimatestart event:

$( ".selector" ).on( "ojanimatestart", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

beforeCollapse

Triggered before an item is collapsed via the expanded option, the collapse method, or via the UI.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
key Object the key of the item to be collapsed
item jQuery the item to be collapsed
Source:
Examples

Initialize the ListView with the beforeCollapse callback specified:

$( ".selector" ).ojListView({
    "beforeCollapse": function( event, ui ) {
        // return false to veto the event, which prevents the item to collapse
    }
});

Bind an event listener to the ojbeforecollapse event:

$( ".selector" ).on( "ojbeforecollapse", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

beforeCurrentItem

Triggered before the current item is changed via the current option or via the UI.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
previousKey Object the key of the previous item
previousItem jQuery the previous item
key Object the key of the new current item
item jQuery the new current item
Source:
Examples

Initialize the ListView with the beforeCurrentItem callback specified:

$( ".selector" ).ojListView({
    "beforeCurrentItem": function( event, ui ) {
        // return false to veto the event, which prevents the item to become focus
    }
});

Bind an event listener to the ojbeforecurrentitem event:

$( ".selector" ).on( "ojbeforecurrentitem", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

beforeExpand

Triggered before an item is expanded via the expanded option, the expand method, or via the UI.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
key Object the key of the item to be expanded
item jQuery the item to be expanded
Source:
Examples

Initialize the ListView with the beforeExpand callback specified:

$( ".selector" ).ojListView({
    "beforeExpand": function( event, ui ) {
        // return false to veto the event, which prevents the item to expand
    }
});

Bind an event listener to the ojbeforeexpand event:

$( ".selector" ).on( "ojbeforeexpand", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

collapse

Triggered after an item has been collapsed via the expanded option, the collapse method, or via the UI.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
key Object The key of the item that was just collapsed.
item jQuery The list item that was just collapsed.
Source:
Examples

Initialize the ListView with the expand callback specified:

$( ".selector" ).ojListView({
    "collapse": function( event, ui ) {}
});

Bind an event listener to the ojcollapse event:

$( ".selector" ).on( "ojcollapse", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

copy

Triggered when the copy action is performed on an item via context menu or keyboard shortcut.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
items Element[] an array of items in which the copy action is performed on
Source:
Examples

Initialize the ListView with the copy callback specified:

$( ".selector" ).ojListView({
    "copy": function( event, ui ) {
    }
});

Bind an event listener to the ojcopy event:

$( ".selector" ).on( "ojcopy", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

cut

Triggered when the cut action is performed on an item via context menu or keyboard shortcut.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
items Element[] an array of items in which the cut action is performed on
Source:
Examples

Initialize the ListView with the cut callback specified:

$( ".selector" ).ojListView({
    "cut": function( event, ui ) {
    }
});

Bind an event listener to the ojcut event:

$( ".selector" ).on( "ojcut", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

destroy

Triggered before the component is destroyed. This event cannot be canceled; the component will always be destroyed regardless.

Inherited From:
Source:
Examples

Initialize component with the destroy callback

// Foo is Button, InputText, etc.
$(".selector").ojFoo({
  'destroy': function (event, data) {}
});

Bind an event listener to the destroy event

$(".selector").on({
  'ojdestroy': function (event, data) {
      // verify that the component firing the event is a component of interest
      if ($(event.target).is(".mySelector")) {
          window.console.log("The DOM node id for the destroyed component is : %s", event.target.id);
      }
  };
});

expand

Triggered after an item has been expanded via the expanded option, the expand method, or via the UI.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
key Object The key of the item that was just expanded.
item jQuery The list item that was just expanded.
Source:
Examples

Initialize the ListView with the expand callback specified:

$( ".selector" ).ojListView({
    "expand": function( event, ui ) {}
});

Bind an event listener to the ojexpand event:

$( ".selector" ).on( "ojexpand", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

optionChange

Fired whenever a supported component option changes, whether due to user interaction or programmatic intervention. If the new value is the same as the previous value, no event will be fired. The event listener will receive two parameters described below:
Properties:
Name Type Description
event Event jQuery event object
ui Object event payload
Properties
Name Type Argument Description
option string the name of the option that is changing
previousValue boolean the previous value of the option
value boolean the current value of the option
subproperty Object <nullable>
an Object holding information about the subproperty that changed.
Properties
Name Type Description
path string the subproperty path that changed.
previousValue Object an Object holding the previous value of the subproperty.
value Object an Object holding the current value of the subproperty.
item jQuery the current item (only available for option "currentItem")
items jQuery the selected items (only available for option "selection")
optionMetadata Object information about the option that is changing
Properties
Name Type Description
writeback string "shouldWrite" or "shouldNotWrite". For use by the JET writeback mechanism.
Source:
Examples

Initialize component with the optionChange callback

$(".selector").ojListView({
  'optionChange': function (event, ui) {
       if (ui['option'] === 'selection') { // handle selection change }
   }
});

Bind an event listener to the ojoptionchange event

$(".selector").on({
  'ojoptionchange': function (event, ui) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) { 
        window.console.log("option that changed is: " + ui['option']);
    }
  };
});

paste

Triggered when the paste action is performed on an item via context menu or keyboard shortcut.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Element the element in which the paste action is performed on
Source:
Examples

Initialize the ListView with the paste callback specified:

$( ".selector" ).ojListView({
    "paste": function( event, ui ) {
    }
});

Bind an event listener to the ojpaste event:

$( ".selector" ).on( "ojpaste", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

ready

Triggered after all items in the ListView has been rendered. Note that in the highwatermark scrolling case, all items means the items that are fetched so far.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Deprecated:
Source:
Examples

Initialize the ListView with the ready callback specified:

$( ".selector" ).ojListView({
    "ready": function( event, ui ) {}
});

Bind an event listener to the ojready event:

$( ".selector" ).on( "ojready", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

reorder

Triggered after items are reorder within listview via drag and drop or cut and paste.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
items Element[] an array of items that are moved
position string the drop position relative to the reference item. Possible values are "before", "after", "inside"
reference Element the item where the moved items are drop on
Source:
Examples

Initialize the ListView with the reorder callback specified:

$( ".selector" ).ojListView({
    "reorder": function( event, ui ) {
    }
});

Bind an event listener to the ojreorder event:

$( ".selector" ).on( "ojreorder", function( event, ui ) {
    // verify that the component firing the event is a component of interest 
    if ($(event.target).is(".mySelector")) {} 
});

Methods

collapse(key, vetoable)

Collapse an item.

Note when vetoable is set to false, beforeCollapse event will still be fired but the event cannot be veto.

Parameters:
Name Type Description
key Object the key of the item to collapse
vetoable boolean whether the event should be vetoable
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

expand(key, vetoable)

Expand an item.

Note when vetoable is set to false, beforeExpand event will still be fired but the event cannot be veto.

Parameters:
Name Type Description
key Object the key of the item to expand
vetoable boolean whether the event should be vetoable
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

getContextByNode(node) → {Object|null}

Returns an object with context for the given child DOM node. This will always contain the subid for the node, defined as the 'subId' property on the context object. Additional component specific information may also be included. For more details on returned objects, see context objects.
Parameters:
Name Type Description
node Element The child DOM node
Source:
Returns:
The context for the DOM node, or null when none is found.
Type
Object | null
Example
 // Foo is ojInputNumber, ojInputDate, etc.
// Returns {'subId': oj-foo-subid, 'property1': componentSpecificProperty, ...}
var context = $( ".selector" ).ojFoo( "getContextByNode", nodeInsideComponent );

getDataForVisibleItem(context) → {Object|null}

Return the raw data for an item in ListView.
Parameters:
Name Type Description
context Object the context of the item to retrieve raw data.
Properties
Name Type Description
index Number the index of the item relative to its parent.
parent jQuery | Element | string | undefined the jQuery wrapped parent node, not required if parent is the root.
Source:
Returns:
item data

Type
Object | null
Example

Invoke the getDataForVisibleItem method:

$( ".selector" ).ojListView( "getDataForVisibleItem", {'index': 2} );

getExpanded() → {Array}

Gets the key of currently expanded items.
Source:
Returns:
array of keys of currently expanded items
Type
Array

getIndexerModel() → {Object}

Gets the IndexerModel which can be used with the ojIndexer. The IndexerModel provided by ListView by defaults returns a list of locale dependent characters. See translations for the key used to return all characters. When a user selects a character in the ojIndexer ListView will scroll to the group header (or the closest one) with the character as its prefix.
Deprecated:
Source:
Returns:
ListView's IndexerModel to be used with the ojIndexer
Type
Object

getNodeBySubId(locator) → {Array.<(Element|null)>|Element|null}

Return the subcomponent node represented by the documented locator attribute values.

To lookup the disclosure icon the locator object should have the following:

  • subId: 'oj-listview-disclosure'
  • key: the key of the item
Parameters:
Name Type Description
locator Object An Object containing at minimum a subId property whose value is a string, documented by the component, that allows the component to look up the subcomponent associated with that string. It contains:

component: optional - in the future there may be more than one component contained within a page element

subId: the string, documented by the component, that the component expects in getNodeBySubId to locate a particular subcomponent

Source:
Returns:
the subcomponent located by the subId string passed in locator, if found.

Type
Array.<(Element | null)> | Element | null

getSubIdByNode(node) → {Object|null}

Returns the subId string for the given child DOM node. For more details, see getNodeBySubId.

Parameters:
Name Type Description
node Element child DOM node
Source:
Returns:
The subId for the DOM node, or null when none is found.
Type
Object | null

option(optionName, value) → {Object|undefined}

This method has several overloads, which get and set component options and their fields. The functionality is unchanged from that provided by JQUI. See the examples for details on each overload.

Parameters:
Name Type Argument Description
optionName string | Object <optional>
the option name (string, first two overloads), or the map (Object, last overload). Omitted in the third overload.
value Object <optional>
a value to set for the option. Second overload only.
Inherited From:
Source:
Returns:
The getter overloads return the retrieved value(s). When called via the public jQuery syntax, the setter overloads return the object on which they were called, to facilitate method chaining.
Type
Object | undefined
Examples

First overload: get one option:

This overload accepts a (possibly dot-separated) optionName param as a string, and returns the current value of that option.

var isDisabled = $( ".selector" ).ojFoo( "option", "disabled" ); // Foo is Button, Menu, etc.

// For object-valued options, dot notation can be used to get the value of a field or nested field.
var startIcon = $( ".selector" ).ojButton( "option", "icons.start" ); // icons is object with "start" field

Second overload: set one option:

This overload accepts two params: a (possibly dot-separated) optionName string, and a new value to which that option will be set.

$( ".selector" ).ojFoo( "option", "disabled", true ); // Foo is Button, Menu, etc.

// For object-valued options, dot notation can be used to set the value
// of a field or nested field, without altering the rest of the object.
$( ".selector" ).ojButton( "option", "icons.start", myStartIcon ); // icons is object with "start" field

Third overload: get all options:

This overload accepts no params, and returns a map of key/value pairs representing all the component options and their values.

var options = $( ".selector" ).ojFoo( "option" ); // Foo is Button, Menu, etc.

Fourth overload: set one or more options:

This overload accepts a single map of option-value pairs to set on the component. Unlike the first two overloads, dot notation cannot be used.

$( ".selector" ).ojFoo( "option", { disabled: true, bar: 42 } ); // Foo is Button, Menu, etc.

refresh()

Redraw the entire list view after having made some external modifications.

This method does not accept any arguments.

Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.
Example

Invoke the refresh method:

$( ".selector" ).ojListView( "refresh" );

scrollToItem(item)

Scrolls the list until the specified item is visible. If the item is not yet loaded (if scrollPolicy is set to 'loadMoreOnScroll'), then no action is taken.
Parameters:
Name Type Description
item Object an object with a 'key' property that identifies the item to scroll to.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

whenReady() → {Promise}

Returns a Promise that resolves when the component is ready, i.e. after data fetching, rendering, and animations complete. Note that in the highwatermark scrolling case, component is ready after data fetching, rendering, and associated animations of items fetched so far are complete.

This method does not accept any arguments.

Source:
Returns:
A Promise that resolves when the component is ready.
Type
Promise

widget() → {jQuery}

Returns a jQuery object containing the root dom element of the listview.

This method does not accept any arguments.

Source:
Returns:
the root DOM element of list
Type
jQuery

Non-public Methods

Note: Extending JET components is not currently supported. Thus, non-public methods are for internal use only.

<protected, static> _AfterCreate()

Initialize the listview after creation
Source:

<protected, static> _ComponentCreate()

Create the listview
Source:

<protected> _AddActiveable(options)

Add touch and mouse listeners to toggle oj-active class
Parameters:
Name Type Description
options !Object | !jQuery This parameter can either be the element (convenience syntax for callers needing to specify only the element(s) that would otherwise have been passed as options.element) or an object supporting the following fields:
Properties
Name Type Argument Description
element jQuery The element(s) to receive the oj-active class on active Required if afterToggle is specified.
afterToggle function(string) <nullable>
Optional callback function called each time the active classes have been toggled, after the toggle. The event.type string is passed and indicates whether the classes were added or removed. The active classes are added on "touchstart" or "mousedown" or "mouseenter" and the active classes are removed on "touchend" or "touchcancel" or "mouseup" or "mouseleave". Components with consistency requirements, such as "oj-default must be applied iff no state classes such as oj-active are applied," can enforce those rules in this callback.
Inherited From:
Source:
See:

<protected> _AddHoverable(options)

Add mouse listners to toggle oj-hover class
Parameters:
Name Type Description
options !Object | !jQuery This param can either be the element (convenience syntax for callers needing to specify only the element(s) that would otherwise have been passed as options.element) or an object supporting the following fields:
Properties
Name Type Argument Description
element jQuery The element(s) to receive the oj-hover class on hover Required if afterToggle is specified.
afterToggle function(string) <nullable>
Optional callback function called each time the hover classes have been toggled, after the toggle. The string "mouseenter" or "mouseleave" is passed, indicating whether the classes were added or removed. Components with consistency requirements, such as "oj-default must be applied iff no state classes such as oj-hover are applied," can enforce those rules in this callback.
Inherited From:
Source:
See:

<protected> _AfterCreate()

This method is called after _ComponentCreate, but before the create event is fired. The JET base component does tasks here that must happen after the component (subclass) has created itself in its override of _ComponentCreate. Notably, the base component handles the rootAttributes and contextMenu options here, since those options operate on the component root node, which for some components is created in their override of _ComponentCreate.

Subclasses should override this method only if they have tasks that must happen after a superclass's implementation of this method, e.g. tasks that must happen after the context menu is set on the component.

Overrides of this method should call this._super first.

Inherited From:
Source:

<protected> _AfterCreateEvent()

This method is called after the create event is fired. Components usually should not override this method, as it is rarely correct to wait until after the create event to perform a create-time task.

An example of a correct usage of this method is Dialog's auto-open behavior, which needs to happen after the create event.

Only behaviors (like Dialog auto-open behavior) should occur in this method. Component initialization must occur earlier, before the create event is fired, so that create listeners see a fully inited component.

Overrides of this method should call this._super first.

Do not confuse this method with the _AfterCreate method, which is more commonly used.

Inherited From:
Source:

<protected> _CompareOptionValues(option, value1, value2) → {boolean}

Compares 2 option values for equality and returns true if they are equal; false otherwise.

Parameters:
Name Type Description
option String the name of the option
value1 Object first value
value2 Object another value
Inherited From:
Source:
Returns:
Type
boolean

<protected> _ComponentCreate()

All component create-time initialization lives in this method, except the logic that specifically needs to live in _InitOptions, _AfterCreate, or _AfterCreateEvent, per the documentation for those methods. All DOM creation must happen here, since the intent of _AfterCreate, which is called next, is to contain superclass logic that must run after that DOM is created.

Overrides of this method should call this._super first.

Summary of create-time methods that components can override, in the order that they are called:

  1. _InitOptions
  2. _ComponentCreate (this method)
  3. _AfterCreate
  4. (The create event is fired here.)
  5. _AfterCreateEvent

For all of these methods, the contract is that overrides must call this._super first, so e.g., the _ComponentCreate entry means baseComponent._ComponentCreate, then _ComponentCreate in any intermediate subclasses, then _ComponentCreate in the leaf subclass.

Inherited From:
Source:

<protected> _create()

This method is final in JET. Components should instead override one or more of the overridable create-time methods listed in _ComponentCreate.

Inherited From:
Source:

<protected> _FixRendererContext(context) → {Object}

Prepares a custom renderer context object for either the JQuery or custom element syntax, removing and exposing keys as needed.
Parameters:
Name Type Description
context Object The renderer context object.
Inherited From:
Source:
Returns:
The cleaned up renderer context.
Type
Object

<protected> _focusable(options)

Sets JET's "focus" CSS classes when the element is focused and removes them when focus is lost.

The oj-focus class is set on all focuses.

Some components additionally have an oj-focus-highlight class, which applies a focus indicator that is appropriate on a subset of the occasions that oj-focus is appropriate. Those components should pass true for the applyHighlight param, in which case the oj-focus-highlight class is set if appropriate given the current focus highlight policy.

Focus highlight policy

The focus highlight policy supports the 3 values listed below. By default, it is retrieved from the $focusHighlightPolicy SASS variable, shared by many components and patterns. Components with different needs, including those exposing a component-specific SASS variable or other API for this, should see the getFocusHighlightPolicy parameter below. Valid focus highlight policies:

Policy Description
"nonPointer" Indicates that the component should apply the oj-focus-highlight class only for focuses not resulting from pointer (touch or mouse) interaction. (In the built-in themes, the SASS variable defaults to this value.)
"all" Indicates that the component should apply the class for all focuses.
"none" Indicates that the component should never apply the class, because the application has taken responsibility for applying the class when needed for accessibility.
Toggling the classes

Components that toggle these focus classes outside of this API must maintain the invariant that oj-focus-highlight is applied to a given element in a (not necessarily strict) subset of cases that oj-focus is applied to that element.

Typically the specified element should be within the component subtree, in which case the classes will automatically be removed from the element when the component is destroyed, when its disabled option is set to true, and when _NotifyDetached() is called.

As a minor exception, for components that wrap themselves in a new root node at create time, if the specified element is within the root node's subtree but not within the init node's subtree, then at destroy time only, the classes will not be removed, since destroy() is expected to remove such nodes.

If the element is NOT in the component subtree, then the caller is responsible for removing the classes at the times listed above.

Listeners

If setupHandlers is not passed, or if setupHandlers is passed and uses _on to register its listeners as seen in the example, then the listeners are not invoked when the component is disabled, and the listeners are automatically cleaned up when the component is destroyed. Otherwise, the caller is responsible for ensuring that the disabled state is handled correctly, and removing the listeners at destroy time.

Related API's

Non-component internal callers should see oj.DomUtils.makeFocusable(). Per its JSDoc (unpublished; see the source), it has a couple of additional usage considerations.

Parameters:
Name Type Description
options !Object | !jQuery This param can either be the element (convenience syntax for callers needing to specify only the element(s) that would otherwise have been passed as options.element) or an object supporting the following fields:
Properties
Name Type Argument Description
element jQuery The element(s) to receive the oj-focus classes on focus. Required if setupHandlers not passed; ignored otherwise.
applyHighlight boolean true if the oj-focus-highlight class should be applied when appropriate. false or omitted if that class should never be applied.
afterToggle function(string) <nullable>
Optional callback function called each time the focus classes have been toggled, after the toggle. The string "focusin" or "focusout" is passed, indicating whether the classes were added or removed. Components with consistency requirements, such as "oj-default must be applied iff no state classes such as oj-focus are applied," can enforce those rules in this callback.
getFocusHighlightPolicy function() <nullable>
Optional if applyHighlight is true; ignored otherwise. Components with a component-specific focus policy mechanism should pass a function that always returns one of the three valid values listed above, keeping in mind that this method can be called on every focus. See the example.
recentPointer function() <nullable>
Relevant iff applyHighlight is true and the focus highlight policy is "nonPointer"; ignored otherwise. Recent pointer activity is considered to have occurred if (a) a mouse button or finger has recently been down or up, or (b) this optional callback function returns true. Components wishing to additionally take into account (say) recent pointer movements can supply a function returning true if those movements have been detected, keeping in mind that this method can be called on every focus. See the example.
setupHandlers function(function(!jQuery),function(!jQuery)) <nullable>
Can be omitted by components whose focus classes need to be added and removed on focusin and focusout, respectively. Components needing to add/remove those classes in response to other events should specify this parameter, which is called once, immediately. See the examples.
Inherited From:
Source:
Examples

Opt into the highlight behavior, and specify a function to be called every time the classes are toggled:

var self = this;
this._focusable({
    'element': this.element, 
    'applyHighlight': true, 
    'afterToggle' : function() {
        self._toggleDefaultClasses();
    }
});

Arrange for mouse movement to be considered in addition to mouse/finger up/down. Also supply a component-specific focusHighlightPolicy:

var self = this;
this._focusable({
    'element': someElement, 
    'applyHighlight': true, 
    'recentPointer' : function() {
        // A timestamp-based approach avoids the risk of getting stuck in an inaccessible 
        // state if (say) mouseenter is not followed by mouseleave for some reason.
        var millisSincePointerMove = Date.now() - _myPointerMoveTimestamp;
        var isRecent = millisSincePointerMove < myThreshold;
        return isRecent;
    },
    'getFocusHighlightPolicy' : function() {
        // Return the value of a component-specific SASS $variable, component option, or other 
        // component-specific mechanism, either "all", "none", or "nonPointer".  SASS variables
        // should be pulled into JS once statically on load, not per-instance or per-focus.
    }
});

Add/remove the focus classes in response to events other than focusin/focusout:

var self = this;
this._focusable({
    'applyHighlight': myBooleanValue, 
    'setupHandlers': function( focusInHandler, focusOutHandler) {
        self._on( self.element, {
            // This example uses focus/blur listeners, which don't bubble, rather than the 
            // default focusin/focusout (which bubble).  This is useful when one focusable  
            // element is a descendant of another.
            focus: function( event ) {
                focusInHandler($( event.currentTarget ));
            },
            blur: function( event ) {
                focusOutHandler($( event.currentTarget ));
            }
        });
    }
});

Alternate usage of setupHandlers, which simply stashes the handlers so they can be called from the component's existing handlers:

var self = this;
this._focusable({
    'applyHighlight': myBooleanValue, 
    'setupHandlers': function( focusInHandler, focusOutHandler) {
        self._focusInHandler = focusInHandler;
        self._focusOutHandler = focusOutHandler;
    }
});

<protected> _getCreateOptions()

This method is not used in JET. Components should instead override _InitOptions.

Inherited From:
Source:

<protected> _GetEventForSyntax(event) → {Object}

Given an event, returns the appropriate event for the component syntax. For custom elements, if the event is a JQuery event, this method will return the unwrapped original event.
Parameters:
Name Type Description
event Object [description]
Inherited From:
Source:
Returns:
Type
Object

<protected> _GetReadingDirection() → {string}

Determines whether the component is LTR or RTL.

Component responsibilities:

  • All components must determine directionality exclusively by calling this protected superclass method. (So that any future updates to the logic can be made in this one place.)
  • Components that need to know the directionality must call this method at create-time and from refresh(), and cache the value.
  • Components should not call this at other times, and should instead use the cached value. (This avoids constant DOM queries, and avoids any future issues with component reparenting (i.e. popups) if support for directional islands is added.)

App responsibilities:

  • The app specifies directionality by setting the HTML "dir" attribute on the <html> node. When omitted, the default is "ltr". (Per-component directionality / directional islands are not currently supported due to inadequate CSS support.)
  • As with any DOM change, the app must refresh() the component if the directionality changes dynamically. (This provides a hook for component housekeeping, and allows caching.)
Default Value:
  • "ltr"
Inherited From:
Source:
Returns:
the reading direction, either "ltr" or "rtl"
Type
string

<protected> _GetSavedAttributes(element) → {Object|null}

Gets the saved attributes for the provided element.

If you don't override _SaveAttributes and _RestoreAttributes, then this will return null.

If you override _SaveAttributes to call _SaveAllAttributes, then this will return all the attributes. If you override _SaveAttributes/_RestoreAttributes to do your own thing, then you may also have to override _GetSavedAttributes to return whatever you saved if you need access to the saved attributes.

Parameters:
Name Type Description
element Object jQuery selection, should be a single entry
Inherited From:
Source:
Returns:
savedAttributes - attributes that were saved for this element in _SaveAttributes, or null if none were saved.
Type
Object | null

<protected> _init()

JET components should almost never implement this JQUI method. Please consult an architect if you believe you have an exception. Reasons:

  • This method is called at create time, after the create event is fired. It is rare for that to be the appropriate time to perform a create-time task. For those rare cases, we have the _AfterCreateEvent method, which is preferred over this method since it is called only at that time, not also at re-init time (see next).
  • This method is also called at "re-init" time, i.e. when the initializer is called after the component has already been created. JET has not yet identified any desired semantics for re-initing a component.
Inherited From:
Source:

<protected> _InitOptions(originalDefaults, constructorOptions)

This method is called before _ComponentCreate, at which point the component has not yet been rendered. Component options should be initialized in this method, so that their final values are in place when _ComponentCreate is called.

This includes getting option values from the DOM, where applicable, and coercing option values (however derived) to their appropriate data type if needed.

No work other than setting options should be done in this method. In particular, nothing should be set on the DOM until _ComponentCreate, e.g. setting the disabled DOM attribute from the disabled option.

A given option (like disabled) appears in the constructorOptions param iff the app set it in the constructor:

  • If it appears in constructorOptions, it should win over what's in the DOM (e.g. disabled DOM attribute). If for some reason you need to tweak the value that the app set, then enable writeback when doing so: this.option('foo', bar, {'_context': {writeback: true, internalSet: true}}).
  • If it doesn't appear in constructorOptions, then that option definitely is not bound, so writeback is not needed. So if you need to set the option (e.g. from a DOM attribute), use this.option('foo', bar, {'_context': {internalSet: true}}).

Overrides of this method should call this._super first.

Parameters:
Name Type Argument Description
originalDefaults Object original default options defined on the component and its ancestors
constructorOptions Object <nullable>
options passed into the widget constructor
Inherited From:
Source:

<protected> _IsCustomElement() → {boolean}

Determines whether the component is being rendered as a custom element.
Inherited From:
Source:
Returns:
True if the component is being rendered as a custom element
Type
boolean

<protected> _IsEffectivelyDisabled() → {boolean}

Determines whether this component is effectively disabled, i.e. it has its 'disabled' attribute set to true or it has been disabled by its ancestor component.

Inherited From:
Source:
Returns:
true if the component has been effectively disabled, false otherwise
Type
boolean

<protected> _NotifyAttached()

Notifies the component that its subtree has been connected to the document programmatically after the component has been created.

Inherited From:
Source:

<protected> _NotifyContextMenuGesture(menu, event, eventType)

When the contextMenu option is set, this method is called when the user invokes the context menu via the default gestures: right-click, Press & Hold, and Shift-F10. Components should not call this method directly.

The default implementation simply calls this._OpenContextMenu(event, eventType). Overrides of this method should call that same method, perhaps with additional params, not menu.open().

This method may be overridden by components needing to do things like the following:

  • Customize the launcher or position passed to _OpenContextMenu(). See that method for guidance on these customizations.
  • Customize the menu contents. E.g. some components need to enable/disable built-in commands like Cut and Paste, based on state at launch time.
  • Bail out in some cases. E.g. components with UX approval to use PressHoldRelease rather than Press & Hold can override this method to say if (eventType !== "touch") this._OpenContextMenu(event, eventType);. When those components detect the alternate context menu gesture (e.g. PressHoldRelease), that separate listener should call this._OpenContextMenu(), not this method (_NotifyContextMenuGesture()), and not menu.open().

Components needing to do per-launch setup like the above tasks should do so in an override of this method, not in a beforeOpen listener or an _OpenContextMenu() override. This is discussed more fully here.

Parameters:
Name Type Description
menu Object The JET Menu to open as a context menu. Always non-null.
event Event What triggered the menu launch. Always non-null.
eventType string "mouse", "touch", or "keyboard". Never null.
Inherited From:
Source:

<protected> _NotifyDetached()

Notifies the component that its subtree has been removed from the document programmatically after the component has been created.

Inherited From:
Source:

<protected> _NotifyDetached()

Notifies the component that its subtree has been removed from the document programmatically after the component has been created.

Inherited From:
Source:

<protected> _NotifyHidden()

Notifies the component that its subtree has been made hidden programmatically after the component has been created.

Inherited From:
Source:

<protected> _NotifyShown()

Notifies the component that its subtree has been made visible programmatically after the component has been created.

Inherited From:
Source:

<protected> _OpenContextMenu(event, eventType, openOptions, submenuOpenOptions, shallow)

The only correct way for a component to open its context menu is by calling this method, not by calling Menu.open() or _NotifyContextMenuGesture(). This method should be called in two cases:

  • This method is called by _NotifyContextMenuGesture() and its overrides. That method is called when the baseComponent detects the default context menu gestures: right-click, Press & Hold, and Shift-F10.
  • Components with UX-approved support for alternate context menu gestures like PressHoldRelease should call this method directly when those gestures are detected.

Components needing to customize how the context menu is launched, or do any per-launch setup, should do so in the caller of this method, (which is one of the two callers listed above), often by customizing the params passed to this method (_OpenContextMenu) per the guidance below. This setup should not be done in the following ways:

  • Components should not perform setup in a beforeOpen listener, as this can cause a race condition where behavior depends on who got their listener registered first: the component or the app. The only correct component use of a beforeOpen listener is when there's a need to detect whether something else launched the menu.
  • Components should not override this method (_OpenContextMenu), as this method is final. Instead, customize the params that are passed to it.

Guidance on setting OpenOptions fields:

Launcher:

Depending on individual component needs, any focusable element within the component can be the appropriate launcher for this launch.

Browser focus returns to the launcher on menu dismissal, so the launcher must at least be focusable. Typically a tabbable (not just focusable) element is safer, since it just focuses something the user could have focused on their own.

By default (i.e. if openOptions is not passed, or if it lacks a launcher field), the component init node is used as the launcher for this launch. If that is not focusable or is suboptimal for a given component, that component should pass something else. E.g. components with a "roving tabstop" (like Toolbar) should typically choose the current tabstop as their launcher.

The :focusable and :tabbable selectors may come in handy for choosing a launcher, e.g. something like this.widget().find(".my-class:tabbable").first().

Position:

By default, this method applies positioning that differs from Menu's default in the following ways: (The specific settings are subject to change.)

  • For mouse and touch events, the menu is positioned relative to the event, not the launcher.
  • For touch events, "my" is set to "start>40 center", to avoid having the context menu obscured by the user's finger.

Usually, if position needs to be customized at all, the only thing that needs changing is its "of" field, and only for keyboard launches (since mouse/touch launches should almost certainly keep the default "event" positioning). This situation arises anytime the element relative to which the menu should be positioned for keyboard launches is different than the launcher element (the element to which focus should be returned upon dismissal). For this case, { "position": {"of": eventType==="keyboard" ? someElement : "event"} } can be passed as the openOptions param.

Be careful not to clobber useful defaults by specifying too much. E.g. if you only want to customize "of", don't pass other fields like "my", since your value will be used for all modalities (mouse, touch, keyboard), replacing the modality-specific defaults that are usually correct. Likewise, don't forget the eventType==="keyboard" check if you only want to customize "of" for keyboard launches.

InitialFocus:

This method forces initialFocus to "menu" for this launch, so the caller needn't specify it.

Parameters:
Name Type Argument Description
event Event What triggered the context menu launch. Must be non-null.
eventType string "mouse", "touch", or "keyboard". Must be non-null. Passed explicitly since caller knows what it's listening for, and since events like contextmenu and click can be generated by various input modalities, making it potentially error-prone for this method to determine how they were generated.
openOptions Object <optional>
Options to merge with this method's defaults, which are discussed above. The result will be passed to Menu.open(). May be null or omitted. See also the shallow param.
submenuOpenOptions Object <optional>
Options to be passed through to Menu.open(). May be null or omitted.
shallow boolean <optional>
Whether to perform a deep or shallow merge of openOptions with this method's default value. The default and most commonly correct / useful value is false.
  • If true, a shallow merge is performed, meaning that the caller's position object, if passed, will completely replace this method's default position object.
  • If false or omitted, a deep merge is performed. For example, if the caller wishes to tweak position.of while keeping this method's defaults for position.my, position.at, etc., it can pass {"of": anOfValue} as the position value.

The shallow param is n/a for submenuOpenOptions, since this method doesn't apply any defaults to that. (It's a direct pass-through.)

Inherited From:
Source:

<protected> _ReleaseResources()

Release resources held by this component, for example, remove listeners. This is called during destroy. _SetupResources will set up resources needed by this component, and is called during _create.

This base class default implementation does nothing.

Component subclasses can opt in by overriding _SetupResources and _ReleaseResources.
Inherited From:
Source:

<protected> _RemoveActiveable(element)

Remove touch and mouse listeners that were registered in _AddActiveable
Parameters:
Name Type Description
element jQuery The same element passed to _AddActiveable
Inherited From:
Source:
See:

<protected> _RemoveHoverable(element)

Remove mouse listners that were registered in _AddHoverable
Parameters:
Name Type Description
element jQuery The same element passed to _AddHoverable
Inherited From:
Source:
See:

<protected> _RestoreAllAttributes()

Restores all the element's attributes which were saved in _SaveAllAttributes. This method is final in JET.

If a subclass wants to save/restore all attributes on create/destroy, then the subclass can override _SaveAttributes and call _SaveAllAttributes and also override _RestoreAttributes and call _RestoreAllAttributes.

Inherited From:
Source:

<protected> _RestoreAttributes()

Restore the attributes saved in _SaveAttributes.

_SaveAttributes is called during _create. And _RestoreAttributes is called during _destroy.

This base class default implementation does nothing.

We also have _SaveAllAttributes and _RestoreAllAttributes methods that save and restore all the attributes on an element. Component subclasses can opt into these _SaveAllAttributes/_RestoreAllAttributes implementations by overriding _SaveAttributes and _RestoreAttributes to call _SaveAllAttributes/_RestoreAllAttributes. If the subclass wants a different implementation (like save only the 'class' attribute), it can provide the implementation itself in _SaveAttributes/_GetSavedAttributes/_RestoreAttributes.

Inherited From:
Source:

<protected> _SaveAllAttributes(element)

Saves all the element's attributes within an internal variable. _RestoreAllAttributes will restore the attributes from this internal variable.

This method is final in JET. Subclasses can override _RestoreAttributes and call _RestoreAllAttributes.

The JSON variable will be held as:

[
  {
  "element" : element[i],
  "attributes" :
    {
      attributes[m]["name"] : {"attr": attributes[m]["value"]
    }
  }
]
Parameters:
Name Type Description
element Object jQuery selection to save attributes for
Inherited From:
Source:

<protected> _SaveAttributes(element)

Saves the element's attributes. This is called during _create. _RestoreAttributes will restore all these attributes and is called during _destroy.

This base class default implementation does nothing.

We also have _SaveAllAttributes and _RestoreAllAttributes methods that save and restore all the attributes on an element. Component subclasses can opt into these _SaveAllAttributes/_RestoreAllAttributes implementations by overriding _SaveAttributes and _RestoreAttributes to call _SaveAllAttributes/_RestoreAllAttributes. If the subclass wants a different implementation (like save only the 'class' attribute), it can provide the implementation itself in _SaveAttributes/_RestoreAttributes.

Parameters:
Name Type Description
element Object jQuery selection to save attributes for
Inherited From:
Source:

<protected> _SetRootAttributes()

Reads the rootAttributes option, and sets the root attributes on the component's root DOM element. See rootAttributes for the set of supported attributes and how they are handled.

Inherited From:
Source:
Throws:
if unsupported attributes are supplied.

<protected> _SetupResources()

Sets up needed resources for this component, for example, add listeners. This is called during _create. _ReleaseResources will release resources help by this component, and is called during destroy.

This base class default implementation does nothing.

Component subclasses can opt in by overriding _SetupResources and _ReleaseResources.
Inherited From:
Source:

<protected> _UnregisterChildNode()

Remove all listener references that were attached to the element.
Inherited From:
Source: