AS3 Who removed Child? - actionscript-3

I have hure legacy project. And sometimes one of my windows is removed from stage. I've created test project to simulate situation with chain of childs root.mc1.mc2.mc3.mc4
mc4 is MovieClipWithEvents custom class
After that I put line removeChild(mc1);
In mc4 I also receive REMOVED_FROM_STAGE, but I can`t figure wich one of parent is removed.
globalVisibleList method in trace shows:
// mc4 added into mc3
[trace] onAddedToStage mc4 mc3 mc4 mc4
// mc1 is removed from root, BUT event.target shows that mc4 is removed from mc3
[trace] onRemovedFromStage mc4 mc3 mc4 mc4
//All parents still have their parents and are visible despite we know that mc1 is removed from root and received REMOVED_FROM_STAGE
[trace] [object MovieClipWithEvents2], mc4, true
[trace] [object MovieClip], mc3, true
[trace] [object MovieClip], mc2, true
[trace] [object MovieClip], mc1, true
[trace] [object Test_VisibleEvent2], root1, true
[trace] [object Stage], null, true
//The next line trace("*************\n" + mc4.globalVisibleList(mc4));
all is ok, mc1 is not child of root now
[trace] *************
[trace] [object MovieClipWithEvents2], mc4, true
[trace] [object MovieClip], mc3, true
[trace] [object MovieClip], mc2, true
[trace] [object MovieClip], mc1, true
Test_VisibleEvent2
package {
import display.MovieClipWithEvents2;
import flash.display.MovieClip;
import flash.display.Sprite;
public class Test_VisibleEvent2 extends Sprite {
private var mc1:MovieClip;
private var mc2:MovieClip;
private var mc3:MovieClip;
private var mc4:MovieClipWithEvents2;
public function Test_VisibleEvent2() {
mc1 = new MovieClip();
mc2 = new MovieClip();
mc3 = new MovieClip();
mc4 = new MovieClipWithEvents2();
mc1.name = "mc1";
mc2.name = "mc2";
mc3.name = "mc3";
mc4.name = "mc4";
addChild(mc1);
mc1.addChild(mc2);
mc2.addChild(mc3);
mc3.addChild(mc4);
removeChild(mc1);
trace("*************\n" + mc4.globalVisibleList(mc4));
}
}
}
MovieClipWithEvents2
package display {
import flash.display.DisplayObject;
import flash.display.MovieClip;
import flash.events.Event;
public class MovieClipWithEvents2 extends MovieClip {
public function MovieClipWithEvents2() {
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
addEventListener(Event.REMOVED_FROM_STAGE, onRemovedFromStage);
}
protected function onAddedToStage(event:Event):void {
trace("onAddedToStage", name, parent.name, event.target.name, event.currentTarget.name);
}
protected function onRemovedFromStage(event:Event):void {
trace("onRemovedFromStage", name, parent.name, event.target.name, event.currentTarget.name);
trace(globalVisibleList(this));
}
public function globalVisibleList(displayObject:DisplayObject):String {
var result:String = "";
var checking:DisplayObject = displayObject;
while(checking){
result += getNameAndVisible(checking);
if(checking.parent){
checking = checking.parent;
}else{
return result;
}
}
return result;// to make Idea happy
}
public function getNameAndVisible(displayObject:DisplayObject):String {
return displayObject + ", " + displayObject.name + ", " + displayObject.visible + "\n";
}
}
}
So I have two questions :
Why mc4 receive REMOVED_FROM_STAGE, but all chain of parents is unbroken till Stage ?
How to figure which parent is removed ?

Related

when Event.ADDED_TO_STAGE is call?

I have this code :
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
when is this event called ? I'm working on a example project of StageVideo but it isn't easy. I'm working on flash pro.
Event.ADDED_TO_STAGE is called whenever addChild() or addChildAt() is called.
In order to make sure that the stage and parent are available within the object that is being added to the stage that you add the listener of Event.ADDED_TO_STAGE within the object's constructor and then when that object is added to the stage, its Event.ADDED_TO_STAGE listener will be fired and the stage and parent of that object will be available.
Example:
package {
import flash.display.Sprite;
public class Main extends Sprite {
public function Main() {
var textField:ChildTextField = new ChildTextField();
textField.text = "Hello StackOverflow";
addChild(textField);
}
}
}
import flash.events.Event;
import flash.text.TextField;
class ChildTextField extends TextField {
public function ChildTextField() {
trace("(Stage (Before addChild):" + stage);
trace("ChildTextField Parent (Before addChild): " + this.parent);
addEventListener(Event.ADDED_TO_STAGE, initWhenAddedToStage);
}
function initWhenAddedToStage(e:Event):void {
trace("Stage (After addChild): " + stage);
trace("ChildTextField (After addChild): " + this.parent);
}
}
Output:
[trace] (Stage (Before addChild):null
[trace] ChildTextField Parent (Before addChild): null
[trace] Stage (After addChild): [object Stage]
[trace] ChildTextField (After addChild): [object Main]
As indicated by its name, the addedToStage event is
Dispatched when a display object is added to the on stage display list, either directly or through the addition of a sub tree in which the display object is contained. The following methods trigger this event: DisplayObjectContainer.addChild(), DisplayObjectContainer.addChildAt().
Hope that can help.

AS3 - Referencing the Stage after Preloader Implementation

Ive just finished the basic structure of a little game and saved the simple preloader till last. Silly me.
After numerous tutorials I found this one that worked for me - Pre Loader in Flash Builder
The preloader works and the game is on the stage, but freezes instantly. Any reference to the stage in my LevelOne code throws up errors. error #1009: cannot access a property or method of a null object reference.
Before implementing the Preloader, my Application Class (RookiesGame) was used as a level switcher. Each level is contained in a Sprite. RookiesGame starts by adding LevelOne to stage, then once player completes it, RookiesGame removes LevelOne and adds LevelTwo to stage etc.
The level classes reference the stage with the _stage variable.
Since Ive been learning this structure, the preloader becoming the application class and RookiesGame becoming just another class has really confused me. Shouldn’t the _stage var still work? Is it okay to keep RookiesGame as a level switcher?
Anyway main problem is referencing the stage from the Level Classes.
Current code:
Preloader Class
Works fine, game starts.
package
{
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.utils.getDefinitionByName;
[SWF(width="650", height="450", backgroundColor="#FFFFFF", frameRate="60")]
public class Preloader extends Sprite
{
// Private
private var _preloaderBackground:Shape
private var _preloaderPercent:Shape;
private var _checkForCacheFlag:Boolean = true;
// Constants
private static const MAIN_CLASS_NAME:String = "RookiesGame";
public function Preloader()
{
trace("Preloader: Initialized.")
addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
public function dispose():void
{
trace("Preloader: Disposing.")
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
if (_preloaderBackground)
{
removeChild(_preloaderBackground);
_preloaderBackground = null;
}
if (_preloaderPercent)
{
removeChild(_preloaderPercent);
_preloaderPercent = null;
}
}
// Private functions
private function onAddedToStage(e:Event):void
{
trace("Preloader: Added to stage.");
removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
stage.scaleMode = StageScaleMode.SHOW_ALL;
stage.align = StageAlign.TOP_LEFT;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(e:Event):void
{
if (_checkForCacheFlag == true)
{
_checkForCacheFlag = false;
if (root.loaderInfo.bytesLoaded >= root.loaderInfo.bytesTotal)
{
trace("Preloader: No need to load, all " + root.loaderInfo.bytesTotal + " bytes are cached.");
finishedLoading();
}
else
beginLoading();
}
else
{
if (root.loaderInfo.bytesLoaded >= root.loaderInfo.bytesTotal)
{
trace("Preloader: Finished loading all " + root.loaderInfo.bytesTotal + " bytes.");
finishedLoading();
}
else
{
var percent:Number = root.loaderInfo.bytesLoaded / root.loaderInfo.bytesTotal;
updateGraphic(percent);
trace("Preloader: " + (percent * 100) + " %");
}
}
}
private function beginLoading():void
{
// Might not be called if cached.
// ------------------------------
trace("Preloader: Beginning loading.")
_preloaderBackground = new Shape()
_preloaderBackground.graphics.beginFill(0x333333)
_preloaderBackground.graphics.lineStyle(2,0x000000)
_preloaderBackground.graphics.drawRect(0,0,200,20)
_preloaderBackground.graphics.endFill()
_preloaderPercent = new Shape()
_preloaderPercent.graphics.beginFill(0xFFFFFFF)
_preloaderPercent.graphics.drawRect(0,0,200,20)
_preloaderPercent.graphics.endFill()
addChild(_preloaderBackground)
addChild(_preloaderPercent)
_preloaderBackground.x = _preloaderBackground.y = 10
_preloaderPercent.x = _preloaderPercent.y = 10
_preloaderPercent.scaleX = 0
}
private function updateGraphic(percent:Number):void
{
// Might not be called if cached.
// ------------------------------
_preloaderPercent.scaleX = percent
}
private function finishedLoading():void
{
var RookiesGame:Class = getDefinitionByName(MAIN_CLASS_NAME) as Class;
if (RookiesGame == null)
throw new Error("Preloader: There is no class \"" + MAIN_CLASS_NAME + "\".");
var main:DisplayObject = new RookiesGame() as DisplayObject;
if (main == null)
throw new Error("Preloader: The class \"" + MAIN_CLASS_NAME + "\" is not a Sprite or MovieClip.");
addChild(main);
dispose();
}
}
}
RookiesGame Class (used to be application class)
Any references to the stage threw up #1009 error, which stopped when I changed stage.addChild to this.addChild
Ive not got to the level switch handler yet with the preloader, so I dont know how stage.focus will work either!
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
public class RookiesGame extends Sprite
{
private var _levelOne:LevelOne;
private var _levelTwo:LevelTwo;
public function RookiesGame()
{
_levelOne = new LevelOne(stage);
_levelTwo = new LevelTwo(stage);
this.addChild(_levelOne);
this.addEventListener("levelOneComplete",levelTwoSwitchHandler);
}
private function levelTwoSwitchHandler(event:Event):void
{
this.removeChild(_levelOne);
_levelOne = null;
this.addChild(_levelTwo);
stage.focus = stage;
}
}
}
LevelOne Class
Lots of #1009 errors. Anything referencing the stage.
Class is huge so I'll highlight problem chunks.
The #1009 error when referencing stage, adding the keyboard listeners.
_stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
Also #1009 when referencing stage to check stage Boundaries. Cant just change stage. to this. anymore.
private function checkStageBoundaries(gameObject:MovieClip):void
{
if (gameObject.x < 50)
{
gameObject.x = 50;
}
if (gameObject.y < 50)
{
gameObject.y = 50;
}
if (gameObject.x + gameObject.width > _stage.stageWidth - 50)
{
gameObject.x = _stage.stageWidth - gameObject.width - 50;
}
if (gameObject.y + gameObject.height > _stage.stageHeight - 50)
{
gameObject.y = _stage.stageHeight - gameObject.height - 50;
}
}
I reference _stage later in the program to remove the event listeners. Thats it.
_stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
_stage.removeEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
How can I reference the stage, without these errors and keep RookiesGame as the level switcher.
LevelOne Class Structure
To show how I use(d) _stage.
package
{
//import classes
public class LevelOne extends Sprite
{
//Declare the variables to hold the game objects
//A variable to store the reference to the stage from the application class
private var _stage:Object;
public function LevelOne(stage:Object)
{
_stage = stage;
this.addEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function addedToStageHandler(event:Event):void
{
startGame();
this.removeEventListener(Event.ADDED_TO_STAGE, addedToStageHandler);
}
private function startGame():void
{
//Includes _stage references that mess everything up.
}
private function levelCleared():void
{
//When Level finished, dispatch event to tell RookiesGame to switch levels.
dispatchEvent(new Event("levelOneComplete", true));
}
}
}
Sorry if thats confusing, but if you can help me reference the stage via LevelOne and RookiesGame classes, It would be much appreciated.
You are passing in a null stage to LevelOne from your RookiesGame class. Whenever you instantiate a RookiesGame the constructor will run first, it has not been added to the display list yet so its inherited reference to stage is null. What you need to do is add an event listener for ADDED_TO_STAGE in the RookiesGame class:
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
public class RookiesGame extends Sprite
{
private var _levelOne:LevelOne;
private var _levelTwo:LevelTwo;
public function RookiesGame()
{
addEventListener( Event.ADDED_TO_STAGE, onAdded );
}
//added to stage event
private function onAdded( e:Event ):void {
removeEventListener( Event.ADDED_TO_STAGE, onAdded );
_levelOne = new LevelOne(stage);
_levelTwo = new LevelTwo(stage);
this.addChild(_levelOne);
this.addEventListener("levelOneComplete",levelTwoSwitchHandler);
}
...
}
Also if you are using addChild() call for LevelOne as in addChild(_levelOne) it has its own reference to stage after it's been added to the display list, you do not need to create a _stage variable for those classes if you are adding them to the display list.
Also you have the listener for ADDED_TO_STAGE in LevelOne, where the stage variable would have no longer been null, so you can remove your class variable _stage entirely.

loaderInfo.addEvenListener doesn't work

I made a code for preloader that worked when it was written in frame actions. But then I decided to move all the code to classes and a bit reworked it. And now it doesn't work. Function that listener should call is just not called, and I started getting errors when address to argument event in this not-called function.
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.ProgressEvent;
public class Preloader extends MovieClip {
public function Preloader() {
addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void {
trace("init started");
removeEventListener(Event.ADDED_TO_STAGE, init);
loaderInfo.addEventListener(ProgressEvent.PROGRESS, showProgress);
trace("init completed");
}
private function showProgress(e:Event):void {
trace(loaderInfo.bytesLoaded);
/*info_txt.text = Math.floor(e.bytesLoaded/e.bytesTotal*100) + "%"
if (e.bytesLoaded==e.bytesTotal) {
loaderInfo.removeEventListener(ProgressEvent.PROGRESS, showProgress);
finalizeLoading();
}
/**/
}
private function finalizeLoading():void {
removeChild(info_txt);
var startGame_btn = new StartGame_btn();
addChild(startGame_btn);startGame_btn.x=395;startGame_btn.y=290;
}
}
}
When I uncomment /*info_txt... part. I get this:
Access of possibly undefined property bytesLoaded through a reference with static type flash.events:Event.
Access of possibly undefined property bytesTotal through a reference with static type flash.events:Event.
Access of possibly undefined property bytesLoaded through a reference with static type flash.events:Event.
Access of possibly undefined property bytesTotal through a reference with static type flash.events:Event.
Change loaderInfo to root.loaderInfo in the init method for listening root loaderInfo object. When your script were in timeline this object were documentClass and root simultaneously, so your code have worked properly.
What about errors, just change type of e argument from Event to ProgressEvent in the showProgress method, because Event doesn't gave such properties.
There is a lot wrong with your code.
Here is a simple loader with some of your code added. at the worst it should point you in the right direction.
package {
import flash.display.MovieClip;
import flash.errors.IOError;
import flash.events.AsyncErrorEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
public class myPreloader extends MovieClip {
public var context:LoaderContext = new LoaderContext();
public var myLoader:Loader = new Loader();
public var url:URLRequest;
public function myPreloader() {
context = new LoaderContext();
context.checkPolicyFile = true;
myLoader = new Loader();
myLoader.addEventListener(AsyncErrorEvent.ASYNC_ERROR, errorHandlerAsyncErrorEvent);
myLoader.addEventListener(IOErrorEvent.IO_ERROR, errorHandlerIOErrorEvent);
myLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandlerSecurityErrorEvent);
myLoader.contentLoaderInfo.addEventListener(Event.INIT, initHandler);
myLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, infoIOErrorEvent);
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressListener);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
this.addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
url = new URLRequest("test.swf"); // change this to whatever it is you are loading
myLoader.load( url,context );
myLoader.load( url);
}
public function progressListener (e:ProgressEvent):void{
trace("Downloaded " + e.bytesLoaded + " out of " + e.bytesTotal + " bytes");
info_txt.text = info_txt.text = Math.floor(e.bytesLoaded/e.bytesTotal*100) + "%"
}
public function onLoadComplete( e:Event ):void{
trace( 'onLoadComplete' );
removeChild(info_txt);
var startGame_btn = new StartGame_btn();
addChild(startGame_btn);
startGame_btn.x = 395;
startGame_btn.y=290;
}
public function initHandler( e:Event ):void{
trace( 'load init' );
}
public function errorHandlerErrorEvent( e:ErrorEvent ):void{
trace( 'errorHandlerErrorEvent ' + e.toString() );
}
public function infoIOErrorEvent( e:IOErrorEvent ):void{
trace( 'infoIOErrorEvent ' + e.toString() );
}
public function errorHandlerIOErrorEvent( e:IOErrorEvent ):void{
trace( 'errorHandlerIOErrorEvent ' + e.toString() );
}
public function errorHandlerAsyncErrorEvent( e:AsyncErrorEvent ) :void{
trace( 'errorHandlerAsyncErrorEvent ' + e.toString() );
}
public function errorHandlerSecurityErrorEvent( e:SecurityErrorEvent ):void{
trace( 'errorHandlerSecurityErrorEvent ' + e.toString() );
}
}
}

ArgumentError: Error #2025 after game "reset", possibly a scope error

My extremely short minigame has 4 objects on stage, after the game is done, I want them all to be removed from stage and for the game to reinitiate.
I've set it up like this (most bits taken out)
function mainGame():void {
var theCoin:coin = new coin();
var cupOne:cup = new cup();
var cupTwo:cup = new cup();
var cupThree:cup = new cup();
stage.addChild(theCoin);
trace(theCoin.parent);
stage.addChild(cupOne);
trace(cupOne.parent);
stage.addChild(cupTwo);
trace(cupTwo.parent);
stage.addChild(cupThree);
trace(cupThree.parent);
function prepReset():void
{
cupOne.removeEventListener(MouseEvent.CLICK, liftCup1);
cupTwo.removeEventListener(MouseEvent.CLICK, liftCup2);
cupThree.removeEventListener(MouseEvent.CLICK, liftCup3);
stage.addChild(resetBtn);
resetBtn.addEventListener(MouseEvent.CLICK, resetGame);
}
function resetGame(event:MouseEvent):void
{
stage.removeChild(cupOne);
stage.removeChild(cupTwo);
stage.removeChild(cupThree);
letsgoagain();
}
} // end mainGame
function letsgoagain():void
{
stage.removeChild(resetBtn);
mainGame();
trace("RESET")
}
This all works fine the first time around. Once it resets for the second time, i'm getting
Game Started
[object Stage]
[object Stage]
[object Stage]
[object Stage]
RESET
[object Stage]
[object Stage]
[object Stage]
[object Stage]
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
at Function/coinGame/$construct/mainGame/resetGame()[*\coinGame.as:147]
Cannot display source code at this location.
The parent continues to be the Stage, yet stage.removeChild is not the right syntax? I don't get it.
Stackoverflow, would you please kindly point me in the right direction?
Here's an example of how you might go about setting up this class :
public class coinGame extends MovieClip
{
public var theCoin:coin;
public var cupOne:cup;
public var cupTwo:cup;
public var cupThree:cup;
public function coinGame():void
{
initGame();
}
public function initGame():void
{
theCoin = new coin();
cupOne = new cup();
cupTwo = new cup();
cupThree = new cup();
addChild(theCoin);
addChild(cupOne);
addChild(cupTwo);
addChild(cupThree);
}
public function prepReset():void
{
cupOne.removeEventListener(MouseEvent.CLICK, liftCup1);
cupTwo.removeEventListener(MouseEvent.CLICK, liftCup2);
cupThree.removeEventListener(MouseEvent.CLICK, liftCup3);
addChild(resetBtn);
resetBtn.addEventListener(MouseEvent.CLICK, resetGame);
}
public function resetGame(event:MouseEvent):void
{
removeChild(cupOne);
removeChild(cupTwo);
removeChild(cupThree);
letsgoagain();
}
function letsgoagain():void
{
removeChild(resetBtn);
initGame();
}
}
I didn't declare your resetBtn or add event listeners etc, but that is the basic structure.
Putting the creation and adding of objects to the stage in a initGame() method, allows you to restart the game easily. The constructor only gets executed once, so it's best not to put things that you might want to do multiple times in the constructor.
Also, unless you want to create the cups each game reset, you could do this :
public function coinGame():void
{
theCoin = new coin();
cupOne = new cup();
cupTwo = new cup();
cupThree = new cup();
initGame();
}
public function initGame():void
{
addChild(theCoin);
addChild(cupOne);
addChild(cupTwo);
addChild(cupThree);
}
This way, you'd not be creating new instances of those objects each time, but just adding/removing them from the display list as needed. Which might be what you desire.

Updating one of several views with event

I don't undertand mechanism of events in actionscript completely, so please forgive if a question is dump. Supose that we have a Controller (extends EventDispatcher) and several views, note that views can be instances of various classes. Supose that each view listens CustomEvent.SOMETHING_CHANGED. The question is if I do dispatchEvent(new CustomEvent(CustomEvent.SOMETHING_CHANGED)) in Controller, will event come to each of listeners or it will be caught by first of views and will not go further.
Thank you in advance!
Yes, it will be passed to all listeners until one of them calls the stopImmediatePropagation method of the event object (this will only stop the event if it is cancelable)
For any object to observe an event dispatched by another object, there are several conditions:
The object has to be a display object.
The object dispatching that event has to be a child of the listening object.
If the parent object is listening for the bubbling phase(default), then bubbling has to be set to true during event creation.
dispatchEvent(new Event(TYPE_NAME, true));
Otherwise it could be captured in the Capture phase, add event listener with 'useCapture = true to accomplish this.
addEventListener(TYPE_NAME, onFuncName, true);
In all other cases, an object can only capture events dispatched by the object itself in the target phase.
Here is a code example:
package regression
{
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.EventPhase;
/**
* ...
* #author ...
*/
public class Check_event_listening_1 extends Sprite
{
public const EVENT_DANCE : String = "dance";
public const EVENT_PLAY : String = "play";
public const EVENT_YELL : String = "yell";
private var baby : Shape = new Shape();
private var mom : Sprite = new Sprite();
private var stranger : EventDispatcher = new EventDispatcher();
public function Check_event_listening_1()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
trace("test begun");
addChild(mom);
mom.addChild(baby);
stage.addEventListener(EVENT_YELL, onEvent);
this.addEventListener(EVENT_YELL, onEvent);
mom.addEventListener(EVENT_YELL, onEvent);
baby.addEventListener(EVENT_YELL, onEvent);
stranger.addEventListener(EVENT_YELL, onEvent);
trace("\nTest1 - Stranger yells with no bubbling");
stranger.dispatchEvent(new Event(EVENT_YELL, false));
trace("\nTest2 - Stranger yells with bubbling");
stranger.dispatchEvent(new Event(EVENT_YELL, true));
stage.addEventListener(EVENT_PLAY, onEvent);
this.addEventListener(EVENT_PLAY, onEvent);
mom.addEventListener(EVENT_PLAY, onEvent);
baby.addEventListener(EVENT_PLAY, onEvent);
stranger.addEventListener(EVENT_PLAY, onEvent);
trace("\nTest3 - baby plays with no bubbling");
baby.dispatchEvent(new Event(EVENT_PLAY, false));
trace("\nTest4 - baby plays with bubbling");
baby.dispatchEvent(new Event(EVENT_PLAY, true));
trace("\nTest5 - baby plays with bubbling but is not a child of mom");
mom.removeChild(baby);
baby.dispatchEvent(new Event(EVENT_PLAY, true));
mom.addChild(baby);
stage.addEventListener(EVENT_DANCE, onEvent, true);
this.addEventListener(EVENT_DANCE, onEvent, true);
mom.addEventListener(EVENT_DANCE, onEvent, true);
baby.addEventListener(EVENT_DANCE, onEvent, true);
trace("\nTest6 - Mom dances without bubbling - everyone is listening during capture phase(not target and bubble phase)");
mom.dispatchEvent(new Event(EVENT_DANCE, false));
trace("\nTest7 - Mom dances with bubbling - everyone is listening during capture phase(not target and bubble phase)");
mom.dispatchEvent(new Event(EVENT_DANCE, true));
}
private function onEvent(e : Event):void
{
trace("Event was captured");
trace("\nTYPE : ", e.type, "\nTARGET : ", objToName(e.target), "\nCURRENT TARGET : ", objToName(e.currentTarget), "\nPHASE : ", phaseToString(e.eventPhase));
}
private function phaseToString(phase : int):String
{
switch(phase)
{
case EventPhase.AT_TARGET :
return "TARGET";
case EventPhase.BUBBLING_PHASE :
return "BUBBLING";
case EventPhase.CAPTURING_PHASE :
return "CAPTURE";
default:
return "UNKNOWN";
}
}
private function objToName(obj : Object):String
{
if (obj == stage) return "STAGE";
else if (obj == this) return "MAIN";
else if (obj == mom) return "Mom";
else if (obj == baby) return "Baby";
else if (obj == stranger) return "Stranger";
else return "Unknown"
}
}
}
I would be glad to shed more light on the subject.