天天看点

Flex3自定义事件(笔记)

Flex事件如此强大,原因是允许开发人员创建并使用自定义事件与应用程序进行通信。

通过在数据变化或者用户执行某些操作时发送事件,可以实现应用程序逻辑与使用这些逻辑的

对象的分离,有助于应用程序结构的模块化,即使一个组件发生改变也不会影响其他部分。

先学习一下Flex事件机制。

1.使用分派程序发送事件,

使用dispatchEvent()方法。

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" creationComplete="init()">

<mx:Script>
 <![CDATA[
  import mx.controls.Alert;
  
                //creationComplete在MXML组件初始化完毕之后触发init()
  //给myButton控件添加一个监听
  //当监听到有一个名为"onClickbutton"的事件时就触发responseToEvent方法。
  private function init():void{
   this.mybutton.addEventListener("onClickbutton",responseToEvent);
  }
  
  private function responseToEvent(event:Event):void{
   Alert.show("type:"+event.type);
  }

  //单击按钮myButton时,会派发事件
  private function doevent():void{
   mybutton.dispatchEvent(new Event("onClickbutton"));
   
  }
  
 ]]>
</mx:Script>

 <mx:Button id="mybutton" label="触发事件" fontSize="36" click="doevent()"/>
 
</mx:Application>

           

接下来自定义事件的学习

2.创建自定义事件

新建一个Flex project之后呢,在src文件夹下,新建一个floder名字是ac吧(可以自己随便起个名字)。new ActionScript Class,在弹出窗口中填写自定义事件类的名字

例如:MyCustomEvent  选择 Generate constructor from superclass复选框, 会自动帮我们生成大部分代码。

然后继续根据需要完善代码如下:

package ac
{
 import flash.events.Event;

 public class MyCustomEvent extends Event
 {
  //给自定义事件类型起个名字,相当于Event.MouseOver(MouseOver就是Event的type)
  //"customEventType"就是自定义事件的type名字
  public static var CUSTOMEVENTTYPE:String = "customEventType";

  public var info:String ;
  
  //可以在构造函数中加入自己的参数,便于前后台进行数据交换啊
  public function MyCustomEvent(info:String ,type:String, bubbles:Boolean=false, cancelable:Boolean=false)
  {
   super(type, bubbles, cancelable);
   this.info = info;
  }
  
 }
}


           

event.mxml代码如下:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal" creationComplete="init()">

<mx:Script>
 <![CDATA[
  //记得引入自定义事件所在的包 哦。。。
  import ac.MyCustomEvent;
  import mx.controls.Alert;
  
  private function init():void{
   //给mybutton添加监听事件,事件类型type是"customEventType"(表示自定义类型的事件啦)
   //此处的"customEventType"也可以写MyCustomEvent.CUSTOMEVENTTYPE。等价的。
   this.myButton.addEventListener("customEventType",responseToEvent);
  }
  
  private function responseToEvent(event:MyCustomEvent):void{
   Alert.show("the message:"+event.info);
   
  }
  
  private function doEvent(info:String):void{
   //派发事件,new一个自定义事件,记住参数的顺序不要弄乱了
   myButton.dispatchEvent(new MyCustomEvent(info,MyCustomEvent.CUSTOMEVENTTYPE));
  }
  
 ]]>
</mx:Script>
 <mx:Button  id="myButton" label="触发自定义事件" fontSize="16" click="doEvent('this click')"/>
 
</mx:Application>

           

单击按钮之后弹出Alert窗口。

继续阅读