1、自定义组件
2、自定义事件
3、结合使用
一、自定义组件(使用的是Flex组件,ActionScript组件相对麻烦点,可视化差点)
该组件由一个TextArea和两个Button组成,如图:
代码:
MyComponent.mxml
/**
*
* Using the Event metadata tag
* You use the [Event] metadata tag to define events dispatched by a component so that the Flex compiler can recognize
* them as MXML tag attributes in an MXML file. You add the [Event] metadata tag in one of the following locations:
* ActionScript components Above the class definition, but within the package definition, so that the events are bound
* to the class and not a particular member of the class.
* MXML components In the mx:Metadata tag of an MXML file.
*
*/
[Event(name="commit",type ="laxino.MyEvent")]
[Event(name="preview",type ="laxino.MyEvent")]
</mx:Metadata>
<mx:Script>
<!--[CDATA[
private function initComponent():void
{
}
private function preview(event:Event):void
{
this.dispatchEvent(new MyEvent(MyEvent.PREVIEW, content.text));
}
private function commitHandle(event:Event):void
{
this.dispatchEvent(new MyEvent(MyEvent.COMMIT, content.text));
}
]]-->
</mx:Script>
<mx:TextArea x="10" y="10" id="content"/>
<mx:Button x="10" y="62" label="Preview" width="82" click="preview(event)"/>
<mx:Button x="100" y="62" label="Commit" click="commitHandle(event)" />
</mx:Canvas>
二、自定义事件
当按Button1时触发preview事件,点击Button2时触发commit事件,传输数据通过$data变量存储。
代码:
public class MyEvent extends Event
{
public static const COMMIT:String = "commit";
public static const PREVIEW:String = "preview";
private var $data:Object;
public function MyEvent(type:String, $data:Object=null, bubbles:Boolean=true, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
this.$data = $data;
}
public function get data():Object
{
return $data;
}
public function set data($data:Object):void
{
this.$data = $data;
}
}
}
三、使用。
private function initApp():void
{
// 方式一,监听preview事件
myComponent.addEventListener(MyEvent.PREVIEW, previewHandle);
}
private function commitHandle(event:MyEvent):void
{
result.text = event.data.toString();
}
private function previewHandle(event:MyEvent):void
{
Alert.show(event.data.toString(), "Preview");
}
]]-->
</mx:Script>
<mx:Label x="10" y="11" text="Custom Component"/>
<!-- 方式二,监听commit事件 -->
<cus:MyComponent id="myComponent" x="10" y="37" commit="commitHandle(event)" ></cus:MyComponent>
<mx:Label x="10" y="139" text="Standard Component(Text)"/>
<mx:Text id="result" x="10" y="165" text="Empty" width="180" height="123" />
</mx:Application>
有时候我们还需要加上一个自定义的EventDispatcher,通过继承EventDispatcher或实现IEventDispatcher接口。
最终结果,如图: