Loading Text


One of the simplest ways to work with data is to load blocks of text either from a text file or from an Internet resource. Although you can certainly embed text in an SWF file, loading text at runtime has the following advantages:

  • You can manage when the text is loaded. When you embed text in an .SWF, the text loads as part of the SWF file. However, when you load text at runtime, you can load the text only when the application requires it. For large amounts of text, this can be a significant advantage.

  • Editing text files is generally easier than assembling strings with ActionScript. This is especially true when the text contains HTML elements or lots of non-standard Unicode characters.

  • Loading text at runtime allows you to update the context without having to recompile and redeploy a new .swf. This is especially true when the text is loaded from a dynamic resource such as a ColdFusion page where the content is retrieved from a Web service, a database, or some other source that is updated frequently.

Although you can load text with any of the techniques described in this chapter, this section focuses on the simplest mechanism for loading blocks of text. Using the flash.net.URLLoader class, you can load data from a URL. When you use URLLoader, you also must use the flash.net.URLRequest class to specify the URL from which you want to load the content. The following statement constructs a new URLRequest object that points to a text file called data.txt that is stored in the same directory as the SWF file:

var request:URLRequest = new URLRequest("data.txt");


You must then create a URLLoader object before you can load data using the URLRequest object. The URLLoader constructor does not require any parameters, as you can see here:

var loader:URLLoader = new URLLoader();


Note

Although it is not required, you can optionally pass a URLRequest object to a URLLoader constructor to begin a data request immediately.


URLLoader objects dispatch complete events when the data loads. For that reason, you'll almost always want to register a listener for the complete event:

loader.addEventListener(Event.COMPLETE, onData);


You can then use the load() method to load the data. The load() method requires that you pass it a URLRequest object specifying the URL of the data to load, like this:

loader.load(request);


The load() method initiates the request for the data and works asynchronously. Flash Player does not wait for the response before continuing to execute the code. It simply makes the request; when the data loads, the URLLoader object dispatches events, including the complete event when the data has completely loaded.

When the complete event occurs, the URLLoader object notifies all listeners. The listeners receive an event parameter with a target property that references the URLLoader object dispatching the event. The URLLoader class defines a data property that contains the data that was loaded. The following event listener uses trace() to output the data that was loaded:

private function onData(event:Event):void {    trace(event.target.data); }


Next, we'll look at a simple example that uses the Model View Controller (MVC) pattern (described in Chapter 3) to load and display four different limericks from text files. This example uses four text files called limerick0.txt, limerick1.txt, limerick2.txt, and limerick3.txt. The files contain the following text (each block of text is a different file):

There was an Old Man on a hill, Who seldom, if ever, stood still; He ran up and down, In his Grandmother's gown, Which adorned that Old Man on a hill. - Edward Lear There was a Young Lady whose chin, Resembled the point of a pin; So she had it made sharp, And purchased a harp, And played several tunes with her chin. - Edward Lear There was a Young Lady whose eyes, Were unique as to colour and size; When she opened them wide, People all turned aside, And started away in surprise. - Edward Lear There was a Young Lady of Bute, Who played on a silver-gilt flute; She played several jigs, To her uncle's white pigs, That amusing Young Lady of Bute. - Edward Lear


Creating the LimerickData Class

Next, we'll create a model class called LimerickData that essentially acts as a wrapper for a URLLoader object:

package com.peachpit.aas3wdp.limerickreader.data {    import flash.events.EventDispatcher;    import flash.net.URLLoader;    import flash.net.URLRequest;    import flash.events.Event;    import flash.net.URLVariables;    import flash.net.URLRequestMethod;    import flash.net.URLLoaderDataFormat; public class LimerickData extends EventDispatcher {    private var _loader:URLLoader;    private var _limerick:String;    private var _ids:Array; // Retrieve the current limerick string. public function get limerick():String {    return _limerick;   } public function LimerickData() {   _loader = new URLLoader();   _loader.addEventListener(Event.COMPLETE, onData);   _limerick = "";   // Store indices to use to reference each of the   // text files.   _ids = [0, 1, 2, 3];  } // Advance to the next limerick. public function next():void {   // Retrieve a random element from _ids.   var index:uint = uint(_ids[Math.floor(Math.random() * _ids.length)]);   // Load the text from one of the files.   var request:URLRequest = new URLRequest("limerick" + index + ".txt");   _loader.load(request);   } // The data has loaded. Set the limerick text, and dispatch // an event to notify listeners. private function onData(event:Event):void {   _limerick = _loader.data;   dispatchEvent(new Event(Event.CHANGE));   }  } }


We'll use the LimerickData class as a data model for the application. As the limerick changes, it will notify listeners.

Creating the LimerickView Class

The LimerickView class listens for change events dispatched by a model object, and it then draws itself using the data passed into the constructor:

package com.peachpit.aas3wdp.limerickreader.views {    import flash.display.Sprite;    import com.peachpit.aas3wdp.limerickreader.data.LimerickData;    import flash.text.TextField;    import flash.text.TextFieldAutoSize;    import flash.events.Event; public class LimerickView extends Sprite {    private var _data:LimerickData;    private var _textField:TextField;    // Pass in the data model to use.    public function LimerickView(data:LimerickData) {      _data = data;      // Listen for change events.      _data.addEventListener(Event.CHANGE, draw);      // Create the text field to use to display the       // limerick.      _textField = new TextField();      _textField.border = true;      _textField.autoSize = TextFieldAutoSize.LEFT;      addChild(_textField);      draw(); } // The data has changed, so display the new text. public function draw(event:Event = null):void {   _textField.text = _data.limerick; } } }


This class simply creates a text field that displays the current limerick text value from the data model.

Creating the Main Class

The main class simply creates an instance of the model and an instance of the view and uses a timer to load a random limerick every five seconds:

package {    import flash.display.Sprite;    import com.peachpit.aas3wdp.limerickreader.views.LimerickView;    import com.peachpit.aas3wdp.limerickreader.data.LimerickData;    import flash.utils.Timer;    import flash.events.TimerEvent;    import flash.events.Event;    public class LimerickExample extends Sprite {       private var _data:LimerickData;       public function LimerickExmmple() {       _data = new LimerickData();       var view:LimerickView = new LimerickView(_data);       addChild(view);       startTimer(null);    }    private function startTimer(event:Event):void {        var timer:Timer = new Timer(5000);        timer.addEventListener(TimerEvent.TIMER, onTimer);        timer.start();        onTimer();    }    private function onTimer(event:TimerEvent = null):void {      _data.next();    }   } }


This class creates an instance of both the model and the view. It uses a timer to advance the model to the next limerick every 5 seconds. When you run this code, you should see the limericks displayed on the screen, changing every 5 seconds.




Advanced ActionScript 3 with Design Patterns
Advanced ActionScript 3 with Design Patterns
ISBN: 0321426568
EAN: 2147483647
Year: 2004
Pages: 132

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net