Component: ojTree

Oracle® JavaScript Extension Toolkit (JET)
3.2.0

E87541-01

QuickNav

Options


Sub-ID's

oj. ojTree extends oj.baseComponent

Version:
  • 3.2.0
Since:
  • 0.6

JET Tree Component

The ojTree component allows a user to display the hierarchical relationship between the nodes of a tree.

The tree contents can be specified in JSON format, or by prepopulating the tree's containing <div> with HTML <ul> list markup.


JSON Node Format


Each node object typically has a title and an attr property. Any node can be defined as a parent by supplying a children property, which is an array of more node definitions. (Note that if a node has a children property defined, but no children are actually specified, then ojTree will perform lazy-loading by requesting child node data only when a node is expanded for the first time - refer to option property data.

Example: Basic JSON Tree definition


[
  {
    "title": "Home",
    "attr": {"id": "home"},
  },
  {
    "title": "News",
    "attr": {"id": "news"}
  },
  {
     "title": "Blogs",
     "attr": {"id": "blogs"},
     "children": [ {
                      "title": "Today",
                      "attr": {"id": "today"}
                   },
                   {
                      "title": "Yesterday",
                      "attr": {"id": "yesterday"}
                   }
                 ]
  }
]


Whatever attributes are defined for the attr property are transferred to the associated DOM <li> element. A metadata attribute can also be defined for arbitrary user-defined data that is to be associated with a node. (This metadata is maintained within the ojTree instance, and is not represented in the DOM.) A node's metadata can be retrieved using the jQuery .data() method.


Example: Expanded use of the attr and metadata properties

[
 {
   "title": "Home",
   "attr": {
              "id": "home",
              "myattr1": "Hello",         <-- additional user-defined attributes
              "myattr2": "World"          <-- additional user-defined attributes
           },
   "metadata": {                          <-- node metadata
                 "type": "T123",
                 "val": 42,
                 "active": true
               }
 },

 . . .
 $('#mytree').on("ojoptionchange", function (ev, ui) {
                 if (ui.option && ui.option == "selection") {
                   // retrieve metadata from (first) selected node
                   var meta = $(ui.value[0]).data() ;
                 }
             }) ;
]


Example: Retrieving node attributes and data

$("#mytree).on("ojtreehover", function (ev, ui){

 // ui.item = node
 // ui.item.attr("id")         -  retrieve a node attribute
 // ui.item.attr("myattr1")    -    ..
 // ui.item.data("active")     -  retrieve the "active" meta-data value from previous example

});


For flexibility, attributes can also be applied to the node's <a> element if required, by specifying the node data property as an object.

Example: Using the data property

{
  "attr" : { "id" : "myid" },                    <-- this is set on the <li>
  "data" : {
             "attr" : {
                        "flags"   : "A-B",       <-- this is set on the <a>
                        "title" : "This is a tooltip"
                      }
            }
}


HTML Node Format


A Tree can be populated via standard HTML markup using a <ul> list structure - refer to option property "data". In the case where the "data" option has not been defined, ojTree will use any HTML markup defined in the Tree's containing <div>, and on startup the <ul> the markup will be detached from the containing <div>, saved, and used as a template to create a new tree structure in its place. When the tree is destroyed, the original markup is restored. Lazy loading of a node's children (when expanded) is performed if any node indicates that it has children, but its child <ul> list is left empty.


Example: Using HTML markup to populate a Tree.

<div id="mytree">
   <ul>
      <li id="home">
         <a href="#"<Home>/a>
      </li>
      <li id="news">
         <a href="#">News</a>
      </li>
      <li id="blogs">
           <a href="#">Blogs</a>
           <ul>
             <li id="today">
                <a href="#">Today</a>
             </li>
             <li id="yesterday">
                <a href="#">Yesterday</a>
             </li>
           </ul>
      </li>
</div>
  


Touch End User Information

Target Gesture Action
Node Disclosure Icon Tap Toggle the node's expanded state.
Node Text Tap Select the node. Toggle the select state if multi-select mode.
Node Text Press and Hold Open the context menu.

Keyboard End User Information

Key Action
UpArrow/DownArrow Moves between visible nodes.
LeftArrow On an expanded node, collapses the node.
On a collapsed or leaf node, moves focus to the node's parent.
RightArrow On a collapsed node, expands the node.
On an expanded node, moves to the first first child of the node.
On an end node, does nothing.
Spacebar Toggles the selected status of the node.
Home Moves to the top node of the tree.
End Moves to the last visible node of the tree.
Shift + UpArrow Extends selection up one node (assuming multiple selection has been defined).
Shift + DownArrow Extends selection down one node (assuming multiple selection has been defined).
Shift + Home Extends selection up to the top-most node.
Shift + PageDown Extends selection to the last node.
Ctrl + Spacebar Toggles the selection state of the current node (assuming multiple selection has been defined).
Shift + Spacebar Extends selection to the current node (assuming multiple selection has been defined).
Shift + F10 Invoke Context Menu (if defined) on current node.
* (asterisk) Expands all nodes.

Reading direction

The only supported way to set the reading direction (LTR or RTL) is to set the "dir" attribute on the <html> element of the page. As with any JET component, in the unusual case that the reading direction is changed post-init, the tree must be refresh()ed, or the page must be reloaded.

Initializer

.ojTree(options)

Creates a JET Tree.
Parameters:
Name Type Argument Description
options Object <optional>
a map of option-value pairs to set on the component
Source:
Example

Initialize the Tree with options:

$( ".selector" ).ojTree( {"selectionMode": "single", "data": [JSON objects]} );

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.

The JET Menu should be initialized before the Tree using it as a context menu.

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.

When defining a contextMenu, ojTree will provide built-in behavior for "edit" style functionality (e.g. cut/copy/paste) if the following format for menu <li> item's is used (no <a> elements are required):

  • <li data-oj-command="oj-tree-cut" />
  • <li data-oj-command="oj-tree-copy" />
  • <li data-oj-command="oj-tree-paste" />
  • <li data-oj-command="oj-tree-paste-after" />
  • <li data-oj-command="oj-tree-paste-before" />
  • <li data-oj-command="oj-tree-remove" />
  • <li data-oj-command="oj-tree-rename" />
The available translated text will be applied to menu items defined this way.
Default Value:
  • null
Source:
Examples

Initialize a JET Tree with a context menu:

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

// via JET initializer (less preferred) :
$( ".selector" ).ojTree({ "contextMenu": "#myContextMenu"  ... } });

Get or set the contextMenu option for an ojTree after initialization:

// getter
var menu = $( ".selector" ).ojTree( "option", "contextMenu" );

// setter
$( ".selector" ).ojTree( "option", "contextMenu", "#myContextMenu"} );

data :Object|Array|string|null

Specifies the data source used to populate the tree. Currently supported data sources are a JsonTreeDataSource, or json, or html.

The general format of the data option is one of the following:

  • data : oj.JsonTreeDataSource

  • data : null (or omit) - ojTree will look at the containing <div> and use any existing html <ul> markup found

  • data : " json string "

  • data : [ array of json objects ]

  • data : "<ul><li> ... html markup string </ul>"

  • data : { "data" :     ... or     "ajax" :     . . .    }       // retrieve json or html

Use of the "data" property of the data option, specifies that the tree is to be populated from JSON or HTML (local or remote). The "data" object contains one of two properties:
  • "data"
  • "ajax"
An optional "dataType" property may also be specified, which can take the value "json" or "html", and indicates what kind of data is being returned in the "data" or "ajax" method (default is "json"). When "data" is specified as an object, its "data" property may be specified as a function which receives two arguments: node, and fn.


Example: Skeleton outline of a "data" function:

data : {
         "data" : function(node, fn) {
                   // node  -  the jQuery wrapped node to be expanded for a lazy load,
                   //          or -1 if it is the initial call to load the tree.
                   // fn    -  a function to call with the JSON to be applied.

                   fn( new_json_node_data ) ;   // return the JSON
                  }
       }

The "ajax" property of the "data" option allows remote JSON to be retrieved. It may be specified as an object (refer to the jQuery .ajax() settings object). If may also be specified as false or omitted, if no AJAX operations are performed.

When specified as an object, it should contain the following two properties:
  • type
  • url

"ajax" : {
          "type": "GET",
          "url":   "my_url"      // some url to the content
         }
"url" may also be specified as a function which should return a url string:

"ajax" : {
          "type" : "GET",
          "url":   function (node) {
                        ... return a url string ...
                    }
         )

where node is a parent node (can be used for lazy loading), or -1 to indicate the initial tree load.

Optionally, success and error functions may be defined. If the success function returns a value, it will be used to populate the tree; this can be useful if there is a need to transform the data returned by a server at the client before it is displayed in the tree.


Note: to enable lazy loading of a parent node, specify that it has children but do not define them. When it is opened, data() or ajax() will be called with the node whose JSON is to be returned.

Default Value:
  • null
Source:
Examples

Example 1: Skeleton outline of success and error functions


"ajax": {
         "type":"GET",
         "url": myurl    <-- url to full tree JSON
         "success" : function(data, status, obj) {
                       // data   = the JSON data
                       // status = "success"
                       // obj    = the AJAX object.
                       trace("Ajax " + status) ;
                       // return the data, can transform it first if required.
                       // if no return value, the data is used untransformed.
         },
         "error" : function(reason, feedback, obj) {
                       // reason e.g. "parsererror"
                       // feedback.message  e.g. "unexpected string"
                       // obj    = the AJAX object.
                       trace("Ajax error " + reason + " feedback=" + feedback.message) ;
         },

Example 2: Load the complete tree from locally defined JSON.


"data" :  [
           {
            "title": "Home",
            "attr": {"id": "home"},
           },
           {
             "title": "News",
             "attr": {"id": "news"}
           },
           {
             "title": "Blogs",
             "attr": {"id": "blogs"},
             "children": [ {
                            "title": "Today",
                            "attr": {"id": "today"}
                           },
                           {
                             "title": "Yesterday",
                             "attr": {"id": "yesterday"}
                           }
                         ]
           }
         ]

Example 3: Load the complete tree with remotely served JSON.


"data" : {
           "ajax": {
                    "type":"GET",
                    "url": myurl    <-- url to full tree JSON
                   }

         }

Example 4: Load the complete tree with remotely served JSON via a function.


"data" : {

          "ajax": {
                    "type":"GET",
                    "url": function() {
                              return (a url) ;
                           }
                  }

         }

Example 5: Load a partial tree, and retrieve node data when a parent node is expanded and needs to be populated.


"data" : {
          "ajax": {
                    "type":"GET",
                    "url": function(node) {
                            if (node === -1) {                       // -1 indicates initial load
                              return (url for for  partial json) ;   // the tree outline with parent nodes empty.
                            }
                            else {
                              var id = node.attr("id") ;

                              return (a url based on the node id to retrieve just the node children) ;
                            }
                          }
                  }

         }

Example 6: Transform data received from server before passing to ojTree.


"data" : {
          "ajax": {
                    "type":"GET",
                    "url": function(node) {
                             . . .
                           },
                     "success" : function (data)  {
                                   . . .    // transform the received data into node JSON format

                                   return (transformed data) ;
                                 },
                     "error" : function () {
                                  // ajax call failed.
                               }
                  }

         }

Example 7: Use own mechanism to load a partial tree and retrieve node data when a parent is expanded.


// Sample outline of a tree.  Note that the parent nodes "Node2" and "Node3" have
// their "children" property specifed, but no children are actually defined.

{
 "title" : Node1",
 "attr" : {"id" : "n1"}
},
{
 "title" : Node2",
 "attr" : {"id" : "n2"},
 "children" : []
},
{
 "title" : Node3",
 "attr" : {"id" : "n3"},
 "children" : []
},


"data" : {
          "data": function(node, fn) {
                    // node  =  the node whose children are to be retrieved
                    // fn    =  the function to call with the retrieved node json

                    if (node === -1) {             // initial tree load
                      fn( acquired node json for the tree) ;
                    }
                    else {                         // node lazy load
                      var id = node.attr("id") ;   // get the node id, will be "n2"
                                                   // or "n3", in this example.
                      fn( acquired node json for the expanded node ) ;
                    }
                 }

         }
}

When an option call is made to reset the data property
of a tree, the application does not need to call refresh.

disabled :boolean

Disables the tree if set to true.
Default Value:
  • false
Source:
Examples

Initialize the tree with the disabled option specified:

$( ".selector" ).ojTree( { "disabled": true } );

Get or set the disabled option, after initialization:

// getter
var disabled = $( ".selector" ).ojTree( "option", "disabled" );

// setter
$( ".selector" ).ojTree( "option", "disabled", true );

dnd :Object

Specifies support for HTML5 Drag and Drop. Please refer to third-party documentation for details of the HTML5 Drag and Drop facilities.

The dnd property and its values indicates whether:

  1. the nodes may be reordered using drag and drop within the same tree
  2. the tree can participate in drag/drop operations with other drag/drop enabled components or elements.
To make a tree reorderable, specify an object with the property reorder set to 'enable'. Setting the reorder property to "disable", or omitting the reorder property disables reordering support.

Example: Enable drag and drop for tree node reordering:

dnd : (
        reorder : 'enable'
      }


To allow tree nodes to act as a drag source, specify the optional property drag. The drag node property object allows the application to control the drag process.

Example: Enable drag support:

dnd : (
        drag : {
                 node: {
                         ... drag callback properties
                       }
               }
      }

To allow a tree to act as a drop target, specify the optional property drop. The properties of the drop object relate to movement over potential node drop targets and the drop itself, and permit application control of the drop process.

Example: Enable drop support:

dnd : (
        drop : {
                 node: {
                         ... drop callback properties
                       }
               }
      }

Note: if the neither of the drag dataTypes nor dragStart properties are specified, the tree will not be drag enabled. If the drop property is not specifed, the tree will not be drop enabled. However, if a tree is drag and/or drop disabled and reorder: 'enabled' is defined, drag/drop will still be permitted for node reordering only (within the same tree).

Properties:
Name Type Description
reorder string Valid values are 'enable' or 'disable'. Default if omitted is 'disable'
drag Object Specifies that the tree will act as a drag source.
The following drag options allow callback functions to be specified to provide application control over the drag process.
(For a discussion of the possible return values from these callback functions, refer to the HTML5 documentation for the dragstart, drag, and dragend events.)
Properties
Name Type Description
node Object Specify an object containing the following optional callback properties. To permit dragging, at least one of the properties dataTypes or dragStart is required. That is, if dataTypes is specified, then dragStart is not required unless additional control of the drag start is required. If dataTypes is not defined, then dragStart should be used to assign the node data to a data type in the event.dataTransfer object.
Properties
Name Type Description
dataTypes string | Array.<string> The optional MIME type(s) to use for the dragged data in the dataTransfer object. May be specified as a string if there is only one type, or an array of strings if multiple types are needed.

When a drag starts, each data type will be set using dataTransfer.setData() with the stringified array of the JSON representation of the dragged tree node(s). (These node objects may be recreated via JSON.parse()). Each array entry is of the same format as used to create/insert nodes using the create() method.)

If not specified, the app should set its own data type(s) in its dragStart callback, using the node data found in the callback's ui argument. If the dataTypes property is omitted and no data type is set in the dragStart callback, drag is not permitted.

dragStart function An application callback function that will be called when a drag operation is initiated on a node.

function(event, ui)
NameTypeDescription
eventEventthe jQuery wrapped native dragstart event object.
uiObjecttree parameters.
NameTypeDescription
itemarray of objectsthe node(s) being dragged.
The dragStart callback function may use the dataTransfer method setDragImage() if it wishes to replace the default drag image, and also the effectAllowed property. If the callback does not modify effectAllowed, a default of 'copy' is used if the ctrl key is used, else it is set to 'move'. If the dataTypes property has not been specified, this callback should set a data type using event.dataTransfer.setData() and the node data in the ui argument. If the dataTypes property is omitted and no data type is set in the dragStart callback, drag is not permitted.

This function should return true to indicate that the drag is permissible or false otherwise. If this function does not return a value, the drag will be permitted.

drag function An application callback function that will be called repeatedly as the drag source is dragged.

function(event)
NameTypeDescription
eventEventthe jQuery wrapped native drag event object.
dragEnd function An application callback function that will be called when a drag operation completes (regardless of whether the drop operation ever occurs or ends successfully or not.

function(event, ui)
NameTypeDescription
eventEventthe jQuery wrapped native dragend event object.
uiObjecttree parameters.
NameTypeDescription
reorderbooleantrue if a reorder was just performed, else false.

If reorder is false the dragEnd callback should remove any nodes from the tree that were moved (that is, dropEffect is "move").

drop Object Specifies that the tree can act as a drop target.
Properties
Name Type Description
node Object An object allowing callback functions to be specifed to provide drag/drop feedback to the application.
(For a discussion of the possible return values from these callback functions, refer to the HTML5 documentation for the dragenter, dragover, drop, and dragleave events.)
Properties
Name Type Description
dragEnter function An application callback function that will be called when a tree node is entered during a drag.

function(event, ui)
NameTypeDescription
eventEventthe jQuery wrapped native dragenter event object.
uiObjecttree parameters.
NameTypeDescription
itemObjectthe jQuery wrapped tree node being entered. This will be null if the tree is empty.
positionstringthe drop position relative to the reference node. Can be 'before', 'after', 'inside', or 'first'.
referenceObjectthe jQuery wrapped reference node that ui.position refers to. This will be null if the tree is empty.
This function should return false to indicate that the dragged data can be accepted, or true otherwise. Any explicit return value will be passed back to jQuery. Returning false will cause event.stopPropagation() and event.preventDefault() to be called. (event.preventDefault() is required by HTML5 Drag and Drop to indicate acceptance of the dragged data at the potential drop position.)

If this function does not return a value, dataTypes will be matched against the drag data types to determine if the data is acceptable. If dataTypes is not defined, the dragged data will be accepted.

dragOver function An application callback function that will be called when a tree node is dragged over. (Note that there will be multiple calls to this function as the mouse moves over the node.

function(event, ui)
NameTypeDescription
eventEventthe jQuery wrapped native event object.
uiObjecttree parameters.
NameTypeDescription
itemObjectthe jQuery wrapped tree node being dragged over. This will be null if the tree is empty.
positionstringthe drop position relative to the reference node Can be 'before', 'after', 'inside', or 'first'.
referenceObjectthe reference node that ui.position refers to. this will be null if the tree is empty.
As for dragEnter, this function should return false to indicate that the dragged data can be accepted at this position, or true otherwise. If this function does not return a value, dataTypes will be matched against the drag data types to determine if the data is acceptable. If dataTypes is not defined the dragged data will be accepted.
drop function An application callback function that will be called when the dragged object is dropped on a tree.

function(event, ui)
NameTypeDescription
eventEventthe jQuery wrapped native event object.
uiObjecttree parameters.
NameTypeDescription
positionstringthe drop position relative to the reference node Can be 'before', 'after', 'inside', or 'first'.
referencestringthe reference node that ui.position refers to.
reorderbooleantrue if a reorder was just performed, else false.

If reorder is true, the drop callback should not perform any tree restructuring since this is automatically performed as part of the reorder.

This function should return false to indicate that the dragged data is accepted, or true otherwise.
dragLeave function An application callback function that will be called when the drag operation moves out of the last entered node. It is also called if the escape key is pressed while the cursor is over a drop position, or a dragOver callback cancels the drag.

function(event, ui)
NameTypeDescription
eventEventthe jQuery wrapped native event object.
uiObjecttree parameters.
NameTypeDescription
itemObjectthe jQuery wrapped tree node that was last entered.
dataTypes string | Array.<string> An optional data type string, or array of strings that the tree will test for in the event.dataTransfer object when the object is moved over a potential tree drop position. If none of the dataTransfer data types are found in this list, a drop over the current position is not permitted. If the array is omitted or empty, the drag operation will continue.

Refer also to dataTypes in the drag property object.

Default Value:
  • {reorder:'disable'}
Source:
Examples

Allow drag from a tree, do not allow drop on the tree.


Note: to permit dragging, at least one of the dataTypes or dragStart properties is required. That is, if
dataTypes is specified, dragStart is not required unless additional tuning of the drag start is needed.
If dataTypes is not defined, then dragStart should be used to assign the node data to a dataType.

dnd: {
      drag: {
              node : {
                       datatypes: ['xxx'],
                       dragStart: myDragStart,
                       dragEnd:   myDragend
                     }
            }
    }

self.myDragStart = function(event, ui)
{
  event.preventDefault() ;   // allow drag
  return false ;
}

self.myDragend = function(event)
{
 var selections ;

 if (event.originalEvent.dataTransfer.dropEffect === "move") {
   // Remove the moved node(s) selected.
   if (self.$tree.ojTree("isSelected", event.target)) {
     selections =  self.$tree.ojTree("option", "selection") ;
     for (i = 0; i < selections.length; i++) {
        self.$tree.ojTree("remove", selections[i]) ;
     }
   }
   else {
     // Single unselected node moved
     self.$tree.ojTree("remove", event.target) ;
   }
 }
}

Handle drop of node(s) from another tree.


dnd: {
      drop: {
              node : {
                       dataTypes: ['xxx'],
                       drop:  myDrop
                     }
            }
    }

self.myDrop = function(event, ui)
{
 var data = JSON.parse(event.originalEvent.dataTransfer.getData('xxx')) ;

 self.$tree.ojTree("create", ui['reference'][0], ui['position'], data) ;
 return false ;
}

Do not allow drag of a particular node.


dnd: {
      drag: {
              node : {
                       dragStart:  function(event, ui) {
                            if (ui.item.id != "myTopId") {
                              event.preventDefault() ;     // allow drag
                              return false ;
                            }
                            // else can't drag
                       }
                     }
            }
    }

Disallow drop above a certain node.


dnd: {
      drag: {
              node : {
                       dragEnter:  function(event, ui)  {
                            if ((ui.position != 'above') ||
                                (ui.item.id) != 'mynode')) {
                              event.preventDefault() ;     // allow drag
                              return false ;
                            }
                            // else can't drop here
                            return true ;
                       }
                     }
            }
    }

emptyText :string|null

The text to display when there are no data in the Tree. If not specified, default text is extracted from the resource bundle. Specify an empty string if this default behavior is not required.
Default Value:
  • "No data"
Source:
Example

Initialize the tree with text set to 'no data':

$( ".selector" ).ojTree({ "data":data, "emptyText": "no data" });

expandParents :boolean

Specify true if expanding a node programatically should also expand its parents (i.e all parent nodes down to this node will be expanded).
Default Value:
  • false
Source:

icons :boolean

Specifies whether node icons are to be displayed. Specify true to display icons, or false to suppress node icons.
Default Value:
  • true
Source:

initExpanded :Array|null

Specifies whether any nodes should be initially expanded on start-up. Specify an array of node id's, or the string "all" if all parent nodes should be expanded. The value may optionally be specified as an empty array.
Default Value:
  • null
Source:

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" );

selectPrevOnDelete :boolean

Specifies the action to take when a selected node is deleted. If set to true, its previous sibling (or parent, if no previous siblings) is selected. If false is specified, no action is taken.
Default Value:
  • false
Source:

selectedParentCollapse :boolean|string

Specifies what action is to be taken when a selected node's parent is collapsed. Specify false if nothing is to be done. Specify "selectParent" if the node's closed parent is to be selected, or specify "deselect" if the node is to be deselected.
Default Value:
  • false
Source:

selectedParentExpand :boolean

Specifies what action is to be taken when a node is programmatically expanded. Specify true if all of the node's closed parents should be opened automatically. If false is specified, the node is selected but will remain invisible if its parents are currently collapsed.
Default Value:
  • true
Source:

selection :Array

An array of node elements that are currently selected. If the array is modified by an application, the selected node status of the tree is modified to match the array (nodes may be defined as elements, jQuery wrapped nodes, or selectors pointing to the elements that should be selected).
Default Value:
  • Array
Source:

selectionMode :string

Specifies whether selection is permitted, and whether more than one node can be selected at a time. Values are "single" for single selection, "multiple" to allow multiple concurrent selections, and "none" to inhibit selection.
Default Value:
  • "single"
Source:

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.labelCopy :string

Context menu text used for copying a node.

See the translations option for usage examples.

Default Value:
  • "Copy"
Source:

translations.labelCreate :string

Context menu text used for creating a new node).

See the translations option for usage examples.

Default Value:
  • "Create"
Source:

translations.labelCut :string

Context menu text used for cutting a node.

See the translations option for usage examples.

Default Value:
  • "Cut"
Source:

translations.labelEdit :string

Context menu text used for the submenu containing the editing context menu entries.

See the translations option for usage examples.

Default Value:
  • "Edit"
Source:

translations.labelMultiSelection :string

.

/**

Used as the dragged text when multiple nodes have been selected and are being dragged during a reorder operation.

See the translations option for usage examples.

Default Value:
  • "Multiple Selection"
Source:

translations.labelNewNode :string

Used as node text when a new node has been added to a Tree and no node text has been supplied.

See the translations option for usage examples.

Default Value:
  • "New Node"
Source:

translations.labelNoData :string

Text shown when a tree contains no nodes.

See the translations option for usage examples.

Default Value:
  • "No Data"
Source:

translations.labelPaste :string

Context menu text used for pasting a node.

See the translations option for usage examples.

Default Value:
  • "Paste"
Source:

translations.labelPasteAfter :string

Context menu text used for pasting a node after the node at the drop point.

See the translations option for usage examples.

Default Value:
  • "Paste After"
Source:

translations.labelPasteBefore :string

Context menu text used for pasting a node before the node at the drop point.

See the translations option for usage examples.

Default Value:
  • "Paste Before"
Source:

translations.labelRemove :string

Context menu text used for removing a node.

See the translations option for usage examples.

Default Value:
  • "Remove"
Source:

translations.labelRename :string

Context menu text used for renaming a node.

See the translations option for usage examples.

Default Value:
  • "Rename"
Source:

translations.stateLoading :string

Used as node placeholder text when a node is being loaded.

See the translations option for usage examples.

Default Value:
  • "Loading..."
Source:

types :Object|null

The 'types' option allow nodes to be classified and their appearance and behavior modified.

Typical uses are to define a specific icon for a particular node, or to inhibit certain operations on a particular type of folder (e.g. the root node cannot be deleted or moved).

A node type has the following properties:

  • "image" - specifies the location of the icon to be used (optional). May also be specified as false to suppress the image.

  • "position" - position of sprite in the image in the format "left top", e.g. "-36px -16px".
    Optional - omit if icon is not contained within a multi-sprite image.

  • method name - specify a function or a boolean. Optional.
    Any node operation method (that is, takes a node as its first argument) can be redefined (e.g. select, expand, collapse, etc). Alternatively, the method can be defined as true or false to permit or inhibit the operation, or a function that returns a boolean value. The default value if omitted is true (i.e. the operation is permitted).
In the following example, three node types have been defined: "myroot", "myfolder", and "myleaf". Any node that does not have one of these types defaults its behavior to the default type (whose properties can also be redefined). The default "default" node type has no restrictions on the operations that can be performed on the node. In the following example, a modification to the default type properties have been made. Also, for the "myroot" node type, the standard select, remove and move operations return false which inhibts those operations. been redefined to be no-ops.
Default Value:
  • true
Source:
Examples

Example 1: Add custom appearance and node behavior.


"types": {
           "myroot" :   {
                           "image"  : baseurl + "/img/root.png",
                           "select" : function() { return false; },
                           "remove" : function() { return false; },
                           "move" :   function() { return false; },
                        },
           "myfolder" : {
                           "image" : baseurl + "/img/folder.png"
                        },
           "myleaf" :   {
                          "image" : "baseurl + "/img/leaf.png"
                        },
           "default" : {   <-- optional redefinition of the default behavior
                          "image" : "baseurl + "/img/leaf.png",
                          "remove" : function() { return false; }
                       }

         }
}

User-defined types are specified as an attribute of the node.  The default
node type attribute is "type", but this could be changed if desired using
the "attr" property. Thus, for the node types in example 1 above, the node
type attribute values in the node definitions could be set as in example 2:

Example 2: Using node types in the tree JSON.


[
  {
    "title": "Root",
    "attr": {
              "id": "root",
              "type": "myroot"                      <--- node type
            },
    "children": [
                  {
                    "title": "Home",
                    "attr": {"id": "home",
                             "type": "myleaf"}      <--- node type
                  },
                  {
                    "title": "News",
                    "attr": {
                              "id": "news",
                              "type": "myleaf"      <--- node type
                            }
                  },
                  {
                    "title": "Blogs",
                    "attr": {
                              "id": "blogs",
                              "type": "myfolder"    <--- node type
                            },
                    "children": [ {
                                    "title": "Today",
                                    "attr": {
                                              "id": "today",
                                              "type": "myleaf"
                                            }
                                  },
                                  {                 <--- default node type
                                    "title": "Yesterday",
                                    "attr": {"id": "yesterday"}
                                  }
                                ]
                  }
                ]
 }
]

As described above, the node type attribute used on the corresponding tree
<li> element defaults to "type", but this can be redefined using the attr
property as in the following example:

Example 2: Using node types in the tree JSON.


"types": {
          "attr" : "mytype",    <--- node type attribute is now "mytype"
          "types": {
                     "myroot" : {
                                  "image" : . . .
                                   . . .
                                }
         }

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:

disclosure

Sub-ID for the ojTree component's disclosure icons.

To find the disclosure (expand/collapse) icon DOM node for a Tree node, the locator object should have the following:
  • subId: "oj-tree-node['node id']['disclosure']"
Source:
Example

Get the disclosure icon DOM node for the Tree node with Id "#home":

var node = $( ".selector" ).ojTree("getNodeBySubId", {"subId": "oj-tree-node['#home']['disclosure]" } );

icon

Sub-ID for ojTree component's node icons.

To find the icon DOM node for a Tree node, the locator object should have the following:
  • subId: "oj-tree-node['node id']['icon']"
Source:
Example

Get the node icon for the Tree node with Id "#home":

var node = $( ".selector" ).ojTree("getNodeBySubId", {"subId": "oj-tree-node['#home']['icon]" } );

Sub-ID for the ojTree's component's node link element.

To find the link DOM element for a Tree node, the locator object should have the following:
  • subId: "oj-tree-node['node id']['link']"
Source:
Example

Get the link DOM node for the Tree node with Id "#home":

var node = $( ".selector" ).ojTree("getNodeBySubId", {"subId": "oj-tree-node['#home']['link]" } );

title

Sub-ID for the ojTree component's node title.

To find the node title DOM node for a Tree node, the locator object should have the following:
  • subId: "oj-tree-node['node id']['title']"
Source:
Example

Get the text title DOM node for the Tree node with Id "#home":

var node = $( ".selector" ).ojTree("getNodeBySubId", {"subId": "oj-tree-node['#home']['title]" } );

Events

before

Triggered prior to an event.

The following events can be vetoed during before event processing by returning false from the before event handler (omitting a return value or returning true permits the event processing to continue): collapse, expand, hover, select, remove, rename.

Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
func string the event causing this before event to be triggered.
item Object the node that is the subject of the event
Source:
Examples

Initialize the Tree with the before callback specified:

$( ".selector" ).ojTree({
    "before": function(event, ui)  {
                    console.log("Before event " + ui.func);
              }
});

Bind an event listener to the ojbefore event:

$( ".selector" ).on( "ojbefore", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) {
                         console.log("Before event " + ui.func);
                  } 
                });

collapse

Triggered when a tree node is collapsed.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that has been collapsed
Source:
Examples

Initialize the Tree with the collapse callback specified:

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

Bind an event listener to the ojcollapse event:

$( ".selector" ).on( "ojcollapse", function(event, ui) {
                   // Verify that component of interest fired the event
                   if ($(event.target).is("#mytree")) { . . . }
                 });

collapseAll

Triggered when all nodes of a parent node, or the complete tree, have been collapsed.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node(s) that were collapsed.
targ Object the node that was targeted for collapseAll, or -1 if the complete tree is collapsed.
Source:
Examples

Initialize the Tree with the collapseAll callback specified:

$( ".selector" ).ojTree({
    "collapseAll": function( event, ui ) {. . .}
});

Bind an event listener to the ojcollapseall event:

$( ".selector" ).on( "ojcollapseall", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

create

Triggered when a tree node has been created and added to the tree.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that has been created
Source:
Examples

Initialize the Tree with the create callback specified:

$( ".selector" ).ojTree({
    "create": function( event, ui ) {. . .}
});

Bind an event listener to the ojcreate event:

$( ".selector" ).on( "ojcreate", function(event, ui) {
                   // Verify that component of interest fired the event
                   if ($(event.target).is("#mytree")) { . . . }
                 });

cut

Triggered when a tree node has been cut from the tree via the context menu.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that was cut
Source:
Examples

Initialize the Tree with the cut callback specified:

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

Bind an event listener to the ojcut event:

$( ".selector" ).on( "ojcut", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

dehover

Triggered when a tree node is no longer hovered over.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that is no longer hovered over
Source:
Examples

Initialize the Tree with the dehover callback specified:

$( ".selector" ).ojTree({
    "dehover": function( event, ui ) {. . .}
});

Bind an event listener to the ojdehover event:

$( ".selector" ).on( "ojdehover", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

destroy

Triggered when a tree is destroyed.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Source:
Examples

Initialize the Tree with the destroy callback specified:

$( ".selector" ).ojTree({
    "destroy": function( event, ui ) {}
});

Bind an event listener to the ojdestroy event:

$( ".selector" ).on( "ojdestroy", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

expand

Triggered when a tree node is expanded.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that has been expanded
Source:
Examples

Initialize the Tree with the expand callback specified:

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

Bind an event listener to the ojexpand event:

$( ".selector" ).on( "ojexpand", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

expandAll

Triggered when all nodes of a parent node, or the complete tree, have been expanded.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node(s) that were expanded.
targ Object the node that was targeted for expandAll, or -1 if the complete tree is collapsed.
Source:
Examples

Initialize the Tree with the expandAll callback specified:

$( ".selector" ).ojTree({
    "expandAll": function( event, ui ) {. . .}
});

Bind an event listener to the ojexpandall event:

$( ".selector" ).on( "ojexpandall", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

hover

Triggered when a tree node is hovered over.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that is hovered over
Source:
Examples

Initialize the Tree with the hover callback specified:

$( ".selector" ).ojTree({
    "hover": function( event, ui ) {. . .}
});

Bind an event listener to the ojhover event:

$( ".selector" ).on( "ojhover", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

loaded

Triggered when a tree has been loaded and the node data has been applied.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Source:
Examples

Initialize the Tree with the loaded callback specified:

$( ".selector" ).ojTree({
    "loaded": function( event, ui ) {}
});

Bind an event listener to the ojloaded event:

$( ".selector" ).on( "ojloaded", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

move

Triggered when a tree node has been moved within the tree.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that was moved
position string the moved node's new position relative to the reference node. Can be "before", "after", or "inside".
reference Object the reference node that ui.position refers to.
Source:
Examples

Initialize the Tree with the move callback specified:

$( ".selector" ).ojTree({
    "move": function(event, ui) {. . .}
});

Bind an event listener to the ojmove event:

$( ".selector" ).on( "ojmove", function(event, ui) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

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 changed.
previousValue Object an Object holding the previous value of the option. When previousValue is not a primitive type, i.e., is an Object, it may hold the same value as the value property.
value Object an Object holding 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.
optionMetadata Object information about the option that changed
Properties
Name Type Description
writeback string "shouldWrite" or "shouldNotWrite". For use by the JET writeback mechanism; 'shouldWrite' indicates that the value should be written to the observable.
Inherited From:
Source:
Examples

Initialize component with the optionChange callback

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

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 one or more tree nodes have been pasted into the tree via the context menu.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Array the node(s) pasted
position string the placement of the nodes relative to the reference node. May be "inside", "before", or "after".
reference Object the reference node
Source:
Examples

Initialize the Tree with the paste callback specified:

$( ".selector" ).ojTree({
    "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 the component of interest
                  if ($(event.target).is("#mytree")) { . . .}
                });

refresh

Triggered when a tree node, or the complete tree, has been refreshed.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that has been refreshed, or -1 if the whole tree has been refreshed.
Source:
Examples

Initialize the Tree with the refresh callback specified:

$( ".selector" ).ojTree({
    "refresh": function( event, ui ) {. . .}
});

Bind an event listener to the ojrefresh event:

$( ".selector" ).on( "ojrefresh", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

remove

Triggered when a tree node has been removed.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that has been removed.
parent Object the parent of the node that was removed.
prev Object the previous sibling, or if ui.item is the first child of its parent, the parent node.
Source:
Examples

Initialize the Tree with the remove callback specified:

$( ".selector" ).ojTree({
    "remove": function( event, ui ) {. . .}
});

Bind an event listener to the ojremove event:

$( ".selector" ).on( "ojremove", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

rename

Triggered when a tree node has been renamed.
Properties:
Name Type Description
event Event jQuery event object
ui Object Parameters
Properties
Name Type Description
item Object the node that has been renamed
title string the new node text title.
prevTitle string the node title prior to the rename.
Source:
Examples

Initialize the Tree with the rename callback specified:

$( ".selector" ).ojTree({
    "rename": function( event, ui ) {. . .}
});

Bind an event listener to the ojrename event:

$( ".selector" ).on( "ojrename", function( event, ui ) {
                  // Verify that component of interest fired the event
                  if ($(event.target).is("#mytree")) { . . .}
                });

Methods

collapse(node, skipAnim)

Collapses an expanded node, so that its children are not visible. Triggers a "collapse" event.
Parameters:
Name Type Argument Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element to be collapsed.
skipAnim boolean <optional>
Set to true to suppress node collapse animation (if a non-zero duration is defined or defaulted). Default is false.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

collapseAll(node, anim)

Collapses a node and all its descendants. Triggers a "collapseall" event.
Parameters:
Name Type Argument Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element whose descendants are to be collapsed. If omitted , or set to -1, all nodes in the tree are collapsed.
anim boolean <optional>
Set to true (or omit) if all nodes are to be collapsed with animation (if a non-zero duration is defined or defaulted). Default is true.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

create(refnode, position, data) → {Object}

Creates a new node and adds it to the tree. Triggers a "create" event.
Parameters:
Name Type Description
refnode HTMLElement | Object | string specifies the node that the new node will be placed in, or next to, depending on the "position" argument. Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element. If there is no reference node (because the tree is empty), specify null or undefined (or -1).
position string | number specifies the position of the newly created node in relation to the "refnode" specified by the first argument. Can be a string : "before", "after", "inside", "first", "last", or a zero-based index to position the new node at a specific point among the children of "refnode".
data Object | Array An object or array of objects containing data to create new node(s). The object properties are the same as for defining a JSON node:
"attr" - an object of attribute name/value pairs (at least an "id" property should be defined).
"title" - a string used for the visible text of the node.

var new Node = { "title" : "My Title", "attr" : { "id": "myid" } };
Source:
Returns:
Returns the jQuery wrapped node(s) created from the 'data' argument.
Type
Object

dehover()

Removes the "hover" state of the currently hovered (i.e. active) node. Triggers a "dehover" event.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

deselect(node)

Deselects a node. Triggers an "optionChange" event for options property "selection".
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element to be deselected.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

deselectAll(context)

Deselects all selected nodes. If optional argument "context" is specified, only the selected nodes within that context will be selected. Triggers an "optionChange" event for options property "selection".
Parameters:
Name Type Argument Description
context HTMLElement | Object | string <optional>
Can be a DOM element, a jQuery wrapped node, or a selector pointing to an element within the tree.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

destroy()

Removes the Tree from the DOM. If the tree was constructed from original user <ul> markup defined in the Tree's containing <div>, this markup is reinstated.

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 destroy method:

$( ".selector" ).ojTree( "destroy" );

expand(node, skipAnim)

Expands a collapsed parent node, so that its children are visible. Triggers an "expand" event.
Parameters:
Name Type Argument Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element to be expanded.
skipAnim boolean <optional>
Set to true to suppress node expansion animation (if a non-zero duration is defined or defaulted). Default is false.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

expandAll(node, anim)

Expands a node and all its descendants. Triggers an "expandall" event.
Parameters:
Name Type Argument Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element whose descendants are to be expanded. If omitted , or set to -1, all nodes in the tree are expanded.
anim boolean <optional>
Set to true (or omit) if all nodes are to expanded with animation (if a non-zero duration is defined or defaulted). Default is true.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

expanded(nodes, skipAnim) → {Object|null}

May be used as a getter of setter. If no argument is supplied, the method returns an array of nodes currently expanded. (An empty array implies that no nodes are expanded.) If an array of nodes is supplied as an argument, the specified nodes are expanded.
Parameters:
Name Type Argument Description
nodes Array <optional>
Omit to use as a getter, or specify an array of nodes to be expanded. Nodes may be defined as elements, id strings, jQuery wrapped nodes, or selectors pointing to the elements to be expanded.
skipAnim boolean <optional>
Set to true to suppress node expansion animation (if a non-zero duration is defined or defaulted). Default is false.
Source:
Returns:
A jQuery wrapped array of nodes if used as a getter, else null if used as a setter.
Type
Object | null

getChildren(node) → {Object|null}

Returns the children of the node specified.
Parameters:
Name Type Description
node HTMLElement | Object | string | number Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element. May also be specified as -1 or omitted to indicate the tree, in which case the top level children of the tree are returned.
Source:
Returns:
The jQuery wrapped array of child nodes, or null if there are no children.
Type
Object | null

getContextByNode(node) → {Object|null}

Returns a context object for the specified tree node. This includes the subid for the node as the subId property. Additional Tree component information is also included.
Parameters:
Name Type Description
node HTMLElement | Object | string | number Can be a DOM element, a jQuery wrapped node, or a selector pointing to a node element.
Source:
Returns:
An object containing node context data, or null if not found.
PropertyTypeDescription
subIdstring"oj-tree-node" or "oj-tree".
itemobjectthe tree node element.
nodeobjectthe jQuery wrapped node.
DEPRECATED - please use item.
leafbooleantrue if leaf node, else false if a parent node.

Type
Object | null

getNextSibling(node) → {Object|null}

Returns the next sibling of the node specified.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
The jQuery wrapped sibling node, or null if there is no next sibling.
Type
Object | null

getNodeBySubId(locator) → {Element|null}

Returns the subcomponent node element represented by the locator object subId property.
(See also getSubIdByNode.)
Parameters:
Name Type Description
locator Object An Object containing at minimum a "subId" property whose value is a string.

The general format of a subId string is:     "oj-tree-node['node id']['request']"
The "request" value can be "title, "icon", "link", or "disclosure".

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

Type
Element | null

getParent(node) → {Object|null}

Returns the parent node of the node specified.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
The jQuery wrapped parent node, or null if node is a top level node.
Type
Object | null

getPath(node, idMode) → {Array|boolean}

Returns the full path to a node, either as an array of ID's or node names, depending on the value of the "idMode" argument.

e.g. Given a node with Id 'Node1' at the root level, with a child 'Node2' which has a child 'Node3', then:

$tree.ojTree("getPath", "#Node3", true) ;

will return:

["Node1", "Node2", "Node3"]

Parameters:
Name Type Argument Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
idMode boolean <optional>
Set to true (or omit) to return ID's from the node attribute "id"), or false to return the names (i.e. text titles). Default is true.
Source:
Returns:
An array of node ID's or names. If the node is not found, false is returned.
Type
Array | boolean

getPrevSibling(node) → {Object|null}

Returns the previous sibling of the node specified.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
The jQuery wrapped sibling node, or null if there is no previous sibling.
Type
Object | null

getRoot() → {Object}

Returns the jQuery wrapped top outer <ul> element of the tree.
Source:
Returns:
The jQuery wrapped <ul> element of the tree.
Type
Object

getSubIdByNode(node) → {Object|null}

Returns the subid string for a child DOM element of a node. Refer to getNodeBySubId for a list of subId's.
Parameters:
Name Type Description
node Element child DOM element of a node.

Source:
Returns:
an object with a "subId" property containing the subid for the DOM element, or null if not found.

Type
Object | null

getText(node) → {string|boolean}

Returns the title of the specified node
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
The text string title of the node.
Type
string | boolean

getType() → {string|boolean}

Returns the user classified node type applied to the node in the "types" option.
Source:
Returns:
The node's type. If no types have been defined in the tree options, false is returned.
Type
string | boolean

hover(node)

Sets the specifed node as the current node of interest (e.g. a mouse-over). Triggers a "hover" event.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

isCollapsed(node) → {boolean}

Returns true if the node is collapsed, else false.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
true if the node is collapsed, else false.
Type
boolean

isExpanded(node) → {boolean}

Returns true if the node is expanded, else false.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
true if the node is expanded, else false.
Type
boolean

isLeaf(node) → {boolean}

Returns true if the node is a leaf node (that is, it has no children), else false.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
true if the node is a leaf node, else false.
Type
boolean

isSelected(node) → {boolean}

Returns true if the node is selected, else false.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
true if the node is selected, else false.
Type
boolean

move(node, refnode, position, iscopy)

Moves (or copies) a node within a tree, or from one tree to a different tree.
Parameters:
Name Type Argument Description
node HTMLElement | Object | string | number The node to be moved. Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
refnode HTMLElement | Object | string | number The reference node for the move (see "position" argument below). Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element. If the receiving tree ie empty and there can be no reference node, null or undefined (or -1) may be specified.
position string | number The position of the moved node relative to the reference node refnode. Can be "before", "after", "inside", "first", "last", or the zero-based index to position the node at a specific point among the reference node's current children.
iscopy boolean <optional>
Omit or specify false for a move operation, or true for a copy.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

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(node)

Refreshes the tree or a node.
Parameters:
Name Type Argument Description
node HTMLElement | Object | string | number <optional>
If -1 is specified (or the argument is omitted), the whole tree is refreshed. Alternatively, a specific node to be refreshed can be supplied. Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

remove(node) → {Object|boolean}

Removes a node. Triggers a "remove" event.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
Source:
Returns:
The jQuery wrapped node used as an argument.
Type
Object | boolean

rename(node, text)

Renames a node title.
Parameters:
Name Type Argument Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
text string <optional>
The new text string.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

scrollIntoView(obj, alignTo, setActive)

Scrolls a node into view.
Parameters:
Name Type Argument Description
obj Object An object containing the scroll properties.
PropertyDescription
"node"Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element to be selected. Any other non-node reference will default to the first tree node.
alignTo string <optional>
Specify 'top' if the top of the node is to be aligned to the top of the container. Specify 'bottom' if the bottom of the node is to be aligned to the bottom of the container. Any other value (or if omitted) will be treated as 'bottom'.
Note that placement is only honored if feasible. For example, when scrolling a node to the top, movement will stop should the bottom node scroll into view - placement to the requested top will not be completely honored in this case.
setActive boolean <optional>
If true, makes node the active node (i.e. keyboard focus) after scrolling into view. If omitted or set to false, node is not made active.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

select(node)

Selects a node. Triggers an "optionChange event for options property "selection".
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element to be selected.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

setType(node, str) → {boolean}

Sets the "type" attribute of the node using a type defined in the "types" option.
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element.
str string The type.
Source:
Returns:
true if the change was successful, else false.
Type
boolean

toggleExpand(node, skipAnim)

Expands a node if collapsed, or collapses a node if expanded. Triggers an "expand" or "collapse" event.
Parameters:
Name Type Argument Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element to be expanded/collapsed.
skipAnim boolean <optional>
Set to true to suppress node expand/collapse animation (if a non-zero duration is defined or defaulted). Default is false.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

toggleSelect(node)

Selects a node if deselected, or deselects a node if selected. Triggers an "optionChange" event for options property "selection".
Parameters:
Name Type Description
node HTMLElement | Object | string Can be a DOM element, a jQuery wrapped node, or a selector pointing to the element to be expanded/collapsed.
Source:
Returns:
When called via the public jQuery syntax, this method returns the object on which it was called, to facilitate method chaining.

widget() → {jQuery}

Returns a jQuery object containing the root element of the Tree component.
Source:
Returns:
the root element of the component
Type
jQuery
Example

Invoke the widget method:

var widget = $( ".selector" ).ojTree( "widget" );

Non-public Methods

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

<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: