Flex中自訂事件

來源:互聯網
上載者:User

       事件是一個非常有用的功能,通常用於資訊傳遞互動大大提高程式編寫的靈活性。在進階語言中都會整合這方面特性;Flex也不例外幾乎所有控制項中都整合了大量的事件,如果Button的Click事件等。但實際應用中控制項自有的事件是不能滿真實需要的,特別在自己編寫自訂控制項時,自訂控制項內部資訊的改變如何及時通知所在的容器變得很更要;這個時候自訂事件就起到它的作用。

       在Flex中定義事件有兩中情況,分別是ActionScript和MXML中定義。

       在ActionScript中定義:

       [Event(name="myEnableEvent", type="flash.events.Event")]

public class MyComponent extends UIComponent

{

           ...

}

在MXML中定義:

<mx:Metadata>

    [Event(name="DataChange", type="DataChangeEvent")]

</mx:Metadata>

 

DataChangeEvent事件參數的定義:

import flash.events.Event;

public class DataChangeEvent extends flash.events.Event

{

       public function DataChangeEvent()

       {

              super("DataChange");

       }

       public var Data:Object;

}

 

在自訂控制項中定義和觸發事件:

<?xml version="1.0" encoding="utf-8"?>

<mx:Form xmlns:mx="http://www.adobe.com/2006/mxml" width="212" height="56">

 <mx:Metadata>

        [Event(name="DataChange", type="DataChangeEvent")]

    </mx:Metadata>

 <mx:Button label="Button" click="Change()"/>

       <mx:Script>

              <![CDATA[

                     function Change():void

                     {

                            this.dispatchEvent(new DataChangeEvent());

                     }

              ]]>

       </mx:Script>

</mx:Form>

 

容器接收相關自訂控制項事件:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="*">

      

       <ns1:EmployeeCombo x="146" y="132" DataChange="onChange(event)" >

       </ns1:EmployeeCombo>

       <mx:Script>

              <![CDATA[

                     import mx.controls.Alert;

                     function onChange(e:DataChangeEvent)

                     {

                           

                     }

              ]]>

       </mx:Script>

</mx:Application>

 

其實自訂事件的現實也很簡單,但起著非常重要的作用;正是因為有了事件的機制,使得大部分重複的功能抽取到自訂控制項中,從而達到一個很高的代碼重用性。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.