Dynamic Custom Event

Custom Events has become very useful when you’re building more complex applications.
You create them for especific cases and usualy they came with especific parameters.

Let’s say you create a custom event for a video player class and you use it to check the loading progress and video playback events, like play, pause, playback progress and playback complete. So when you create this event you must pass these parameters somehow, directly as an opitional parameter, inside an object, array or whatever you want.

Although, when you’re loading the video you need stream bytesLoaded and stream bytesTotal, but you don’t need the current time of playback. Other case is when you dispatch an event saying that the stream is paused or the playback is complete, you don’t need any other parameters. The problem (not a problem but a pain in the ass)  is that, for every param, you need to create a var in your class to store the value passed, otherwise you can’t pass any of them thru the event.

To avoid this you can set your custom event as a dynamic class. For those who don’t know, dynamic classes allow you to add properties at runtime, like movie clips. So you can pass any param thru an object as a opitional param of your event an store them in your class, like this:

package app.events {
	import flash.events.Event;
 
	dynamic public class CustomEvent extends Event {
		public function CustomEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false, param:Object = null):void{
			super(type, bubbles, cancelable);
 
			if(param){
				for(var i:String in param){
					this[i] = param[i];
				}
			}
		}
	}
}

So when you need to pass any value you should add it to an object:

dispatchEvent(new CustomEvent(CustomEvent.LOAD_PROGRESS, false, false, {bytesLoaded:135817, bytesTotal:521387}));
dispatchEvent(new CustomEvent(CustomEvent.VIDEO_PROGRESS, false, false, {currentTime:8.65}));
dispatchEvent(new CustomEvent(CustomEvent.PAUSE));

And you recieve then like this:

function onLoadProgress(event:CustomEvent):void{
	trace(Math.floor(event.bytesLoaded*100/event.bytesTotal)+"% loaded");
}
function onVideoProgress(event:CustomEvent):void{
	trace("Current time:", event.currentTime);
}
function onPause(event:CustomEvent):void{
	trace("Video paused");
}

Tags: ,

One Response to “Dynamic Custom Event”

  1. MichaelJW says:

    Fantastic idea! Fantastic blog all round, actually.

Leave a Reply