AS3 - How to assign names or tags to loader?

I have a list of images that i’ve loaded with the Loader class, but I’m having a tough time assigning them unique names. I need unique names because I want to remove certain images after a while. Is there a way to assign loaders a name or some unique tag so i can remove them later? thanks.

Here's part of my code

for (var i = startnum; i < endnum; i++){
    var thumb = panels[i].@THUMB;
    var thumb_loader = new Loader();
    thumb_loader.load(new URLRequest(thumb));
    thumb_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded);

    thumb_loader.name = i;
    thumb_loader.x = (thumb_width + 20)*i;
}

I tried to use getChildByName in another function..

var myLoader:Loader = getChildByName( "1" ) as Loader;
myLoader.unload();

But it's giving me Error #1009: Cannot access a property or method of a null object reference.

I tried to put thumb_loader as global variable, and do this

var myLoader:Loader = thumb_loader.getChildByName( "1" ) as Loader;

But it's still not working. Thanks.

Answers


All display objects in ActionScript 3 have a name property. Whenever you create a Loader object you can assign a name to it like so:

var myLoader:Loader = new Loader();
myLoader.name = "myUniqueName";
myLoader.load( .... );
addChild( myLoader );

If you'd like to refer to the loader by the name you gave it, use the getChildByName() method.

var myLoader:Loader = getChildByName( "myUniqueName" ) as Loader;
myLoader.unload();

Please be mindful that getChildByName() will only work after you've added the Loader(s) to the display list using addChild(). Otherwise, you'll have to create something to store the references to the Loader objects in, such as an Array and refer to the loaders via that Array. For example, outside your loop you could create an Array named loadersArr. In your loop you would do:

loadersArr["uniqueName"] = thumb_loader;

Then you can refer to your loaders with your unique name through the loadersArr Array.

var loaderToUnload:Loader = loadersArr["uniqueName"];
loaderToUnload.unload();

Without seeing more of your code, its difficult to understand the scope in which this code resides and where any other code that may try to reference these Loaders resides.


Need Your Help

how to troubleshoot: why I can't obtain a lock?

c# visual-studio-2010

In a debugger I "froze" when executing such line of code: lock (myvar) Obviously someone else is holding myvar. However I expect at this line that myvar should be free. So I want to know which part...

Get bootstrap-datetimepicker to appear on field and on icon, without duplicating

javascript jquery ruby-on-rails twitter-bootstrap-3 datetimepicker

I am trying to get bootstrap-datetimepicker to work the way I want it to. Normally the datetime selector only pops up when clicked on the icon. But I want it to pop up when clicked on the field and...