views:

1447

answers:

2

How do I wait for an external .txt file to load in ActionScript 3? If I use URLLoader, I have no guarantee that the file has loaded, since it dispatches an event when it's complete. I'm calling the loader function from another class, so I can't simply stick the next actions into the event listener.

+1  A: 

To load a text file (or an XML file) you can use URLLoader. Here´s an example for XML (pretty much the same) from kirupa

var loader:URLLoader;
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, xmlLoaded);

var request:URLRequest = new URLRequest("file.xml");
loader.load(request);
function xmlLoaded(event:Event):void {
    var myXML:XML = new XML(loader.data);
}

If you are calling it from another class you can pass the caller as a reference to the EventListener and handle the Event.COMPLETE from the called class:

loader.addEventListener(Event.COMPLETE, caller_class.xmlLoaded);

Ideally, you could make your loader class reusable and make it extend EventDispatcher so instead of listening the URLLoader you listen your own class. I'm not posting code for that to keep the answer simple but here´s a couple of links if you´re interested: An example for XML loader and Another example for a more complex image loader (to avoid confussions don´t read it unless you already understand the text/XML one)

I hope it helps :)


EDITED: As apparently you're looking for the dispatchEvent way here´s a couple of tips:

1) extend your class to EventDispatcher

public class YourClass extends EventDispatcher{

2) use dispatchEvent(new Event("event_name")); to dispatch the event

3) Listen to this event from another class. E.g.: loader_class.addEventListener("event_name", callback);

*4) Optionally you can change the string ("event_name") by a constant like DispatcherClass.EVENT_NAME by defining the constant in the dispatcher class public const EVENT_NAME:String = "event_name", and call it from the other class like this: loader_class.addEventListener(DispatcherClass.EVENT_NAME, callback);

I hope everything is clearer now.

ozke
Thank you! I guess there's no way of resolving this problem functionally? If I do "loader.addEventListener(Event.COMPLETE, caller_class.xmlLoaded);", then I can't keep the 2 classes separate, since caller_class is coded into to the loader class. Ideally, I'd like to call the loading function from caller_class, wait for it to finish, and continue doing stuff in caller_class.
Archagon
You don´t exactly need to reference the calling section as you could get the caller a non-typed parameter but I think what you´re looking for is the other solution I mentioned converting your loading. I´ll edit my post to explain that.
ozke
A: 

hey friend so much for the script I was looking for a way to listen when something its completed loaded, was very useful for me, thanks.

alan