View Full Version : Theory of Custom Events
pilbug
03-20-2011, 01:58 AM
This is not a specific question but more of a general one about when to use custom Events. After reading the section about them in Colin Moock's Essential ActionScript 3.0 and reading posts on the internet that basically say the same thing I am still confused about the advantage to using them.
It seems to me that you can achieve the same result with simply calling functions (which to me is a lot more intuitive). The only thing I read that gives me an inkling to their use is that they can easily be reused by other developers/programs, since your functions are likely to have a program specific name.
Thanks in advance for the help.
maskedMan
03-20-2011, 03:01 PM
The most immediate benefits of using custom events are when:
a. A movieclip that is 10 layers deep on the display list "does something interesting" that a data object or a movie clip much higher on the display list (maybe the main timeline itself) cares about. Events make it very easy to get the message from one place to the next simply by using event bubbling. That way you don't have to pass callback functions 10 layers deep
b. The default event dispatch system allows for *multiple* dispatching, so if you find that more than one object cares about the event you can just keep calling addEventListener on the dispatcher and it can have multiple callbacks. If you roll this yourself you have to create an array or some other collection for your callbacks in the event that you want more than one listener.
pilbug
03-20-2011, 10:41 PM
Thanks for the answer.
Here is an example I came across working on a game:
The game has Players and Enemies, both extensions of the MovieClip class. I want the Enemies to always face the player they are focused on. I figure why check this on enterframe? The check only needs to happen if the Player moves. However, other things are happening when the Player moves (ie updating the position of the bg). I should create a custom event and dispatch it when the character moves. This way the Arena (which contains the bg) and the Enemies could register listeners and run their respective codes on this event.
Please advise if this seems incorrect.
|
vBulletin® v3.8.5, Copyright ©2000-2012, Jelsoft Enterprises Ltd.