[AS 3.0] 나만의 이벤트 만들기 – #1 (EventDispatcher, dispatchEvent)

커스텀 이벤트를 만드는 방법에 대해서 간단히 알아보자.
이벤트 객체의 역활을 하게 될 MY_EVENT 를 정의하고 dispatchEvent 시켜준다.

//EventDispatchExam.as
package {	

	import flash.events.Event;
	import flash.events.EventDispatcher;	

	public class EventDispatchExam extends EventDispatcher{

		public static const MY_EVENT:String = "my_event";
		public var _myEventValue:Number;

		public function EventDispatchExam() {
		}

		public function callMyEvent(n:Number):void {
			_myEventValue = n;
			dispatchEvent(new Event(MY_EVENT));
		}
	}
}

EventDispatchExam인스턴스를 생성하고, callMyEvent()를 호출하면 MY_EVENT 가 이벤트리스너로 등록된 인스턴스에 이벤트와 인수를 전달, 해당 함수를 실행한다.

//Main.as
package {

	import flash.display.Sprite;
	import flash.events.Event;

	public class Main extends Sprite {

		public function Main():void{
			var myEvent:EventDispatchExam = new EventDispatchExam();
			myEvent.addEventListener(EventDispatchExam.MY_EVENT, onMyEventFunc);
			myEvent.callMyEvent(10);
		}

		private function onMyEventFunc(e:Event):void {
			trace( "onMyEventFunc" );
			trace( "e : " + e );
			trace( "e.target : " + e.target );
			trace( "e.target._myEventValue : " + e.target._myEventValue );
		}
	}
}

결과값은 다음과 같다.

//OutPut
//onMyEventFunc
//e : [Event type="my_event" bubbles=false cancelable=false eventPhase=2]
//e.target : [object EventDispatchExam]
//e.target._myEventValue : 10
Share

0 Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2012 blog.flasia.com | powered by WordPress with Barecity