JavaScript Object-oriented technology to implement tree control

Source: Internet
Author: User
Tags abstract define array arrays html page implement string javascript array
Javascript| Object | control

A tree control is a familiar user interface control that is widely used to display hierarchical data.

The tree control has the unique ability to expand and fold branches, can display a large amount of information in a small space, and clearly conveys the hierarchical relationship between the data. All users who are familiar with the graphical user interface are able to use the tree-shaped control freely.


Figure I: A tree-shaped control implemented with JavaScript

The HTML itself does not support tree controls, but we can implement them through some JavaScript scripting code. In order to improve the reusability of the control, we should make full use of JavaScript to support object-oriented programming technology. The tree controls in this article apply to IE 4+ and Netscape 6.x, which should be said to cover the current mainstream browsers.

One, JavaScript and object-oriented

Object-oriented programming has three basic concepts: inheritance, encapsulation, polymorphism. The concepts of inheritance and encapsulation are relatively well understood, and the concept of polymorphism is relatively difficult to master and apply. In general, polymorphism refers to the ability to perform in many forms. In object-oriented programming, polymorphism represents the ability of a programming language to take a different approach depending on the data type or class of the object.

In "pure" object-oriented languages, such as Java, polymorphism is generally inseparable from the inheritance of classes. That is, you must define a hierarchical relationship of classes, at the top of which is an abstract class, and the underlying is a variety of specific implementations. Abstract classes define methods that subclasses must implement or overwrite, and different subclasses override methods of abstract classes in different ways depending on their needs.

For example, the formula for calculating the circle area and the rectangular area is completely different, and according to the object-oriented design idea, we first define an abstract class Shape,sharp class has a Findarea () method, and all subclasses deriving from the shape class must implement the Findarea () method. Then we define a rectangle class that represents a rectangle, a circle class that represents a circle, all two classes that inherit from the shape class. The rectangle class and the Circle class respectively implement the Findarea () method, both of which calculate the area with different formulas. The ultimate goal: regardless of which subclass of the shape the object belongs to (rectangle or circle), the Findarea () method can be invoked in the same way, without having to do with what formula is used to calculate the area of the called Findarea (). To effectively hide implementation details.

JavaScript languages do not support class based inheritance, but still have the ability to support polymorphism. JavaScript inheritance is a prototype based (Prototype) inheritance. In fact, as the example in this article shows, this kind of inheritance simplifies the writing of polymorphic methods and, structurally, the resulting program is also very close to the pure object-oriented language.

Ii. preparatory work

The entire tree control consists of four parts: graphics, CSS style definitions, HTML frame code, JavaScript code. As you can see from figure one, the tree control requires three graphs, representing collapsed branches (http://www.webjx.com/htmldata/2005-03-06/closed.gif), expanded branches (open.gif), and leaf nodes (http:// Www.webjx.com/htmldata/2005-03-06/doc.gif).

The following is the CSS style definition to use for the tree control:

< style>
body{
Font:10pt song, Sans-serif; Color:navy; }
. branch{
Cursor:pointer;
Cursor:hand;
Display:block; }
. leaf{
Display:none;
margin-left:16px; }
a{Text-decoration:none;}
a:hover{Text-decoration:underline;}
</style>

CSS rules are simple: the body rule sets the font and foreground (text) color of the document. The purpose of the branch rule is that when the mouse passes over a node that has child nodes, the pointer becomes the shape of the hand. The reason for defining two cursor properties is that IE and Netscape use different property names. Set the Display property to none in the leaf rule to implement the collapse effect of the leaf node, which does not contain the final node of the child node. In the scripting code, we display a node by setting the display property to block, which is set to none of the hidden nodes.

Third, the script design

The tree control implemented in this article contains a subtree object that has a collection of branches child objects, and each branch (branch) object has a collection of child objects. The child object can be either a branch object or a leaf (leaf) object. All three objects implement a polymorphic write () method, and the Write () method of different objects performs different operations depending on the object, i.e. the write () method of the tree object differs from the write () method of the Branch object. The write () method of the Branch object differs from the write () method of the Leaf object. In addition, the tree and branch objects each have an add () method that is used to add child objects to each object to which they belong.

Add the following code to the section of the HTML document. The purpose of this code is to create two image objects that correspond to the folder graphics of the open and collapsed state of the branch. There are also several tool functions that open or collapse the child elements of any branch, and transform the folder graph accordingly, depending on the opening or collapsing state of the branch.

< script language= "JavaScript" >
var openimg = new. Asset not found.
OPENIMG.SRC = "Open.gif";
var closedimg = new. Asset not found.
CLOSEDIMG.SRC = "Http://www.webjx.com/htmldata/2005-03-06/closed.gif";

function Showbranch (branch) {
var objbranch = document.getElementById (branch). style;
if (objbranch.display== "block")
Objbranch.display= "None";
Else
objbranch.display= "Block";
Swapfolder (' I ' + branch);
}

function Swapfolder (IMG) {
objimg = document.getElementById (IMG);
if (objImg.src.indexOf (' http://www.webjx.com/htmldata/2005-03-06/closed.gif ') >-1)
OBJIMG.SRC = OPENIMG.SRC;
Else
OBJIMG.SRC = CLOSEDIMG.SRC;
}
</script>

The code is preloaded with graphics objects, which helps to increase the speed of the display later. The Showbranch () function first obtains the style of the branch provided by the parameter, and then determines and toggles the display properties of the current style (switching back and forth between Block and none) to form branching and folding effects. The principle of the swapimage () function is essentially the same as the Showbranch () function, which first determines the current branch's graphics (open or collapsed folder), and then toggles the graphic.

Four, tree objects

Here is the constructor for the tree object:

function tree () {
This.branches = new Array ();
This.add = Addbranch;
This.write = Writetree;
}

The tree object represents the root of the entire structure. The tree () constructor creates a branches array, which is used to hold all child elements. The Add and write properties are pointers to two polymorphic methods, and the two polymorphism methods are implemented as follows:

function Addbranch (branch) {
This.branches[this.branches.length] = Branch;
}

function Writetree () {
var treestring = ';
var numbranches = this.branches.length;
for (Var i=0;i<>
Treestring + + this.branches[i].write ();
document.write (treestring);
}

The Addbranch () method joins the object passed by the parameter to the end of the branches array. The Writetree () method iterates through each object stored in the branches array, calling each object's write () method. Note that this takes advantage of the advantages of polymorphism: Regardless of the type of object the current element of the branches array is, we simply call the Write () method in a uniform way, and the actual write () method is determined by the type of the current element of the branches array- May be the write () method of the Branch object, or the Write () method of the Leaf object.

It's important to note that while the JavaScript array object allows you to save any type of data, we can only save objects that implement the Write () method. Pure object-oriented languages such as Java have robust type checking mechanisms to automatically report type errors, but JavaScript is a looser restriction, and we have to manually guarantee that objects saved to the branches array have the correct type.

V. Branch objects

The branch object is similar to the tree object:

function branch (ID, text) {
This.id = ID;
This.text = text;
This.write = Writebranch;
This.add = Addleaf;
this.leaves = new Array ();
}

The branch object's constructor has an ID and text two parameters. The ID is a unique identifier, and text is what appears after the folder in the branch. The leaves array is a collection of child elements of the branch object. Note The Branch object defines an essential write () method and can therefore be saved to the branches array of the tree object. Both the tree object and the branch object define the Write () and add () methods, so both methods are polymorphic. The following is a concrete implementation of the Add () and write () methods of the Branch object:

function Addleaf (leaf) {
This.leaves[this.leaves.length] = leaf;
}

function Writebranch () {
var branchstring =
' < span class= ' branch ' + ';
Branchstring + = ' >< img src= "http://www.webjx.com/htmldata/2005-03-06/closed.gif" id= "I ' + this.id + '" > "+ this . text;
Branchstring + = ' </span> ';
branchstring = ' < span class= ' leaf ' id= ';
Branchstring + = this.id + ' > ';
var numleaves = this.leaves.length;
for (var j=0;j< numleaves;j++) branchstring + = This.leaves[j].write ();
Branchstring + = ' </span> ';
return branchstring;
}

The Addleaf () function is similar to the Addbranch () function of the tree object, which joins the object passed in by the argument to the end of the leaves array.

The Writebranch () method first constructs the HTML string needed to display the branch, and then iterates through each object in the leaves array to invoke the Write () method of each object in the array. As with branches arrays, leaves arrays can only hold objects with the Write () method.

Six, the Leaf object

The leaf object is the simplest of three objects:

function leaf (text, link) {
This.text = text;
This.link = link;
This.write = Writeleaf;
}

The leaf object's Text property represents the text that you want to display, and the link property represents the links. As mentioned earlier, the Leaf object also defines the write () method, which is implemented as follows:

function Writeleaf () {
var leafstring = ' < a href= ' + This.link + ' > ';
Leafstring + = ' < img src= "http://www.webjx.com/htmldata/2005-03-06/doc.gif" border= "0" > ";
Leafstring + = This.text;
Leafstring + = ' </a>< br> ';
return leafstring;
}

The purpose of the Writeleaf () function is to construct an HTML string that displays the current node. The leaf object does not need to implement the Add () method because it is the endpoint of the branch and does not contain child elements.

Vii. assembling a tree-shaped control

The last thing to do is to assemble the tree control in the HTML page. The construction process is simple: Create a Tree object, and then add branch nodes and leaf nodes to the tree object. After the entire tree structure is constructed, the write () method of the tree object is invoked to display the TreeView. Here is a multi-layered tree structure, just add it to the tag to show the location of the tree control. Note that in the following example, wherever a link should be added, it is replaced by "#":

< script language= "JavaScript" >
var mytree = new Tree ();
var branch1 = new Branch (' Branch1 ', ' javascript reference book ');
var leaf1 = new Leaf (' Preface ', ' # ');
var leaf2 = new Leaf (' Introduction ', ' # ');
Branch1.add (LEAF1);
Branch1.add (LEAF2);
Mytree.add (BRANCH1);

var branch2 = new Branch (' Branch2 ', ' chapter I ');
Branch2.add (New Leaf (' first verse ', ' # '));
Branch2.add (The New Leaf (' Sect. II ', ' # '));
Branch2.add (The New Leaf (' sect. III ', ' # '));
Branch1.add (BRANCH2);

var Branch3 = new Branch (' Branch2 ', ' chapter II ');
Branch3.add (New Leaf (' first verse ', ' # '));
Branch3.add (The New Leaf (' Sect. II ', ' # '));
Branch3.add (The New Leaf (' sect. III ', ' # '));
Branch1.add (BRANCH3);

Mytree.add (The New leaf (' Contact us ', ' # '));
Mytree.write ();
</script>

The above code works as shown in Figure one. As you can see, the code that assembles the tree controls is fully compliant with the object-oriented style, simple and efficient.

In essence, a tree control constructed with object-oriented technology contains a set of objects, and this set of objects implements what is called an interface in a pure object-oriented language, but the interface is not clearly defined because of the limitations of the JavaScript language itself. For example, the tree control in this article is made up of three objects of trees, branch, and leaf, and each of these three objects implements the write interface, that is, all three objects have a write () method, and the Write () method of different objects provides different functionality depending on the type of object. For example, the tree and branch objects implement the Add interface, and two objects define the different behavior of the Add () method respectively according to their own needs. Thus, polymorphism is an important concept in object-oriented technology, which facilitates the construction of robust, scalable, reusable code.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.