Flex组件组件添加自定义事件

主要注意的就是要在<fx:Metadata>中来定义事件,这样在外部才能添加此事件的监听。

自定义组件如下:com.cp2
<?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="254" height="218">
	<s:layout>
		<s:BasicLayout/>
	</s:layout>
	
	<fx:Metadata>
		/* 在这里定义事件  */
		[Event(name="shareData",type="flash.events.TextEvent")]
		[Event(name="clickMe",type="flash.events.Event")]
	</fx:Metadata>
	
	<fx:Script>
		<![CDATA[
			protected function button1_clickHandler(event:MouseEvent):void
			{
				var textEvent:TextEvent=new TextEvent("shareData");
				textEvent.text="hello world.";//传递简单的参数
				dispatchEvent(textEvent);			
			}

			protected function button2_clickHandler(event:MouseEvent):void
			{
				dispatchEvent(new TextEvent("clickMe"));	//不传递参数	
			}

			protected function button3_clickHandler(event:MouseEvent):void
			{
				this.owner.dispatchEvent(new Event("clickMeToo"));
			}
		]]>
	</fx:Script>

	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>
	<s:Button x="40" y="10" label="单击我(传递参数)" width="190" height="45" click="button1_clickHandler(event)"/>
	<s:Button x="39" y="74" label="单击我" width="190" height="37" click="button2_clickHandler(event)"/>
	<s:Button x="39" y="139" label="按钮" width="190" height="35" click="button3_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:com="com.*"
			   creationComplete="application1_creationCompleteHandler(event)">
	
	<fx:Script>
		<![CDATA[
			import mx.controls.Alert;
			import mx.events.FlexEvent;

			protected function application1_creationCompleteHandler(event:FlexEvent):void
			{
				//this.addEventListener("clickMeToo",handler1);//因为在cp1里,发送事件的是cp1.owner.因此,此处添加监听无效,应该是直接、第一个拥有着
				bc.addEventListener("clickMeToo",handler1);
				cpID.addEventListener("shareData",handler);
			}
			private function handler(event:TextEvent):void{
				Alert.show("增加监听的方式 ,并传递参数。"+event.text);
			}
			
			private function handler1(event:Event):void{
				Alert.show("增加监听的方式 ");
			}
			protected function xxx_shareDataHandler(event:TextEvent):void
			{
				Alert.show(event.text);
			}

			//在组件中添加事件监听
			protected function cpID_clickMeHandler(event:Event):void
			{
				Alert.show("事件传递成功");
			}
		]]>
	</fx:Script>
	<fx:Declarations>
		<!-- 将非可视元素(例如服务、值对象)放在此处 -->
	</fx:Declarations>
	<s:BorderContainer id="bc" x="141" y="38" width="299" height="303" borderColor="#A10F0F" dropShadowVisible="true" chromeColor="#B19191" contentBackgroundColor="#FFFFFF" borderWeight="4" rollOverColor="#164FA4">
		<com:cp2 x="22" y="31" id="cpID" clickMe="cpID_clickMeHandler(event)" >
		</com:cp2>
	</s:BorderContainer>

</s:Application>

另外可自定义事件,传递复杂参数

你可能感兴趣的:(Flex组件组件添加自定义事件)