ActionScript 3: Creating custom event handlers using EventDispatcher

Creating custom event handlers in ActionScript 3 is pretty much simple. Here is a simple example which loads an image and fires a custom event named “onImageLoad” as soon as image is loaded.

Class imageLoader.as

package {
import flash.events.*;
import flash.net.URLRequest;
import flash.display.Loader;
import flash.display.Sprite;
public class imageLoader extends EventDispatcher {
private var _mc:Sprite;
private var url:String;
private var loader:Loader;
public function imageLoader(_mc:Sprite, url:String) {
this._mc = _mc;
this.url = url;
loadImg();
_mc.addChild(loader);
}
private function loadImg():void {
loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
var request:URLRequest = new URLRequest(url);
loader.load(request);
}
private function onComplete(event:Event):void {
dispatchEvent(new Event("onImageLoad"));
}
private function onIOError(event:IOErrorEvent):void {
trace("IO Error.");
}
}
}

Now in Flash, create a a object of imageLoader class and add a event listener (for our custom event “onImageLoad”).

var myImageLoader:imageLoader = new imageLoader(this, "images/someImg.jpg");
myImageLoader.addEventListener("onImageLoad", callbackHandler);
function callbackHandler(event:Event) {
trace("Image Loading Complete!");
}

Now test the file. Be sure to have someImg.jpg in images folder. Once image is loaded, you should be able to see “”Image Loading Complete!” message in output window.

About these ads

34 thoughts on “ActionScript 3: Creating custom event handlers using EventDispatcher

  1. hi tushar,

    examples you give are actually very good.but i want to suggest one thing that can you give very simple example avoiding too much coding and with only necessary syntax? it will help people who are new in AS2 or AS3. for you AS2 is old version but many companies have just started using AS2.

  2. how about removing it? i dun seem to get it to remove the “loaded img” and have it ready to load a new image. any idea? thx.

  3. I agree with sara actually. Extraneous code, italics and no helpful formatting or higlighting make this very difficult to understand for beginners.

  4. Common asdlfkj… Really? Lighten up, dude.

    Sarah,

    There is not really any code there that doesn’t need to be. AS3 looks a bit more convoluted, but it’s structure is consistent and you get used to it. Once you get past how it “looks” like more code you will learn it’s much nicer than AS2.

    Unfortunately most folks are still using the flash 8 player so AS2 is still in demand. But I strongly urge you to start learning AS3 now. Once you wrap your head around it you will see it is much easier to write than AS2.

    It was a tough jump for me but I’m much happier now :)

    Check out “Learning ActionScript 3 – A Beginner’s Guide” by Rich Shupe with Zevan Rosser. It puts practical examples into plain terms… very good. Also the more advance reference book “Essential ActionScript 3.0″ by Colin Moock… this book truly is essential after you have decent footing in AS3.

    -W

  5. I just finished a fairly heavy AS3 application, and although I feel I kept a pretty good OOP model I never used custom events. About 80% of the way through I really started to understand why I should of… near the end of the project a lot of nice OOP code started to become pretty procedural and hacky because of certain requests.

  6. Will, agreed lol :)

    AS3 IS ALLOT different to AS2, for me AS2 is easier to learn then AS3 but I guess I am not sure what language AS3 is akin to (seems like C# but not sure)

  7. Hi Tushar,

    I am flash developer with 6 yrs of experience, more into elearning development. I just want to know how good/suitable is flex for elearning development.

    Thanks
    B.S

  8. Hi Tushar,

    Thanks you for the reply. I have one more question. The Company I m currently working with involved in Game development – online as well as PC games and elearning. My question is, can Flex be used for any of these developments to increase productivity?

    B.S.
    Hyderabad, India

  9. Hi Tushar,

    Can you give me any example where flex is used for Online Game statistics or is it good to use flex for statics for the game developed in flash?.

    Thanks
    B.S

  10. This is by far the most practical example in using custom events. I have been at it for months but was not able to get my head around events and dispatchers. This has really put it together for me. Huge thanks for the post.

  11. This is not a custom event handler. This is a custom event listener and custom event dispatcher. A custom event handler is quite different and a bit more complicated.

    That aside this is a good tutorial.

  12. Thanks

    but can i ask you question?

    why we are using custom Events ?
    and where we can do it?

    thanks

  13. how do you index an event so that i would like to load 2 pic that are loaded in a extended sprite.
    For example: i’ve loaded one picture(duplicated the image to fil the matrix) basicly onFront(4×4 matrix), and behind them other random pic (one by one) onBehind.
    How do i launch an Mouse event on both picture, front and back , one to be visible an the other not, at the same time ?

  14. Hi people,

    I tried this code but kept receiving the error message “Packages cannot be nested”
    I tried it on a clean new page, trying to load a .swf file on it.
    I ave been doing this with AS2 but cannot really get on to it with AS3…d
    Can anypne help me?

    Thaks a lot in advance

  15. Tushar Wadekar,

    I want to marry you, you are a genius, I am having problem with loading swf file and I was running conversion from AS2 to AS3 and your code works for “someSWF.swf” movie file as well, Thanks,

  16. I’ve already done this couple times, but now I’m in a trouble cause of listeners not being reached by the dispatched events.
    I have a class that wraps couple constants used dispatching custom events, let’s say “MyEvent”. Then I have a class (in the same package) that dispatch those messages, let’s say “MyEngine”, and another class where I declare an object of the MyEngine class, let’s say “MyMainClass”.
    I add an eventListener to the MyMainClass object, then I declare an object of MyEngine class that dispatches couple events. The point is that the eventListeners are not triggered! They are correctly triggered if the callback function in put in the MyEngine class as well as the eventListener, too.
    It looks like the event wasn’t “forwarded” to the MyMainClass…
    Any suggestions?
    P.S. I used to do the same in the same project while it was simpler and I got that 100% working. Now that its dimension is grown, I get this weird behaviour

    Thank you in advance for your help.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s