AS3 | Flex | Programming

Encapsulating interactive behavior in Flex applications for better code readability

Consider for a moment dragging an element within an application. The steps required for this operation are as follows:

Behavior Description Event to listen for
START DRAGGING… When the mouse button is pressed down over the element. MouseEvent.MOUSE_DOWN
DRAG… While the mouse is moving and the mouse button is pressed down over the element. MouseEvent.MOUSE_MOVE
STOP DRAGGING… When the mouse button is released over the element. MouseEvent.MOUSE_UP
When the mouse is moved outside the stage (e.g. outside the application window). This is necessary because we cannot determine whether the mouse button has been released while the mouse is outside the application window. Event.MOUSE_LEAVE

Adobe Flex’s event model makes it easy to listen for interactive mouse events within an application. A simple operation like a mouse click only requires listening for a MouseEvent.CLICK event being dispatched from the element in question, like so:

element.addEventListener( MouseEvent.CLICK , _element_clickHandler );
protected function _element_clickHandler( event:MouseEvent ) : void
// handle click on element

While handling a mouse click is simple enough to do, more complex interactive behavior such as dragging requires listening to multiple events from both the element in question as well as the stage. Implementing this behavior can clutter your code and not be as clear as it could be, since there is not a dragging event to listen for natively in Flex (Drag and Drop aside).

An alternative is to encapsulate the dragging behavior in a separate class that acts as a proxy for the element and issues its own events that the main application listens for. For example:

var behavior:DraggableBehavior = new DraggableBehavior(element);
element.addEventListener( DraggableBehaviorEvent.DRAGGING , _element_draggingHandler );
protected function _element_draggingHandler( event:DraggableBehaviorEvent ) : void
// handle dragging of element

This moves all the event handling methods and listeners to a separate class file, organizing your code better. It also creates an event that more accurately reflects what operation is going on.


This movie requires Flash Player 9

Download Source Here