1. 程式人生 > >flex自定義元件與自定義事件

flex自定義元件與自定義事件

今天研究了一下flex自定義控制元件與事件,成功!過程詳細如下:

1,首先新建一個mxml元件檔案,各個引數自己填寫。

<?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" >
	<fx:Script>
		<![CDATA[
			import mx.events.FlexEvent;
			//定義需要給這個自定義元件傳入的屬性值
			[Bindable]
			public var imgPath:String;
			[Bindable]
			public var imgName:String;

			//自定義元件中,某一個控制元件的事件,
			protected function UserImg_clickHandler(event:MouseEvent):void
			{
				// TODO Auto-generated method stub
				//通過元件的事件,建立自定義的事件,   並分發(廣播)事件;當點選圖片時就觸發了這一事件 
				this.dispatchEvent(new customEvent(customEvent.eventName,imgName));
			}

		]]>
	</fx:Script>
	<fx:Metadata>
		//由於是自定義的元件,如何知道它有哪些事件-----通過元資料     
		//以下據表明:本元件custonImage有一個imgClicked事件(在下文中宣告的事件名稱),,類似與Button元件的click事件,   
		// 型別為customEvent(在下文中宣告的事件型別),類似於Button的MouseEvent 
		[Event(name="imgClicked", type="compent.customEvent")]
	</fx:Metadata>

	<fx:Declarations>
		<!-- 將非可視元素(例如服務、值物件)放在此處 -->
	</fx:Declarations>
	<s:Image id="UserImg" width="100%" height="100%" scaleMode="stretch"  source="{imgPath}" click="UserImg_clickHandler(event)"/>
</s:Group>


2,新建一個ActionScript類檔案,定義名稱,選擇超類為“flash.events.Event”,

package compent
{
	import flash.events.Event;
	
	//定義事件型別
	public class customEvent extends Event
	{
		//定義事件名稱
		public static const eventName:String="imgClicked";
		//定義事件需要傳出的引數
		public var imgNameStr:String; 
		public function customEvent(type:String,$data:String=null, bubbles:Boolean=false, cancelable:Boolean=false)
		{
			super(type, bubbles, cancelable);
			this.imgNameStr=$data;
		}
	}
}


3,自定義元件與事件的引用

protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
	img.imgPath="toolsPng/pageLeft.png";
	img.imgName="zk";
	img.addEventListener(customEvent.eventName,showImgName);
}
function showImgName(e:customEvent):void
{
	Alert.show(e.imgNameStr);
}
<compent:customImage id="img" x="696" y="354" width="200" height="100"/>