FreeLayoutContainer [Part 2]

In my previous post, I had created a basic container in Flex within which any child DisplayObject was draggable. The demo was a little sluggish and not very responsive while dragging the objects around. Well…. There was a much simpler way to achieve this.

Using the startDrag() and stopDrag() functions.

package com.jeethukarthik.containers
{
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import mx.containers.Canvas;
	public class FreeLayoutContainer extends Canvas
	{
		public function FreeLayoutContainer()
		{
			super();
		}
		override public function addChild(child:DisplayObject):DisplayObject{
			//Call the super class method.
			super.addChild(child);
			//Set the event listeners
			child.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
			child.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			//Resturn the display object
			return child;
		}
		protected function onMouseDown(e:MouseEvent):void {
			//Bring the currently clicked child to the top of the Display stack
			setChildIndex(e.currentTarget as DisplayObject, numChildren-1);
			//Start Dragging the target
			e.currentTarget.startDrag();
		}

		//Stop dragging the target
		protected function onMouseUp(e:MouseEvent):void {
			e.currentTarget.stopDrag();
		}
	}
}

Chucks! Was that easy or what? The dragging will be much responsive now.

Should’ve figured that out in the first place. Alright…I’ve decided not to keep this blog sleeping all the time and so, I will make time to post at least one post a week. Oh yeah! Believe that!

Leave a Reply


Creative Commons License