2009年8月23日 星期日

ActionScript3 自定義事件使用

//客制化事件物件
package customEvent
{
  import flash.events.Event;

  public class CustomEvent extends Event
  {
    //事件名稱
    static public const ATTRIBUTE_CHANGED:String = "attributeChanged";
    //建構式
    public function CustomEvent(
      type:String,
      newAttribute:Object=null, oldAttribute:Object=null,
      bubbles:Boolean=false, cancelable:Boolean=false)
    {
       super(type, bubbles, cancelable);
       this.newAttribute = newAttribute;
       this.oldAttribute = oldAttribute;
    }

    //新的屬性值

    private var _newAttribute:Object;
    public function get newAttribute():Object
    {
  return _newAttribute;
    }
    public function set newAttribute(value:Object):void
    {
     _newAttribute = value;
    }

    //舊的屬性值
    private var _oldAttribute:Object;
    public function get oldAttribute():Object
    {
  return _oldAttribute;
    }
    public function set oldAttribute(value:Object):void
    {
  _oldAttribute = value;
    }

    override public function  clone():Event
    {
    return new CustomEvent(type , newAttribute, oldAttribute , bubbles , cancelable);
    }
   }
}


//測試程式
package
{
import customEvent.CustomEvent;
import flash.display.Sprite;
import flash.events.MouseEvent;
public class ActionScript_Test extends Sprite
{
private var btn:Sprite;
private var color:uint = 0xff3366;
public function ActionScript_Test()
{
  //畫一個圓角矩形用來發事件
  btn = new Sprite();
  btn.x = 0;
  btn.y = 20;
  drawButton();
  //加入滑鼠事件偵聽
  btn.addEventListener(MouseEvent.CLICK , onClickHandler);

  //加到stage中
  this.addChild(btn);

  //加入偵聽式
  this.addEventListener(CustomEvent.ATTRIBUTE_CHANGED , feeback);
}

private function drawButton():void
{
  btn.graphics.clear();
  btn.graphics.beginFill(color,0.8);
  btn.graphics.drawRoundRect(0,0,100,30,5,5);
  btn.graphics.endFill();
}


//滑鼠點擊事件
public function onClickHandler(e:MouseEvent):void
{
  var event:CustomEvent = new CustomEvent(CustomEvent.ATTRIBUTE_CHANGED,0x6666cc,color);
  //發送事件
  this.dispatchEvent(event);
}

//客制化事件處理
public function feeback(e:CustomEvent):void
{
color = (e.newAttribute as uint);
drawButton();
}
}

}

沒有留言:

張貼留言