Javascript object-oriented technology to achieve tree-like control stickers)

Source: Internet
Author: User

The tree control has a unique ability to expand and collapse branches. It can display a large amount of information in a small space and clearly convey the hierarchical relationship between data. Users familiar with graphic user interfaces can use tree controls freely.


Figure 1: tree control implemented by JavaScript

HTML itself does not support tree controls, but we can use some Javascript script code. To improve the reusability of controls, we must make full use of JavaScript to support object-oriented programming technology. The tree control in this article applies to IE 4 + and Netscape 6.x. it should be said that it already covers mainstream browsers.

I. JavaScript and object-oriented

Object-Oriented Programming has three basic concepts: inheritance, encapsulation, and polymorphism. Inheritance and encapsulation are easy to understand. In contrast, polymorphism is difficult to grasp and use. In general, polymorphism refers to the ability to present in multiple forms. In object-oriented programming, polymorphism represents the ability of a programming language to take different processing methods based on the data types or classes of objects.

In a "pure" object-oriented language, such as Java, polymorphism is generally inseparable from class inheritance. That is to say, a type of hierarchy must be defined. The abstract class at the top and various specific implementations at the bottom. Abstract Classes define methods that must be implemented or overwritten by subclasses. Different subclasses overwrite abstract classes in different ways as needed.

For example, the formula for calculating the circular area and the rectangular area is completely different. According to the object-oriented design idea, we must first define an abstract class shape, and the sharp class has a findarea () method, all subclasses derived from the shape class must implement the findarea () method. Then, we define a rectangle class that represents the rectangle and a circle class that represents the circle. Both classes inherit from the shape class. The rectangle class and the circle class implement the findarea () method respectively. The two use different calculation formulas to calculate the area. Eventually, the findarea () method can be called in the same way no matter which type of Child class (rectangle or circle) the object belongs to the shape, you do not need to worry about the formula used by the called findarea () to calculate the area, so as to effectively hide the implementation details.

The javascript language does not support class-based inheritance, but it still supports polymorphism. Javascript inheritance is prototype-based inheritance. In fact, as shown in the example in this article, this inheritance method simplifies the compilation of the polymorphism method, and in terms of structure, the final program is very similar to that of the pure object-oriented language.

2. Preparations

The entire tree control consists of four parts: graphics, CSS style definition, HTML framework code, and JavaScript code. ).

The following is the CSS style definition used by the tree control:

<Style>
Body {
Font: 10pt, 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>

The CSS rule is simple: the body rule sets the font and foreground (text) color of the document. The purpose of the branch rule is: when the mouse goes through a node with a subnode, the pointer turns into a hand shape. Two cursor attributes must be defined because IE and Netscape use different attribute names. Set the display attribute to none in the leaf rule to achieve the folding Effect of leaf nodes (final nodes without child nodes. In the script code, we set the display attribute to block to show the node and set it to none to hide the node.

Iii. Script Design

The tree control implemented in this article contains a tree object. The tree object has a branches sub-object set, and each branch (Branch) object has a set of sub-objects. Sub-objects can be branch objects or leaf (leaf) objects. All three objects implement a write () method with a single polymorphism. The write () method of different objects performs different operations based on their own objects, that is, the write () method of the tree object () the method is different from the write () method of the branch object. The write () method of the branch object is different from the write () method of the leaf object. In addition, the tree and branch objects each have an add () method to add sub-objects to their respective objects.

Add the following code to the HTML document. The purpose of this Code is to create two image objects, which correspond to the folder graphics in the open and folding status of the branch respectively. There are also several tool functions used to open or collapse sub-elements of any branch, and change the folder chart accordingly according to the opening or folding status of the branch.

<Script language = "JavaScript">
VaR openimg = new... asset not found ..;
Openimg. src = "open.gif ";
VaR closedimg = new... asset not found ..;
Closedimg. src = "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('closed.gif ')>-1)
Objimg. src = openimg. SRC;
Else
Objimg. src = closedimg. SRC;
}
</SCRIPT>

The code is preloaded with graphical objects, which improves the display speed in the future. The showbranch () function first obtains the branch style provided by the parameter, judges and switches the display attribute of the current style (switches back and forth between block and none), thus forming the extension and folding effect of the branch. The principle of the swapimage () function is basically the same as that of the showbranch () function. It first judges the graph of the current branch (the opened folder or the collapsed folder), and then switches the graph.

4. Tree object

The following is the tree object constructor:

Function tree (){
This. Branches = new array ();
This. Add = addbranch;
This. Write = writetree;
}

The tree object represents the root of the entire tree structure. The tree () constructor creates the branches array, which is used to save all child elements. The ADD and write attributes are pointers to two polymorphism methods. The implementation of the two polymorphism methods is 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 adds the object passed in the parameter to the end of the branches array. The writetree () method traverses every object stored in the branches array and calls the write () method of each object. Note that the advantages of polymorphism are used here: No matter what type of object the current element of the branches array is, we only need to call the write () method in a uniform way and actually execute the write () method () the method is determined by the type of the current element in the branches array. It may be the write () method of the branch object or the write () method of the leaf object.

It must be noted that although the array object of javascript can save any type of data, we can only save the objects that implement the write () method. A pure object-oriented language like Java has a robust type check mechanism that can automatically report type errors. However, JavaScript imposes loose restrictions, we must manually ensure that the objects saved to the branches array have the correct type.

5. Branch object

Branch objects are similar to tree objects:

Function Branch (ID, text ){
This. ID = ID;
This. Text = text;
This. Write = writebranch;
This. Add = addleaf;
This. Leaves = new array ();
}

The branch object constructor has two parameters: ID and text. ID is a unique identifier. Text is the text displayed after the folder of the branch. The leaves array is a set of child elements of the branch object. Note that the branch object defines an essential write () method, so it can be saved to the branches array of the tree object. Both the tree object and branch object define the write () and add () methods, so these two methods are polymorphism. The following describes how to implement the add () and write () Methods of branch objects:

Function addleaf (leaf ){
This. Leaves [This. Leaves. Length] = leaf;
}

Function writebranch (){
VaR branchstring =
'<SPAN class = "branch"' + onclick = "showbranch (/'' + this. ID + '/')"';
Branchstring + = '> ' + 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. It adds the objects passed in through parameters to the end of the leaves array.

The writebranch () method first constructs the HTML string required to display the branch, then cyclically traverses every object in the leaves array, and calls the write () method of each object in the array. Like the branches array, the leaves array can only save objects with the write () method.

Vi. Leaf object

The leaf object is the simplest of the three objects:

Function leaf (text, link ){
This. Text = text;
This. Link = link;
This. Write = writeleaf;
}

The text attribute of the leaf object indicates the text to be displayed, and the link attribute indicates the link. As mentioned above, the leaf object must also define the write () method. Its implementation is as follows:

Function writeleaf (){
VaR leafstring = '<a href = "' + this. Link + '"> ';
Leafstring + = ' ';
Leafstring + = This. text;
Leafstring + = '</a> <br> ';
Return leafstring;
}

The writeleaf () function is used 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 end point of the branch and does not contain child elements.

7. Assemble tree controls

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 add branch nodes and leaf nodes to the tree object. After constructing the entire tree structure, call the write () method of the tree object to display the tree control. The following is a multi-layer tree structure. You only need to add it to the tag to display the position of the tree control. Note that in the following example, all links should be replaced:

<Script language = "JavaScript">
VaR mytree = new tree ();
VaR branch = new branch ('branch', 'javascript reference book ');
VaR leaf1 = new leaf ('Preface ','#');
VaR leaf2 = new leaf ('Introduction ','#');
Branch1.add (leaf1 );
Branch1.add (leaf2 );
Mytree. Add (branching );

VaR branch2 = new branch ('branch2', 'Chapter 1 ');
Branch2.add (new leaf ('1100 ','#'));
Branch2.add (new leaf ('section 2 ','#'));
Branch2.add (new leaf ('section 3 ','#'));
Branch1.add (branch2 );

VaR branch3 = new branch ('branch2', 'Chapter 2 ');
Branch3.add (new leaf ('1100 ','#'));
Branch3.add (new leaf ('section 2 ','#'));
Branch3.add (new leaf ('section 3 ','#'));
Branch1.add (branch3 );

Mytree. Add (new leaf ('Contact Us ','#'));
Mytree. Write ();
</SCRIPT>

The running effect of the above Code is as follows. As you can see, the code for assembling the tree control fully conforms to the object-oriented style and is simple and efficient.

Essentially, tree controls constructed using object-oriented technology contain a set of objects, and these objects implement interfaces in a pure object-oriented language, the interface is not clearly defined due to the limitations of the Javascript language. For example, the tree control in this article consists of three objects: Tree, branch, and leaf, and these three objects all implement the write interface. That is to say, all three objects have a write () the write () method of different objects provides different functions based on different object types. For example, the tree and branch objects implement the Add interface. The two objects define different actions of the add () method based on their own needs. It can be seen that polymorphism is an important concept in object-oriented technology. It facilitates the construction of robust, scalable, and reusable code.

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.