1、通过dispatchEvent委托事件模式完成自定义事件:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
creationComplete="application1_creationCompleteHandler()"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<!-- 将非可视元素(例如服务、值对象)放在此处 -->
</fx:Declarations>
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.messaging.events.MessageEvent; protected function application1_creationCompleteHandler():void
{
this.addEventListener("Clicked",clickedHandler);
Alert.show(" creationComplete ","提示");
} private function clickedHandler(e:Event):void{
Alert.show("事件响应","提示");
} protected function button1_clickHandler():void
{
dispatchEvent(new Event("Clicked"));
Alert.show(" click ","提示");
} ]]>
</fx:Script>
<fx:Metadata>
[Event(name="Clicked",type="flash.events.Event")]
</fx:Metadata>
<s:Button x="102" y="29" label="按钮" enabled="true" width="85" height="35" click="button1_clickHandler()" />
</s:Application>
2、通过继承Event类是实现自定义事件:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark" creationComplete="application1_creationCompleteHandler(event)"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<s:layout>
<s:BasicLayout/>
</s:layout>
<fx:Script>
<![CDATA[
import com.flex.event.MyEvent; import mx.controls.Alert;
import mx.events.FlexEvent; protected function application1_creationCompleteHandler(event:FlexEvent):void
{
this.addEventListener(MyEvent.MYEVENT,eventHindler);
}
//自定义函数
private function eventHindler(e:MyEvent):void{
Alert.show("事件响应结果:"+e.getEventObj(),"提示");
} protected function button1_clickHandler(event:MouseEvent):void
{
var evt:MyEvent = new MyEvent(MyEvent.MYEVENT,122);
dispatchEvent(evt); //将事件发送出去
} ]]>
</fx:Script>
<fx:Declarations> </fx:Declarations>
<s:Button x="93" y="59" label="click me" click="button1_clickHandler(event)"/>
</s:Application>
MyEvent类定义:
package com.flex.event
{
import flash.events.Event; public class MyEvent extends Event
{
public static const MYEVENT:String="myevent";
private var eventObj:int;
public function MyEvent(type:String, i:int,bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
this.eventObj=i;
}
public function getEventObj():int{
return this.eventObj;
}
}
}