Search code examples
actionscript-3actionscriptflashuiloader

addEventListener in SWF Nesting


I currently have a .swf file that is nested into another .swf file.

In the parent SWF file I use a UILoader to load the other .swf file.

uiLoader.source = "data/child.swf";

-

In the child SWF file I have

stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressedDown);

and when I run it on it's own, it works perfectly; but when I run child.swf through parent.swf stage.addEvent... give me a null reference exception.

Is the stage part of what is causing the issue?, and if so, is there a way to fix this?


Solution

  • Ok this is a good question, took me a little while to figure it out.

    Basically Flash does this wierd thing (maybe a bug?) but runs the functions before actually initializing the objects. This happens with initializing movieclips with just on stage as well:

    var mc:something = new something(); addChild(something)

    now in something.as if you had a reference to a stage in the initialize function it would give null. (reference: http://www.emanueleferonato.com/2009/12/03/understand-added_to_stage-event/)

    So basically taking that same problem and extending it to urlLoader it's running your code before actually building its hierarchy stage -> movie clips

    now in order to solve this problem do something like this in your child swf:

    import flash.events.KeyboardEvent;
    import flash.events.Event;
    import flash.display.MovieClip;
    
    addEventListener(Event.ADDED_TO_STAGE, init);
    
    
    function init(event:Event){
        trace("test");
        stage.addEventListener(KeyboardEvent.KEY_DOWN, moveBox);
        var testMC:test = new test();
        addChild(testMC);
    }
    
    function moveBox(event:KeyboardEvent){
        trace("a");
        testMC.x += 11;
    }
    

    The above is my code, you can scrap most of it, but the main thing to note is that: addEventListener(Event.ADDED_TO_STAGE, init); executes after your objects are initialized.