So after a few years of using events, here is my current system:
When sending messages DOWNWARDS, use public methods
If I have say, a MovieClip or my Sprite on my main timeline (many times this is your Document class) and I want to send it a message, I write a public function (method) on the Class file of my MovieClip or Sprite, for example:
public function sendMessageToMySprite(message:String):void
{
__giveMeMyMessage = message;
}
The downside with this is that public methods are not the most loosely coupled, but as long as you keep variables private in the MovieClip or Sprite, this seems to work okay. This is just how I do it.
Now, say I have a MovieClip on my main timeline, and inside of that MovieClip is another MovieClip. Then I just write a public method in my grand-child MovieClip and use dot-notation to get to it:
my-MovieClip-Child-instance.my-MovieClip-GrandChild-instance.doMyPublicMethod();
Again, there are other ways to do this (AS Signals, NResponder, Central Event Management) but for a smaller project, this seems to work.
When sending messages UPWARDS, dispatch Events
Here is what I do when I want to send messages from my grand-child MovieClip or Sprite, up to my child Sprite, up to the stage – I dispatch events.
dispatchEvent(new CustomEvent(CustomEvent));
Then I use bubbling if I want it to go further than 1 level. For example, if I want the message to go from my grand-child or great-grand-child all the way to the stage, I create an event where bubbling is set to TRUE
package
{
import flash.events.Event;
public class CustomEventThatBubbles extends Event
{
public static const EVENT_NAME:String = "customEvent";
public function CustomEventThatBubbles(type:String, bubbles:Boolean=true, cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
override public function clone():Event
{
return new CustomEventThatBubbles(type, bubbles, cancelable);
}
}
}
And in my Document Class (or Main Class), I write
stage.addEventListener(CustomEventThatBubbles, doSomethingNowThatIKnow)
When sending from an instance that’s not on the display list, use a Display Object to dispatch
This might be another “lazy” but it seems to work. If you have a class that doesn’t extend Sprite or MovieClip and isn’t added to the display list via addChild, just pass in the nearest display object through the constructor or other public method
public class MyNonDisplayObject(mc:MyMovieClip):void
{
_mc = mc;
_mc.dispatchEvent(new MyCustomEvent(MyCustomEvent));
}
You can also try creating a sprite in your non-display list class, but this seems to defeat the purpose of having a class that does not extend Sprite or MovieClip.