Search code examples
actionscript-3eventsevent-dispatching

Proper way to add event listeners to things that don't have it as a native method


I have a custom class that is currently not extending anything (it's for executing specific types of queries on a database) but I need it to send an event to its parent class. addEventListener is not defined in it, though.

I notice a lot of the main flash classes extend EventDispatcher, so is that what I should do if there's no other alternative? Just have any class that will have to communicate with other classes extend EventDispatcher?


Solution

  • There are a couple of things you can do, you are definitely not limited to using events. Events are nice because it decouples code, and allows many objects to act on a single event, without the object that dispatches the event from caring who is listening, or what they are doing. If you want to dispatch events, extend EventDispatcher, or have one as a property of your object. (Some times you may need to define it as a property if you are already extending another class.)

    Alternatively your object can maintain a reference to another object, and explicitly call methods on it. In this case you do not need to extend EventDispatcher, but you must store a reference to all other objects you want to communicate with.

    Both solutions accomplish the same end result, it comes down to situation and/or preference.

    I hope that helps.