Question

I'm a C# developer who is trying to learn some AS3, so this is going to be a pretty newbie question.

I'm getting confused with regards to scope and GC, as I have a custom MovieClip-extending class (Slide) which I create instances of within a loop and push() into an Array, but afterwards the items are null when I pull them out of the collection.

var ldr:URLLoader = new URLLoader();
ldr.load(new URLRequest("presentation.xml"));
ldr.addEventListener(
    Event.COMPLETE,
     function(e:Event):void {
         config = new XML(e.target.data);
         for (var i:Number = 0; i < config.slides.slide.length(); i++)
         {
             var node = config.slides.slide[i];
             var slide:Slide = new Slide();                      
             slides.push(slide);

             addChild(slide); // Works fine
         }
     }
);

slides.forEach(function(e:*, index:int, array:Array):void
    {
        addChild(e); // Causes "Parameter child must be non-null" exception
    }
);

I would like to be able to references the slides later in order to toggle them as needed - how can I keep the reference to my new objects?

Update: It appears there were two problems with this. The forEach call was being made before the URLLoader's complete event was called, and also forEach doesn't seem to work as expected. Here is the final working code:

var ldr:URLLoader = new URLLoader();
ldr.load(new URLRequest("presentation.xml"));
ldr.addEventListener(
    Event.COMPLETE,
    function(e:Event):void {
        config = new XML(e.target.data);
        for (var i:Number = 0; i < config.slides.slide.length(); i++)
        {
            var node = config.slides.slide[i];
            var slide:Slide = new Slide();                      
            slides.push(slide);
        }
        for each (var sl in slides)
        {
            addChild(sl);
        }
    }
);
Was it helpful?

Solution

Try this. Let's see if it traces your slides.

var ldr:URLLoader = new URLLoader();
ldr.addEventListener(Event.COMPLETE, processXML);
ldr.load(new URLRequest("presentation.xml"));

function processXML(e:Event):void {
    config = new XML(e.target.data);
    var slide:Slide;
    for (var i:Number = 0; i < config.slides.slide.length(); i++)
    {
        var node = config.slides.slide[i];
        slide = new Slide();                                          
        slides.push(slide);

        addChild(slide); // Works fine
    }

    for each(var slide:Slide in slides){
        trace(slide);
    }
 }

I am coding it here so I can't assure you it'll work. Also, I don't have the rest of the code so you'll have to test it by yourself.

OTHER TIPS

Your slides.forEach call is executing before the event is being fired so the slides array has no values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top