Creating a Cross-Browser (DOM) Expandable Tree

Step 2: Define the Classes

I prefer to think of creating JavaScript of this nature as a problem in Java: start by thinking
about what classes we will need to accomplish our task. For our JavaScript tree, we will need two
classes: a class to represent the tree and a class to represent an individual node on the tree. Each
class has its own properties, collections, and methods.

The jsTree Class

We will call the class to represent the tree jsTree (creative, huh?). The one and only
property of the jsTree class is the root property. The root property
will serve as a pointer to the root node of the JavaScript tree.

The jsTree class also has one collection, which we will call nodes. The
nodes collection will serve as a collection of pointers to each node in the tree. In this
way, there is one place to go in order to get access to any node in the tree. This will be created as
a native JavaScript Array object.

The final step of the class is a constructor. In JavaScript, the class definition and the constructor
are one and the same, so we'll just put the constructor code at the bottom of the class definition. The
only thing to do in the constructor is to assign a copy of the instantiated tree object to the global
objLocalTree variable. This is done because we will need a reference to the tree in order
for the expanding/collapsing of nodes to work. Because we can't guess what variable name the developer
will assign to their tree, we need a variable that will point to the same instantiated object. This
point will become clearer as we continue on.

The jsTreeNode Class

The class to represent a node in the tree is called jsTreeNode (again, creativity flows
freely). Visually, a node is made up of essentially two parts: an icon and some text. Obviously, these
will be two properties of the jsTreeNode class. But what other properties are needed?

Since we want the tree to contain HTML links to pages, we actually need to provide the information
about a URL and its target location (that's two more properties for those keeping track at home). Add
to that the indent of the node (the root node's indent is 0; each level under the node increases the
indent by 1) and whether the node is expanded (with children visible) or collapsed (with children
invisible).

We have a total of six properties, four of which can be considered public (that is, the developer
can feel free to change their value without any repercussions), one that is private (indent: we do not want
the developer to change the value at all), and one that is a state (expanded: this should only be accessed
in read mode by the developer).

Finally, we have a collection for the jsTreeNode class. This is the collection of
child nodes for the node. We implement this using the native JavaScript Array object.