Set up the Branch Object
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 constructor includes
id and text properties. The
id property serves as the unique identifier for the document object written to the screen and the
text property represents the text to display next to the folder. The
leaves array is a collection of children the control displays for any branch node. Note that branch objects include the necessary
write() method to enable their storage in the
branches array of a tree object. Because both the tree and branch objects include
write() and
add() methods, those methods are polymorphic. Here are the implementations for
write() and
add():
function addLeaf(leaf){
this.leaves[this.leaves.length] = leaf;
}
function writeBranch(){
var branchString =
'<span class="branch" ' +
onClick="showBranch(\'' + this.id + '\')"';
branchString += '><img src="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 does the same thing as the
addBranch() function of the tree objectit appends the object passed to the method to the end of the
leaves collection.
The writeBranch() method first sets up the HTML string necessary for the display of the branch and then loops through the leaves array and calls the write() method of each object stored in the array. Once again, you can only store objects that implement a write() method in the leaves array.