okay so here is my problem in my main project I’m trying to fire an event using dispatchEvent I’ve made a simple test class to test this and yet it still isn’t working…
Here is the test class
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main() {
stage.addEventListener("pOver", rake);
dispatchEvent(new Event("pOver"));
}
public function rake(e:Event):void {
trace("working");
}
}
Why isn’t it firing? or why is the listener not capturing that event?
You are dispatching the event on the
Main, which is a child ofStage. If you want to specifically dispatch an event on theStagethen use:Now you may be wondering, “If it’s a child, then my event handler should still be getting triggered!”
Well, yes and no.
Lets take a look at a simple diagram of the event life-cycle:
First, the event that you are dispatching is not a bubbling
Event. Examining theEventconstructor, its signature looks like this:Notice that the second argument is by default
false, which means this event does not perform the bubbling part of the event life-cycle.Second, you have attached the event dispatcher on the bubbling side of the event life-cycle. If you look at the signature for
.addEventListener()it looks like this:Notice the third argument. Which is by default
falseagain. This means that you are attaching on the “bubbling” side of the event.This means that this event is getting to the targeted element, the instance of
Main, and then stopping and not going anywhere else.TL;DR: So what does that all mean?
So to trigger your event handler, and not change where the event gets dispatched, you need to change your event that you are triggering to:
Then your event handler, since it is a child, will be triggered by this event.
Conversely, I think that non-bubbling events will also progress through the capturing side of the event life-cycle so you could also change your event listener to attach to that side of the event as well.
I believe that event will always flow through the capturing phase, even if they are marked as not bubbling. But I could be wrong on that. I just can’t remember if “non-bubbling” events skip both capturing and bubbling phases and just trigger the target event phase and I don’t have time to check it right now.
Edit
So, I wrote up a quick test on wonderfl:
The output from this is
Notice that events will always progress through the capturing phase. However, if they are not marked as a “bubbling event”, see before, they will descent through the tree they stop when they arrive at target of the event (the
EventDispatcherthe event was dispatched on).Bubbling events, on the other hand, will turn around and head back up the tree.
Hopefully, this clears things up.