triangulito
triangulito

Reputation: 202

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?

Upvotes: 1

Views: 505

Answers (2)

Saad
Saad

Reputation: 28486

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.

Upvotes: 2

debu
debu

Reputation: 910

I'm not entirely sure, but it could be that because the MovieClip with the event listener is nested inside another MovieClip, it doesn't have access to the 'stage' Object.

One thing to try, would be to remove the eventListener from stage, so it simply looks like this:

addEventListener(KeyboardEvent.KEY_DOWN,keyPressedDown);

That might work. Alternatively, you could just keep the event code in the parent MovieClip. Hope these things might help.

Debu

Upvotes: 0

Related Questions