自定义组件与自定义事件(组件的数传递)
自定义组件与自定义事件(组件的数传递)
1.新建一个Flex工程 File-New-Flex Project
2.为工程命一个名字(如:CustomComponent)
3.在Flex Navigator视图下展开CustomComponent – src 右击src文件夹新建一个文件夹components
4.新建一个组件 File – new – MXML component 如命为MyIntroduce 路径为CustomComponent/src/components
5.打开MyIntroduce.mxml为组件添加属性和控件并做简单的数据绑定
<?xml version="1.0" encoding="utf-8"?><mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"><mx:Script><![CDATA[/** * 为组件添加两个属性 */[Bindable]public var myName:String;[Bindable]public var myPosition:String;]]></mx:Script><mx:Label text="名字:"/><mx:TextInput id="myname" text="{myName}"/><mx:Label text="职位:"/><mx:TextInput id="myposition" text="{myPosition}"/><mx:Button label="确定" id="ok"/></mx:VBox>
<?xml version="1.0" encoding="utf-8"?><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="components.*" initialize="initApp()"><mx:Script><![CDATA[private function initApp():void{introduce.myName="中国星";introduce.myPosition="Manager";}]]></mx:Script><ns1:MyIntroduce x="364" y="51" id="introduce"></ns1:MyIntroduce></mx:Application>
package com.zkl.events{import flash.events.Event;public class CustomEvent extends Event{public static const EVENT_TYPE:String="event_type";public var id:int;public var myname:String;public var myposition:String;public function CustomEvent(type:String, id:int, myname:String,myposition:String, bubbles:Boolean=false, cancelable:Boolean=false){super(type, bubbles, cancelable);this.id=id;this.myname=myname;this.myposition=myposition;}override public function clone():Event{return new CustomEvent(type,id,myname,myposition,bubbles,cancelable);}}}
package com.zkl.events{public class CustomEventId{public static const COMPONENT_EVENT:int=0;}}
<?xml version="1.0" encoding="utf-8"?><mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"><mx:Script><![CDATA[import com.zkl.events.*;/** * 为组件添加两个属性 */[Bindable]public var myName:String;[Bindable]public var myPosition:String;private function customHandler():void{this.dispatchEvent(new CustomEvent(CustomEvent.EVENT_TYPE,CustomEventId.COMPONENT_EVENT,myname.text,myposition.text));}]]></mx:Script><mx:Label text="名字:"/><mx:TextInput id="myname" text="{myName}"/><mx:Label text="职位:"/><mx:TextInput id="myposition" text="{myPosition}"/><mx:Button label="确定" id="ok"/><mx:Button label="修改" click="customHandler()"/></mx:VBox>
<?xml version="1.0" encoding="utf-8"?><mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:ns1="components.*" initialize="initApp()"><mx:Script><![CDATA[ import com.zkl.events.*; import mx.controls.Alert;private function initApp():void{introduce.myName="中国星";introduce.myPosition="Manager";introduce.addEventListener(CustomEvent.EVENT_TYPE,customEventHandler);}private function customEventHandler(e:CustomEvent):void{Alert.show("收到组件的事件了:\n名字=" + e.myname + "\n职位=" + e.myposition);}]]></mx:Script><ns1:MyIntroduce x="364" y="51" id="introduce"></ns1:MyIntroduce></mx:Application>