AS3: How to dispatch from the document class?
I have a pretty good handle o开发者_开发技巧n dispatching from classes other than the Document Class, but what happens when I want to dispatch an event from the Document class and have other classes listen to the document class broadcast?
It seems like there are several ways to approach this (i.e using a Singleton, using composition, using MovieClip(root)) I was just wondering what people find is the "best practice" way to do this?
Simple: Don't do it.
Why can't you just tell the objects what to do? The Document Class is at the top of the hierarchy, it should be able to manipulate objects directly. Objects lower down the hierarchy should dispatch up, but not down.
I would do it like this:
in document class:
public function attachEventListener(event:String, callback:Function) { addEventListener(e, callback, false, 0, true); }
If you don't want the other classes to have access to the document class, I would just put
addEventListener(Event.MY_EVENT, someClass.eventListenerFunction, false, 0, true);
in the document class.
But obviously there's other ways to do it too. Depends on your preference.
You should pass the document class as a paramenter to the others classes constructors.
精彩评论