I need help bubbling an event in AS3

3.3k Views Asked by At

I want to have the parent of my class handle the event first, then I want to have the child handle the event. Is there a way to explicitly bubble the event up? I want to do something like this:

...
this.addEventListener(MouseEvent.CLICK, characterClicked);
...

private function characterClicked(e:Event):void{
// pass event to parent to be handled first
...
}

Is this possible, and if so how?

3

There are 3 best solutions below

2
On BEST ANSWER

I figured out a way to do this. Is seems hackish, but it works. If there is a better way of doing this please let me know.

...
this.addEventListener(MouseEvent.CLICK, characterClicked);
...

private function characterClicked(e:Event):void{
// pass event to parent to be handled first
this.removeEventListener(MouseEvent.CLICK, characterClicked); //prevent infinite loop
            dispatchEvent(e); // send event to parent object
            this.addEventListener(MouseEvent.CLICK, characterClicked);
            e.stopImmediatePropagation();
...
}
1
On

If you were to handle the listener in the parent instead of the child it might be easier. Then you could just pass the event to the child when you're done:

// inside parent class:
childObj.addEventListener(MouseEvent.CLICK, onCharacterClicked);

private function onCharacterClicked(e:Event):void {
    // do parent stuff first
    // ...

    // then pass event to child 
    childObj.onCharacterClicked(e);
}
3
On

There are three "phases" of an event; Capture, At target and Bubble. They occur in this order, meaning that if you set an event listener to be in the capture phase it will always fire before one set regularly (which would mean either at target or bubble).

Like so:

// in parent, third argument is "use capture"
child.addEventListener(MouseEvent.CLICK, handleClickInParent, true); 

// in child, add listener as usual
addEventListener(MouseEvent.CLICK, handleClick);

Now, your parent event listener will always fire first!