Custom Events

Creating custom events in AS3 is really easy, and very powerful. example:

lets say that there is a custom event that should be fired when a "Tween Lite" animation is done playing. we start by creating the custom event :

package  {
	import flash.events.*;

	public class FinishedEvent extends Event{

		private var trackingValue:String;
		public static var DO_SOMETHING= "do_something"

		public function FinishedEvent(type:String , someValue:String) {
 			super(type);
			trackingValue = someValue;

		}

		public function getDispatcherName()
 		{
 			return  trackingValue;
 		}
	}
}


now, somewhere in the code, we have these lines:


public class someClass extends MovieClip
 	{
	....

	....

	TweenLite.to(   _someMovieClip,
			1 ,         // duration
			{
				x:100,
 				y:100,
	 			ease:Quadratic.easeInOut
 			} ,
 			0 ,            // delay
 			finishedFunction        // function to be
						//called on finish animation

 		);

	public function  finishedFunction()
 	{

		// the Finished event constructor can have an optional value
		// that we can pass to it for identification
		dispatchEvent(new FinishedEvent(FinishedEvent.DO_SOMETHING ,
						_someMovieClip.name));

	}

...

....

}

now somewhere else in the code, in some other class (or possibly in the same class):

........

var _someObject:someClass = new someClass();

.....

.....

_someObject.addEventListener(FinishedEvent.DO_SOMETHING , callBackFunction);

public function callBackFunction(_event:FinishedEvent)
{
	trace(_event.getDispatcherName() )
}

This way, if we have several objects animating with a tween lite call , we can identify which one is finished animating with:

_event.getDispatcherName()

and do something by detecting the name and calling the appropriate functions if we know the name of the object that we want to track

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.