flex中Event类的使用
当您创建自己的自定义 Event 类时,必须覆盖继承的 Event.clone() 方法,以复制自定义类的属性。如果您未设置在事件子类中添加的所有属性,则当侦听器处理重新分派的事件时,这些属性将不会有正确的值。
自定义事件类 继承flash.events.Event类 下面看代码 其中 message 是自定义的属性, 下面要使用这个属性 来传递参数
- 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
<fx:Metadata> [Event(name="CopyText",type="com.demo.event.TestEvent")] </fx:Metadata> 指派事件
protected function button1_clickHandler(event:MouseEvent):void { dispatchEvent(new TestEvent("CopyText",tempText.text)); }
- <?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>
最后将这个控件放到主程序中, 并使用了这个自定义事件
- <?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>