任意のActionScriptクラスで任意のイベントクラスをイベントとして送出するサンプル。
clone()をオーバーライドしないとイベントバブリングが発生した場合に問題になるそうだ。
これまで見て見ぬふりをしてきた「イベントバブリング」ってなんだろ?
それから、
[Event(name="alert", type="MyEvent")]
という属性(なのかな?)を書くと、Adobe Flex Builder 3 のコードエディタでaddEventListenerの引数の補完候補に表示されるようになる。これは便利。
カスタムイベントの作成(Flex2だけど日本語)とか
Flex2基礎講座(第19章 カスタムイベント)を参考にした。
com.blogspot.takumakei.MyEventDispatcher.as
package com.blogspot.takumakei
{
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
[Event(name="alert", type="MyEvent")]
[Event(name="notify", type="MyEvent")]
public class MyEventDispatcher extends EventDispatcher
{
public function MyEventDispatcher(target:IEventDispatcher=null)
{
super(target);
}
public function dispatchAlert(customProperty:String):void {
dispatchEvent(new MyEvent(MyEvent.ALERT, customProperty));
}
public function dispatchNotify(customProperty:String):void {
dispatchEvent(new MyEvent(MyEvent.NOTIFY, customProperty));
}
}
}
com.blogspot.takumakei.MyEvent.as
package com.blogspot.takumakei
{
import flash.events.Event;
public class MyEvent extends Event
{
public static const NOTIFY:String = 'notify';
public static const ALERT:String = 'alert';
public var customProperty:String = null;
public function MyEvent(type:String, customProperty:String, bubbles:Boolean=false, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
this.customProperty = customProperty;
}
override public function clone():Event {
return new MyEvent(type, customProperty);
}
}
}
StudyCustomEvent.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" initialize="init()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import com.blogspot.takumakei.MyEvent;
import com.blogspot.takumakei.MyEventDispatcher;
private var myEventDispatcher:MyEventDispatcher = new MyEventDispatcher();
private function init():void {
myEventDispatcher.addEventListener(
MyEvent.NOTIFY,
function(event:MyEvent):void {
Alert.show(event.customProperty, 'MyEvent(notify) received');
});
myEventDispatcher.addEventListener(
MyEvent.ALERT,
function(event:MyEvent):void {
Alert.show(event.customProperty, "MyEvent(alert) received");
});
}
private function dispatchAlert():void {
myEventDispatcher.dispatchAlert('hello world');
}
private function dispatchNotify():void {
myEventDispatcher.dispatchNotify('hello world');
}
]]>
</mx:Script>
<mx:Button label="alert" click="dispatchAlert()"/>
<mx:Button label="notify" click="dispatchNotify()"/>
</mx:WindowedApplication>
0 件のコメント:
コメントを投稿