How flash dispatchEvent really works?

2.1k views Asked by At

It is said in the docs, that EventDispatcher's dispatchEvent "...dispatches an event into the event flow". The phrase is nice-looking and doesn't really explain anything.

Say, we have two listeners waiting for an event "A" on object "a", so what behaviour do we have to expect on calling:

a.dispatchEvent("A")?

Would both listeners be called immediately, before return from distpatchEvent? Or they will be queued in some internal flash player queue and will be processed by entering the next frame? Can we rely on some defined behaviour of flash player here or the behaviour is undefined? How one should read "dispatches an event to event flow"? The question is important since in practice it affects the control flow of the code.

2

There are 2 answers

0
ruedaminute On BEST ANSWER

Just use Signals instead :P

https://github.com/robertpenner/as3-signals/wiki

No but really, they're very easy to use and understand, a great addition to the AS3 toolbox.

You can also learn a lot about how native AS3 events work by reading Rob Penner's critiques (scroll down to bottom of wiki page)

0
AudioBubble On

It all depends on your display list hierarchy.

Flash's event structure is based on its internal event model.

  1. The Stage will be the first object notified, and then the event will trickle down the display list until it reaches its target. This phase is called the capture phase. To enable it, set useCapture to true on an event listener. Do note that it's pointless to do so unless the object listening is a parent of the object targeting the event. This is called event intercepting.

  2. The next phase is the target phase. This is the behavior most commonly known with events. The targeted display object (the one the has a listener for the event) will receive the event and carry out the code in the listener.

  3. The final phase is called the bubbling phase. This is when the event bubbles up the display list after the event has been received. Event bubbling is very important for dispatching custom events, as you'll need to know how to listen for events dispatched by an object's children.

When dispatching an event, I generally use this syntax (Event.CHANGE is just a common example):

Object.dispatchEvent(new Event("CHANGE", true, false));

The Object is the object you're dispatching from. The first parameter is the event you're dispatching. The second is the bubbles parameter. The final is the cancelable property. Event.cancelable is used to prevent the default action of an event (IE: a mouse click) via Event.preventDefault().

Reference: