基於鬆耦合的概念 自定義事件類型將取到很重要的做用 java
當您建立本身的自定義 Event 類時,必須覆蓋繼承的 Event.clone() 方法,以複製自定義類的屬性。若是您未設置在事件子類中添加的全部屬性,則當偵聽器處理從新分派的事件時,這些屬性將不會有正確的值。 ide
自定義事件類 繼承flash.events.Event類 下面看代碼 其中 message 是自定義的屬性, 下面要使用這個屬性 來傳遞參數 flex
- package com.demo.event
- {
- import flash.events.Event;
-
- public class TestEvent extends Event
- {
- public static const EVENT_CLICK:String = "copy_text";
-
- public var message:String;
-
- public function TestEvent(type:String, message:String)
- {
- super(type);
- this.message = message;
- }
-
- override public function clone():Event{
-
- return new TestEvent(type,message);
-
- }
- }
- }
接下來創建一個控件 來指派這個事件
註冊事件 CopyText this
<fx:Metadata>
[Event(name="CopyText",type="com.demo.event.TestEvent")]
</fx:Metadata>
指派事件 spa
protected function button1_clickHandler(event:MouseEvent):void
{
dispatchEvent(new TestEvent("CopyText",tempText.text));
} .net
- <?xml version="1.0" encoding="utf-8"?>
- <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
- xmlns:s="library://ns.adobe.com/flex/spark"
- xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300">
- <s:layout>
- <s:BasicLayout/>
- </s:layout>
- <fx:Metadata>
- [Event(name="CopyText",type="com.demo.event.TestEvent")]
- </fx:Metadata>
-
- <fx:Script>
- <!--[CDATA[
- import com.demo.event.TestEvent;
- protected function button1_clickHandler(event:MouseEvent):void
- {
- dispatchEvent(new TestEvent("CopyText",tempText.text));
- }
- ]]-->
- </fx:Script>
-
- <fx:Declarations>
- <!-- 將非可視元素(例如服務、值對象)放在此處 -->
- </fx:Declarations>
- <s:TextInput x="10" y="10" height="107" width="260" id="tempText"/>
- <s:Button x="14" y="124" label="Copy" click="button1_clickHandler(event)"/>
- </s:Group>
最後將這個控件放到主程序中, 並使用了這個自定義事件 component
- <?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"
- xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:components="com.demo.view.components.*">
- <s:layout>
- <s:BasicLayout/>
- </s:layout>
- <fx:Script>
- <!--[CDATA[
- import com.demo.event.TestEvent;
-
- protected function testforms1_CopyTextHandler(event:TestEvent):void
- {
- this.t.text = event.message;
- }
-
- ]]-->
- </fx:Script>
- <fx:Declarations>
- <!-- 將非可視元素(例如服務、值對象)放在此處 -->
- </fx:Declarations>
- <components:testForms x="23" y="28" CopyText="testforms1_CopyTextHandler(event)">
- </components:testForms>
- <s:TextInput x="440" y="28" width="227" height="184" id="t"/>
- </s:Application>