Flash/AS3 Cookbook

From ThinkyWiki

Jump to: navigation, search

Contents

HTML Encode / Decode

public function htmlUnescape(str:String):String {
  return new XMLDocument(str).firstChild.nodeValue;
}
public function htmlEscape(str:String):String {
  return XML( new XMLNode( XMLNodeType.TEXT_NODE, str ) ).toXMLString();
}

Object Dynamic Properties

Arrays in ActionScript don't have named keys, so if you want a keyed array you have to use an Object. Objects can have properties added to them at any time without declaring them ahead of time. These dynamic properties can have any string as the key. The following code snipped demonstrates the use of dynamic properties to store values that can be retrieved by property name.

var myThing:Object = { width: 10, height: 25, origin: 'top left' };
myThing.dynprop = 'anything at all';
myThing['prop name with spaces'] = new Object();
for (key in myThing) {
  trace(key +" is "+ myThing[key]);
}

Load an XML file

Loading an XML file requires a responder function to handle the load completion. This code snippet does the necessary setup. See the following example for the parser.

private function initWithXMLFile(inXMLFile:String = 'xml/sprocket-data.xml'):void {
  // Create a URLLoader, make a listener for completion, and load the XML
  var loader:URLLoader = new URLLoader();
  loader.addEventListener(Event.COMPLETE, xmlLoaderCompleted);
  loader.addEventListener(ErrorEvent.ERROR,
    function(e:Error)  {
      trace("Error loading " + inXMLFile);
    }
  );

  loader.load(new URLRequest(theFeed));
}
private function xmlLoaderCompleted(e:Event):void {
  parseSprocketXML(new XML(e.target.data));
}

Parse XML Data

The load completion function takes care of parsing the XML and updating the data state. The new XML accessors make it easy to select elements you know about, while the traversal functions allow you to step hierarchically through the structure. This simple example uses the traversal method to gather sprocket data and store it all into an array of ad-hoc "sprocket" objects.

private function parseSprocketXML(xmlData:XML):void {
  var si:uint = 0;
  var groupsList:XMLList = xmlData.sprocket_group;
  for each (var groupElement:XML in groupsList) {
    var mySprocketGroup = new Object();

    // sprocket_group > ...
    for each (var groupChild:XML in groupElement.children()) {
      var gn:String = groupChild.name();
      switch (gn) {
        // sprocket_group > sprocket
        case 'sprocket':
          var mySprocket:Object = new Object();
          mySprocket.group = mySprocketGroup;
          mySprocket.index = si++;
          // sprocket_group > sprocket > ...
          for each (var sprocketChild:XML in groupChild.children()) {
            var sn:String = sprocketChild.name();
            switch (sn) {
              // sprocket_group > sprocket > area
              case 'area':
                var theArc:Object = new Object();
                for each (var arcAttr:XML in sprocketChild.attributes()) {
                  theArc[arcAttr.name().toString()] = arcAttr.valueOf();
                }
                if (mySprocket.arcs == null) mySprocket.arcs = new Array();
                mySprocket.arcs.push(theArc);
                break;

              default:
                // for other tags add a dynamic property
                mySprocket[sn] = sprocketChild.attribute('value');
                break;
            }
          }
          // initialize the data structures for easy access
          if (mySprocketGroup.sprockets == null) {
            mySprocketGroup.sprockets = new Array();
          }
          mySprocketGroup.sprockets.push(mySprocket);
          break;

        default:
          // for other tags add a dynamic property
          mySprocketGroup[gn] = groupChild.attribute('value');
          break;
      }
    }

    // push the completed sprocket group
    _sprocketGroups.push(mySprocketGroup);
  } 

  dispatchEvent(new SprocketEvent(SprocketEvent.XML_LOADED));
}

Create and Save XML Data

Saving a file out of Flash requires Flash Player 10.0 or higher. XML can be created from raw XML snippets or strings. This example uses property traversal to convert dynamic properties into xml tags, which are then nested into containers, and finally sent off to disk through a save dialog.

private function exportAsXML():void {
  var discSize:Number = 10.0;
  var key:String;

  // Create a PLATE xml object with inner properties
  var plateProps:Object = {
    WIDTH: discSize,
    HEIGHT: discSize,
    ORIGIN: 'top left'
  };
  var thePlate:XML = new XML(<PLATE></PLATE>);
  for (key in plateProps) {
    thePlate.appendChild(new XML("<"+key+">"+htmlEscape(plateProps[key])+"</"+key+">"));
  }

  // Convert TextArc objects into ARCTEXT xml
  for each (var anArc:TextArc in _textArcs) {
    var arcProps:Object = {
      CENTERX: discSize / 2.0,
      CENTERY: discSize / 2.0,
      RADIUS: anArc.starradius,
      ROTATION: anArc.startangle,
      FONT: anArc.font,
      HEIGHT: anArc.archeight,
      JUSTIFY: 'left',
      TEXT: anArc.text
    };
    var arcText:XML = new XML(<ARCTEXT></ARCTEXT>);
    for (key in arcProps) {
      arcText.appendChild(new XML("<"+key+">"+htmlEscape(arcProps[key])+"</"+key+">"));
    }
    thePlate.appendChild(arcText);
  }

  // Put it all into ENGRAVINGTEMPLATE tags
  var theXML:XML = new XML(<ENGRAVINGTEMPLATE version="1.0"></ENGRAVINGTEMPLATE>);
  theXML.appendChild(thePlate);

  // An XML object can be saved directly
  var xmlFile:FileReference = new FileReference();
  xmlFile.save(theXML, "untitled.xml");
}

TODO

  • Manipulating, comparing, searching and replacing strings
  • Compare to a sprocket loader that uses xml accessors
  • Converting between data types
  • Extending classes
Personal tools