Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Build an Object-Oriented Tree Control Using JavaScript : Page 6

When you need to display hierarchical information in your Web pages, build this Explorer-like tree control by creating only three polymorphic JavaScript objects.


advertisement
Build the Tree
The only thing left to do is to build the tree on the page. The process is simple: Create a tree object and add branches and/or leaves to it. Then add as many sub-branches and/or leaves as you'd like. When you've finished building the tree, call the tree object's write() method to display it on the screen. Here's an example tree that's three levels deep. Add the following script between the body tags in an HTML page:

<!-- place the tree building script where you'd like in the body --> <script language="JavaScript"> var myTree = new tree(); var branch1 = new branch('branch1','Branch 1'); var leaf1 = new leaf('Leaf 1','#'); var leaf2 = new leaf('Leaf 2','#'); branch1.add(leaf1); branch1.add(leaf2); var branch2 = new branch('branch2','Branch 2'); var leaf3 = new leaf('Leaf 3','#'); branch2.add(leaf3); branch1.add(branch2); myTree.add(branch1); var branch3 = new branch('branch3','Branch 3'); branch3.add(new leaf('Leaf 4','#')); branch2.add(branch3); var branch4 = new branch('branch4','Branch 4'); branch4.add(new leaf('Leaf 5','#')); branch1.add(branch4); var branch5 = new branch('branch5','Branch 5'); branch5.add(new leaf('Leaf 6','#')); myTree.add(branch5); myTree.add(new leaf('Leaf 7','#')); myTree.write(); </script>

Essentially, the object-oriented tree is a set of objects that implement what class-based inheritance languages usually term an interface. There are three objects (tree, branch, leaf) that implement the write interfacethat is, they all include a write() method that supplies the behavior needed by the object based on its type. In addition, two of the objects (tree, branch) implement the add interface by supplying add() methods that work for their own respective object types.

Polymorphism represents a powerful object-oriented principle that allows for the creation of robust and scalable systems. Using polymorphism lets you separate object design from object implementation. In other words, you can say that trees, branches, and leaves should each have a write() method (design) but that each is written differently (implementation).




Tom Duffy , DevX's JavaScript Pro, is an Associate Professor at Norwalk Community College, Norwalk, CT where he teaches Web Development and Java. Tom is also the Manager of the NCC Ventures Lab, the College's in-house web design studio. You can reach him via e-mail at: tduffy@ncc.commnet.edu.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap