Step 4: Implementing additional functions for Node

In the previous step I left an important implementation, it is important because every class visual or not must have it, it is called the constructor and it has the same as the class that is being implemented, in our case we have the following code for the constructor.

// Implement class constructor
public function Node(): void {
	super(); // always call the superclass constructor in aour case Canvas
		
	setStyle("backgroundImage", normalSkin); // Setting up the background image
	setStyle("backgroundSize", "100%"); // adjusting background image to the size of our control
	setStyle("backgroundAlpha", 0.8); // setting transparency for background image

	var fadeIn:Fade = new Fade(); // Effect for for rollover
	fadeIn.alphaFrom = 1.0;
	fadeIn.alphaTo = 0.7;
	fadeIn.duration = 500;

	var fadeOut:Fade = new Fade(); / Effect for rolout
	fadeOut.alphaFrom = 0.7;
	fadeOut.alphaTo = 1.0;
	fadeOut.duration = 500;

	// Setting up effects
	setStyle("rollOverEffect",fadeIn);
	setStyle("rollOutEffect",fadeOut);
}

Now, from the step 1 we conclude that each node has one parent and it may have children, to implement this we will declare a parent variable of the type Node and an array for the children, also we need to implement an addChild method to let our control create a new node and add it as a child of the current node.

public var parentNode:Node;
public var childNodes:Array;

// Implementing parents, childs association
public function addChildNode(child:Node):void{
	if(!childNodes){
		childNodes = [child];
	}
	else {
		childNodes.push(child);
	}
	child.parentNode = this;
}

Additionally from behavior in step 1 we conclude that we need a status variable for the selection, we will declare selected as boolean to do this and we will change it when the control is clicked, a function to deselect the node is also needed.

public var selected:Boolean = false;
// Event handlers
private function handleEventClick(objEvent:MouseEvent):void{
	// find the root node, we will deselect all the nodes and then set this instance as selected.
	var rootNode:Node = this;
	while(rootNode.parentNode){
		rootNode = rootNode.parentNode;
	}
			
	deselectNodes(rootNode);
			
	this.selected = true;
	this.setStyle("backgroundImage", activeSkin);
	invalidateDisplayList();
	dispatchEvent(new Event("nodeSelected") );
}
		
// deselect the node and its children
private function deselectNodes(node:Node):void{
	node.selected = false;
	node.setStyle("backgroundImage", normalSkin);
			
	node.invalidateDisplayList();
	if(node.childNodes){
		for( var iNode:int = 0; iNode < node.childNodes.length; iNode++){
			deselectNodes(node.childNodes[iNode] as Node);
		}
	}
}