<

Creating a custom event listener in AS3

Published on
12,798 Points
6,598 Views
2 Endorsements
Last Modified:
Approved
I come across a lot of question about how to access things in the document class from a movieclip, or accessing something from a movieclip in the document class.

It took me a while to figure this out but once I did it makes life so much easier.

By creating a CustomEvent class and placing it in your own utils folder and setting up your AS3 class path, once you import the Custom Event, this is how you'd go about it.

your class would look something like this ...

package whatever.utils //change your package name as required
{
 import flash.events.Event;

    public class CustomEvent extends Event
    {
       
      public static const NOTIFY:String = "notify";
        public var data:*;
            
       public function CustomEvent(type:String, data:*,  bubbles:Boolean = false, cancelable:Boolean = false){
                  super(type, bubbles, cancelable);
            this.data = data;
        }
    }
}

to implement

say you have a nested movieclip that when it hits frame 5 you want to execute a function in the document class called callSomething();

when you add the movieclip in your document class

addChild(nameOfMovieClip);
//add the dispatcher

nameOfMovieClip.addEventListener(CustomEvent.NOTIFY, handleNotifyRoot);

//note the CustomEvent.NOTIFY part - you can add items in your CustomEvent class

Create a handleNotifyRoot method in your document class

function handleNotifyRoot(e:CustomEvent):void
{
trace(e.data.myData.toString());
}

in the movieclip when you want the event to trigger, you must dispatch the event

var varString:String = "clicked ball";
dispatchEvent(new CustomEvent(CustomEvent.NOTIFY, {myData:varString}));



you can pass anything to your custom event.

I hope this all makes sense.
2
Author:blue-genie
Enjoy this complimentary article view.

Get unlimited access to our entire library of technical procedures, guides, and tutorials written by certified industry professionals.

Get 7 days free
Click here to view the full article

Using this article for work? Experts Exchange can benefit your whole team.

Learn More
COLLABORATE WITH CERTIFIED PROFESSIONALS
Experts Exchange is a tech solutions provider where users receive personalized tech help from vetted certified professionals. These industry professionals also write and publish relevant articles on our site.
Ask questions about what you read
If you have a question about something within an article, you can receive help directly from the article author. Experts Exchange article authors are available to answer questions and further the discussion.
Learn from the best.