Question

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.

Was it helpful?

Solution

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.

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