MyButton class

Adding functionality to a button

We now have placed a button on stage, but it is lacking functionality. Our aim is to create another button, which is actually a child button. This means, when we move the parent button the child will also move.

We again import similar classes as before. The constructor has two parameters for the positioning of the button. We use the same event listeners as in the former script for this button, too.

package
{
	import flash.events.MouseEvent;
	import flash.display.MovieClip;
	import flash.text.TextField;
	public class MyButton extends MovieClip
	{
	       public function MyButton (xpos:uint, ypos:uint)
	       {
	               this.x = xpos;
	               this.y = ypos;
	               this.buttonMode = true;
	               this.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
	               this.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
	       }

We also have a function, when the mouse is pressed. However, now we need to disconnect the previous mouse downhandler from the one for the button. We want to have complete focus on only the button. To achieve that we trigger the "stopPropagation" method. This method will turn off the mouse eventhandler for the stage as long as the mouse is placed over the button. The rest of the script is just some function to drag the button and to add some text when pressed.

	       private function mouseDownHandler(event:MouseEvent):void
	       {
	               event.stopPropagation ();
	               trace("myButton mousedown");
	               this.startDrag();
	               var myText:TextField = new TextField();
	               myText.text = "Press the \nchild. \nDrag child.";
	               myText.mouseEnabled = false;
	               myText.width = this.width;
	               myText.height = this.height;
	               this.addChild(myText);
	               var child:ChildButton = new ChildButton (10, 50);
	               this.addChild(child);
	       }
	       private function mouseUpHandler(event:MouseEvent):void
	       {
	               event.stopPropagation ();
	               trace("myButton mouseup");
	               this.stopDrag();
	       }
	}
}

Next we will give the child button, which is placed on stage when the parent button is pressed, some function.

previous  |  next