Pages

Tuesday, March 20, 2012

AS3: Custom Button Controller


Here is the pseudo code for the flash application architecture of custom-button movieclip.
<movieclip name="controller_mc">
 <frameset>
  <frame name="normal">
   <textfield name="caption" framespan="4"></textfield>
   <graphics color="#333333"></graphics>
  </frame>
  <frame name="over">
   <graphics color="#666666"></graphics>
  </frame>
  <frame name="down">
   <graphics color="#999999"></graphics>
  </frame>
  <frame name="disabled">
   <graphics color="#333333" alpha="0.7"></graphics>
  </frame>  
 </frameset>
</movieclip>
The controller class of the custom button.
package com.engine 
{
 import flash.display.MovieClip;
 import flash.events.MouseEvent;
 /**
  * @file CButton.as
  * @author Abhishek Kumar
  */
 public class CButton 
 {
  private var container:MovieClip;
  private var proceed:Function;
  
  public function CButton(mc:MovieClip, fn:Function) 
  {
   container = mc;
   proceed = fn;
   
   initialize();
  }
  
  private function initialize():void
  {   
   container.gotoAndStop('up');
   container.buttonMode = true;
   container.mouseChildren = false;
  }
  
  public function attachListeners():void
  {
   container.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
   container.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
   container.addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
   container.addEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
  }
  
  public function detachListeners():void
  {
   container.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
   container.removeEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
   container.removeEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
   container.removeEventListener(MouseEvent.MOUSE_OUT, onMouseOut);
  }
  
  private function onMouseUp(me:MouseEvent):void
  {
   container.gotoAndStop('up');
   proceed(me.target);
  }
  
  private function onMouseDown(me:MouseEvent):void
  {
   container.gotoAndStop('down');
  }
  
  private function onMouseOver(me:MouseEvent):void
  {
   container.gotoAndStop('over');
  }
  
  private function onMouseOut(me:MouseEvent):void
  {
   container.gotoAndStop('up');
  }
  
  public function show():void
  {
   container.visible = true;
  }
  
  public function hide():void
  {
   container.visible = false;
  }
  
 }

}

No comments:

Post a Comment