Creating Sub Classes

A very common scenario is that you want to create a table where each row can be selected. The entire script was made with this in mind and you'll see that the power of Object Oriented Programming makes this almost too easy.

Constructor

All we need to do in the constructor is to call the super class constructor. We also set up the prototype chain.

function SelectableTableRows(oTableElement, bMultiple) {
   SelectableElements.call(this, oTableElement, bMultiple);
}
SelectableTableRows.prototype = new SelectableElements;

Notice the use of the method call. All function objects have this method and the first argument is the object that should be bound to the keyword this inside the function.

isItem

This is probably the most important method that you need to override when creating your own subclasses. The method takes an HTML element and returns true if the element should be considered to be an item. In this case it is an item if the element is a table row of the table.

SelectableTableRows.prototype.isItem = function (node) {
   return node != null && node.tagName == "TR" &&
      node.parentNode.parentNode == this._htmlElement;
};

Indexable Interface

That's all there is to it but out of convenience we override a few methods to make them more efficient. Since every table row has a property called rowIndex we are going to use this to our advantage. We also take advantage of the rows collection to simplify the methods.

SelectableTableRows.prototype.getItems = function () {
   return this._htmlElement.rows;
};

SelectableTableRows.prototype.getItemIndex = function (el) {
   return el.rowIndex;
};

SelectableTableRows.prototype.getItem = function (i) {
   return this._htmlElement.rows[i];
};

Usage

To use the SelectableTableRows you also need to include the file selectabletablerows.js. Then just use the SelectableTableRows constructor instead of the SelectableElements constructor.

SelectableTableCells

Another useful subclass is the SelectableTableCells class found in the file selectabletablecells.js. The implementation of this uses the HTML properties rowIndex and cellIndex to implement the methods for the Indexable interface. Once that is done the Traversable interface is implemented using this.

SelectableListItems

The subclass SelectableListItems (selectablelistitems.js) allows nested list items to be selected. The implementation for getNext and getPrevious are a bit complicated but it doesn't get much worse than this. In most cases it is as easy as it is for the SelectableTableRow class.

The demo for the SelectableListItems is only available in Mozilla due to the lack of CSS2 selector support (and differences in list styling) in other browsers.

Introduction
Usage
Sub Classes
API
Demo
Download

Author: Erik Arvidsson