AS3 Gotcha #4: Calling Event Handlers From Other Places (dispatchEvent)

So, here's a scenario:

You've got two buttons, and both should do the exact same thing — but they're located in different places; in fact, one of them could even be in a different SWF. What to do?

You've got a button assigned to do something when it's clicked. Let's say it triggers some complex ActionScript-driven animation. You want the exact some functionality (the complex animation) to be triggered from somewhere else in your Flash movie as well.

Well, in AS2 it was relatively simple:
buttonOne.onRelease = function() {
    doSomething();
    doSomeOtherStuff();
    doSomeMoreStuff();
    //...and lots of more other stuff
    //that we won't re-type here
    //but you get the pic
}

...and elsewhere in the movie:
buttonTwo.onRelease = function() {
    this._parent.the_rest_of_the_path.buttonOne.onRelease();
}

Essentially, you'd just call buttonOne's onRelease handler from within buttonTwo (since buttonOne's handler was essentially a self-contained function). And you'd be done.

Unfortunately, it doesn't work that way in AS3. (You can thank event listeners for that.)

Long story short, the new way to do that in AS3 would be with dispatchEvent(). Like so:

buttonOne.addEventListener(MouseEvent.CLICK, clickButtonOne);
function clickButtonOne (e) {
    trace("button one was clicked")
}

...and elsewhere in the movie:

buttonTwo.addEventListener(MouseEvent.CLICK, clickButtonTwo);
function clickButtonTwo (e) {
    Object(this.parent).the_rest_of_the_path.buttonOne.dispatchEvent(
        new MouseEvent(MouseEvent.CLICK)
    );
}

Now why would you ever want to do something like this? Well, my friend. Consider the following:

  • You're lazy. You have technology at your fingertips. There has to be a better way, right?

  • If you used the copy and paste method, and you ever needed to change anything to closeButtonOne's onRelease handler, you would have to manually update closeButonTwo's handler as well. How genuinely lo-tech.

  • ...not to mention things could really start to get messy when the two buttons are in totally different places in your Flash file, if means all of your target paths would have to be re-written to suit each individual MovieClip.


[ EDIT: October 17, 2009 ] Updated code example according to Banned App's suggestion.


About this entry