Search:

Sections:

Language
API, Various
Event Stuff
XML
Sound
Fonts, CSS
fl package
Beyond the Client
Security-related
Flex Builder-related
Flash-related
Flash IDE-related
Tips
Dev Tools
Misc.

Related pages

AS3_Code_Snippets
SWFAddress
Keycodes

Related files, links

http://livedocs.adobe.com/flex/3/langref/index.html
Attach:avm2overview.pdf
Attach:AdobeCodingConventions.pdf


Language

TYPES

	int
		signed integer; range ~ -2 to 2 billion; default value = 0

	uint 
		unsigned integer; range ~ 0 to 4 billion; used for color values

	Number
		default value is NaN (ie, isNaN(myNumber)===true)

	null
		default value for strings and Objects of all kinds

	undefined (== void)
		default value for _untyped_ variables

	NaN
		default value for Numbers

	typeof
		returns the type of a variable, eg, "typeof myVariable"		

	CASTING

		'Upcasting' - is always 'safe'

		'Downcasting' - is potentially dangerous

VECTORS

	var vec:Vector.<int> = new Vector.<int>();
	var vec:Vector.<int> = new Vector.<int>(5, true); // fixed mode

	- When not in fixed mode, does all the methods available to Array (except sortOn)
	- When in fixed mode, won't do push, pop, shift, splice, etc.



STATEMENTS

	FOR IN / FOR EACH IN

		Order is not guaranteed, except for XML, where enumeration happens in 
		same order as in the XML document

		FOR IN goes thru variable names (or array keys), whereas FOR EACH IN 
		goes thru values!

ARRAYS

	FIFO == stack == .push & .pop
	FILO == queue == .push & .shift

	indexOf, lastIndexOf

		not just for strings!

	splice - 
		a.splice(startIndex, deleteCount, item1, item2, ...);
		or, a.splice(3) -- cuts down the length of the array to just 3

	push - 
		add element to the end

	unshift -
		insert element at the beginning

	delete - does NOT 'delete' the element, just sets it to undefined		

	concat - 
		combinedArray = thisArray.concat(thatArray);
		or, combinedArray = this.Array.concat(newElement1, newElement2, ...)

	sort - 
		myArray.sort(compareFuction, Array.NUMERIC|Array.DESCENDING|Etc.);


	sortOn -
		myArray.sortOn("fieldNameInQuotes", Array.NUMERIC|Array.DESCENDING|Etc.);


	ALTERNATIVE: LINKED LISTS

	Don't forget about doing linked lists, too, by creating objects that 
	point to each other. And then using iterator pattern.

	Eg:
		myNode.data = "something"; 
		myNode.next = someOtherNode; 
		myNode.previous = differentNode;


STRINGS

	Replace:
	s = s.replace(/this/g, "that");

ACCESS MODIFIERS

	public		accessible from any package
	protected	accessible from within package and from descendents of class
	internal	accessible from descendants of class
	private		accessible from within class only
	static		...

	* "private" can yield some performance gains...

SUPER

	class myClass extends yourClass 
	{
		function myClass() {
			super( whatever, misc, parameters, here );
		}
	}

INTERFACES	

	Interfaces can inherit from other interfaces

	Classes can implement more than 1 interface

	'MARKER INTERFACE' - empty interfaces used to 'mark' 
		classes as having some feature; eg, IBitmapDrawable


MISC SYNTAX THINGS

	var myObject:Object = { thisProperty:new SpecialClass(), 
		thatProperty:new StupidClass("ugly.png") };	

	name = name || child.name || child.id;

API, Various

DISPLAYLIST, ORDERING STUFF:

	.addChild()
	.addChildAt()
	.getChildAt()
	.getChildByName()
	.getChildIndex()
	.setChildIndex()


LOADING SWF'S (or IMAGES)

	The Loader class is used to load SWF files or image (JPG, PNG, or GIF) files. 
	Use the load() method to initiate loading. The loaded display object is added 
	as a child of the Loader object.

	(Use the URLLoader class to load text or binary data.)

	A Loader object can only have one child display object—the display object 
	that it loads. 
	To remove a loaded display object, you must remove the Loader object from its 
	parent DisplayObjectContainer child array.


		var ldr = new Loader();
		ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
		ldr.load( new URLRequest("icon.gif") );

		private function onLoadComplete(e:Event)
		{
			myDisplayObject = ldr.content;
			// or...
			myImage = Bitmap(ldr.content);
			myBitmap = myImage.bitmapData;
		}

LOADING SWF'S II (SHELL CONSIDERATIONS)

	If a SWF which is to be loaded in is a Flash 9 SWF with a custom Document 
	class (or not?), all the named stuff on stage which is referenced in the 
	document class'es code will generate compile errors. Therefore you must do 
	the following:

	In the FLA, under Publish Settings > AS Settings, turn OFF "Automatically 
	declare stage instances"

	Then, in the document class, add public variable declarations for each 
	instantiated MovieClip (eg, "public var myMovieClip:Movieclip;").

	Additionally, if you dynamically instantiate linked library items, you must 
	create 'stub' classes for each.


RUNTIME SHARED LIBRARIES

	Give library asset a class name under 'Linkage Properties', eg, as "myClassName"

	Export library asset as SWF (not SWC).

	Load the SWF.

	Store it as a class variable, eg,
		var myRslClass:Class = e.target.applicationDomain.getDefinition( "myClassName" ) as Class;

	Instantiate that class as often as desired, eg,
		var myInstance:MovieClip = new myRslClass() as MovieClip;


	Enumerate thru definitions without knowing their names in advance:
		http://etcs.ru/pre/getDefinitionNamesSource/


LOADING FLEX INTO FLASH

	http://algorithmist.wordpress.com/2008/04/30/load-flex-into-flash/


EVENT.RENDER

	Though ActionScript 3 has not aquired prepareFrame or exitFrame, it has 
	gained a new frame event, render, or Event.RENDER (flash.events.Event.RENDER).

	The render event in AS3 is a frame event that occurs after enterFrame 
	(flash.events.Event.ENTER_FRAME) allowing one more chance to do what you need 
	to do before the screen updates its display.

	Unlike enterFrame, however, the render event will not be called unless 
	the display object using it is attached to a stage (or in any display list 
	attached to the stage). Also, render is not automatically called every frame, 
	even if attached to the stage. In order for render to be called for the 
	current frame, you must make a call to stage.invalidate() 
	(flash.display.Stage.invalidate());


"GETURL"

	 navigateToURL(new URLRequest("http://www.google.com"), "_new")


BITMAPS

	The image goes in a BitmapData object, which goes in a Bitmap object, 
	which is added to the displaylist:

		var myBitmapData:BitmapData = new BitmapData(100,100,0xFF0000);
		var myBitmap = new Bitmap( myBitmapData );
		addChild(myBitmap);

STAGE

	dimensions:

		stage.stageWidth (NOT "stage.width")
		stage.stageHeight

	Scaling:

		...

	.focus
		Note, you can only successfully set focus if the Flash has focus on 
		the user's system!

MOVIECLIPS

	.currentFrame
	.currentLabel
	.currentLabels
	.totalFrames
	.nextFrame()
	.prevFrame()


DATE/TIME

	myDate.time == myDate.getTime() == myDate.valueOf

	.setTime - convert a getTime back to Date


FORMS, ETC.

	Remember to do stuff like this:

		mcKnob.tabEnabled = false;
		mcKnob.tabChildren = false;
		mcKnob.tabIndex = 666;


WEBCAM / CAMERA - Example:

	camMain = Camera.getCamera();
	camMain.setMode(320,240 15, true);
	camMain.setQuality(99999,100);
	vidMain = new Video(320,240);
	vidMain.attachCamera(camMain);	
	addChild(vidMain);

 	Camera ready event: 

		Use this:		
			camLive.addEventListener(ActivityEvent.ACTIVITY, onCamActivity);
			private function onCamActivity(e:ActivityEvent):void 
			{ if (e.activating) /* do things */ }

		Don't use this
			camLive.addEventListener(StatusEvent.STATUS, onCamStatus);
			- because it doesn't fire if security settings is 
			set to accept by default.

Auto-select webcam from the list of devices:
http://www.squidder.com/2009/03/09/trick-auto-select-mac-isight-in-flash/

	var index : int = 0;
	for ( var i : int = 0 ; i < Camera.names.length ; i++ ) {
		if ( Camera.names[ i ] == "USB Video Class Video" ) {
			index = i;
		}
	}
	//Oddly, Camera.getCamera needs a string of the camera index, NOT the name of the camera.
	_webcam = Camera.getCamera( String( index ) );


BYTEARRAY & COMPRESS

	COMPRESS/DECOMPRESS TEXT:

		var s:String = "This is a test. This is a test.";
		var ba:ByteArray = new ByteArray();

		ba.writeUTF( s );
		trace(ba.length);
		ba.compress();
		trace(ba.length);

		ba.uncompress();
		trace(ba.length);
		trace(ba.toString()); // blank

		var t:String;
		ba.position = 0;
		t = String( ba.readUTF() );
		trace(t);


KEYPRESS HANDLING -- 

	3 important things to note here. 
	Esp. allows for multiple keypresses at once (important for games, e.g.)

	s.addEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler );
	s.addEventListener( KeyboardEvent.KEY_UP, keyUpHandler );

	private function keyDownHandler( event :KeyboardEvent ):void
	{
		switch( event.keyCode )
		{
			case "W".charCodeAt():
			case Keyboard.UP:
				keyForward = true;
				keyReverse = false;
				break;

			case "S".charCodeAt():
			case Keyboard.DOWN:
				keyReverse = true;
				keyForward = false;
				break;
	[...]
	private function keyUpHandler( event :KeyboardEvent ):void
	{
		switch( event.keyCode )
		{
			case "W".charCodeAt():
			case Keyboard.UP:
				keyForward = false;
				break;

			case "S".charCodeAt():
			case Keyboard.DOWN:
				keyReverse = false;
				break;
	[...]

Event Stuff

EVENT.TARGET & EVENT.CURRENTTARGET

	Are the same unless the event source is a displayobject, in which case, 
	one might refer to a parent and one could refer to a child, etc.
	Programs typically use currentTarget to control the object that registered a 
	listener in some way.

	Better writeup:

	So what is the use of Event.currentTarget? While the target property will 
	always have its value set to the DisplayObject that originally dispatched 
	the Event, the currentTarget property always points to the DisplayObject 
	that the event is currently processing (i.e. bubbling at).

DEFAULT BEHAVIORS: PREVENTDEFAULT() - 

	Stops default behavior of an event from happening (Eg, think 
	TextEvent.TEXT_INPUT). Use it in the eventlistener. You can check if an event 
	is cancellable by checking the property CANCELABLE of the Event instance. You 
	can check if an event was canceled by calling the method ISDEFAULTPREVENTED() 
	of the Event instance. You can make a event that's cancelable by setting the 
	right parameter to true in the Event constructor... 		

REMOVING EVENTS

	Do not rely on 'useWeakReference', as the moment of garbage 
	collection cannot be relied upon. Always remove events.

MORE ON CUSTOM EVENTS	

	Custom classes that want to dispatch custom events must: 

	(1) Extend from EventDispatcher class or a class that inherits from it (like 
	DisplayObjects); 
	(2) Implement the IEventDispatcher interface and then use composition to use 
	EventDispatcher's services.

	Custom events should:

	(1) override clone() and toString().
	(2) Also might as well create own constructor that 'super's the Event class 
	constructor, too.

	HOW TO ENFORCE THE USE OF ONLY SUPPORTED EVENT TYPES 

	Override addEventListener(), check for event type, and throw 
	an error if a bad one comes up


ROLL_OUT vs. MOUSE_OUT EVENTS

	Where they differ is with their interaction with interactive object children. 
	The roll events (rollOver and rollOut) simplify the process and prevent 
	interference with child events. Essentially, this is the same as using 
	mouseOver and mouseOut with mouseEnabled set to false. mouseOver and mouseOut 
	with mouseEnabled provide a parent sprite with events from its children. 
	rollOver and rollOut keeps the events on the parent object.	 

	Basically, always use ROLL_OVER/OUT unless you have a good reason for using MOUSE_*


DETECTING IF MOUSE LEAVES FLASH AREA

	stage.addEventListener(Event.MOUSE_LEAVE, ...)

	* Remember this only works on the stage object!


EVENT PROPAGATION

	ActionScript 3 now supports event propagation - the transference of a 
	single event applying to multiple objects to each of those objects 
	instead of one - in Display objects. In ActionScript 1 and 2, "Button" 
	events (such as onPress, onRelease, etc.) handled by movie clips were 
	not propagated to that movie clip's children. This means that though 
	visually you were clicking on a child of a movie clip handling an onPress 
	event, that onPress would never make it to the child because the parent 
	movie clip handling the event would intercept it and prevent the 
	propagation of the onPress event to that child.


USE THIS - Similar to that 'Proxy' AS2 class...

	public class ProxyUtil {
		public static function create($function:Function,... $rest):Function {
			return function(... $moreRest):void {
				$function.apply(this, $moreRest.concat($rest));
			}
		}
	}

	// ...

	myMc.addEventListener(MouseEvent.CLICK, ProxyUtil.create(myHandler, param/s));


XML

WHITESPACE

	XML.ignoreWhitespace = true;


LOADING

	public function LoadXMLExample(  ) 
	{
	  var loader:URLLoader = new URLLoader(  );
	  loader.dataFormat = URLLoaderDataFormat.TEXT;
	  loader.addEventListener( Event.COMPLETE, handleComplete );
	  loader.load( new URLRequest( "example.xml" ) );
	}

	private function handleComplete( event:Event ):void 
	{
	  try {
		var example:XML = new XML( event.target.data );
		trace( example );	        
	  } catch ( e:TypeError ) {
		trace( "Error:", e.message );
	  }
	}


CREATING XML

	var example:XML = <abc><a>eh</a><b>bee</b><c>see</c></abc>;

		or

	var example:XML = <gamescore>
				 <username>{username}</username>
				 <score>{score}</score>
			  </gamescore>;

		-- where username and score are variables...

		or

	var str:String = "<gamescore><username> .. etc ..";
	var example:XML = new XML( str );

ADDING TO XML

	var example:XML = <example />;
	example.newElement = <newElement />;

		== <example><newElement/></example> 

	(See AS3 Cookbook for more...)

XML.CHILDREN()

	Returns an XMLList

ACCESSING XML STUFF

	myXml.myNodeName

		Returns an XMLList of nodes whose nodeNames are "myItem"

		So, "myXml.myItem[0]" returns the first "myItem" node within "myXml"

	DO THIS TOO
		var file:XMLList = xmlData.descendants("VideoPath");

	Filtering by attribute
		node.(@id=="hello")

LOOK HERE

	http://developer.yahoo.com/flash/articles/e4x-beginner-to-advanced.html

MORE:

	var items:XMLList = data.item.(source == "Amazon" && price < 400);  

	or..

	var sourceName:String = "Target";  
	var itemNames:XMLList = data.item.(source == sourceName); 

	Using the attribute() function:

	var filterBy:String = "name";  
	var filterValue:String = "Wii";  
	var items:XMLList = data.item.(attribute(filterBy) == filterValue); 


NAMESPACES:

	var ns:Namespace = new Namespace( xml.namespace("") );
	or,
	var ns:Namespace = new Namespace( xml.namespace("content") );

	trace(xml.ns::PhotoUploadRecord[0]);
	var node:XML = xml.ns::PhotoUploadRecord[0];
	trace(node.ns::UserName);

Sound

Sound.load(stream:URLRequest, context:SoundLoaderContext = null):void

	Once load() is called on a Sound object, you can't later load a different 
	sound file into that Sound object. To load a different sound file, create 
	a new Sound object.

	Throws... IOError


Sound.play(startTime:Number = 0, loops:int = 0, 
	sndTransform:SoundTransform = null):SoundChannel

	Returns a SoundChannel. This is the only way to get to the SoundChannel, 
	so you have to assign it here...

SoundChannel

	The SoundChannel class controls a sound in an application. Each sound playing in an 
	Adobe® Flash® application is assigned to a sound channel, and the application can 
	have multiple sound channels that are mixed together. The SoundChannel class 
	contains a stop() method, properties for monitoring the amplitude (volume) of the 
	channel, and a property for setting a SoundTransform object to the channel. 

	.position

		When the sound is playing, the position property indicates the current point that is 
		being played in the sound file. When the sound is stopped or paused, the position 
		property indicates the last point that was played in the sound file. 

		A common use case is to save the value of the position property when the sound is 
		stopped. You can resume the sound later by restarting it from that saved position. 

		SoundChannel.leftPeak, .rightPeak

		Current amplitude of the soundchannel at that moment...

SoundTransform

	Controls volume ...

SoundMixer

	SoundMixer.computeSpectrum() ...

	Global 'mute':
	SoundMixer.soundTransform = new SoundTransform(0);

Fonts, CSS

LOADING FONTS AT RUNTIME IN AS3/FLEXBUILDER

	Make a SWF:

		Make new Flash file, add font symbol to library, name it "myFont", 
		link it to "clsMyFont", compile it to "myFont.swf". 
		(Works for both TTF and OTF)

	In the AS3 project:

		private var loader:Loader = new Loader();

		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
		loader.load(new URLRequest("myFont.swf"));

		private function completeHandler(event:Event):void 
		{
			var fontLib:Class = event.target.applicationDomain.getDefinition("clsMyFont") 
				as Class;
			Font.registerFont(fontLib);

			myTextField.defaultTextFormat = 
				new TextFormat(new fontLib().fontName, 12, 0xFF0000);

			// or ... myTextField.defaultTextFormat = 
			// 		new TextFormat("myFont", 12, 0xFF0000);

			myTextField.embedFonts = true;
			myTextField.text = "hello";
		}

		Note that [font].fontName gives the name of the font as shown in the "Name" field in "Font Symbol Properties", 
		not the symbol name or the class name. (You don't want to change this).


EMBEDDING FONTS AT COMPILETIME

	* Starting with Flash Builder Beta 2, also add this: embedAsCFF='false'

	[Embed(source='C:/WINDOWS/Fonts/ARIAL.TTF', fontName='_Arial', unicodeRange='U+0020-U+002F,U+0030-U+0039,U+003A-U+0040,U+0041-U+005A,U+005B-U+0060,U+0061-U+007A,U+007B-U+007E')]  
	public static var fontArial:Class;  

		// Basic Latin plus these special characters –—…©™®“”‘’£€¥
		// "U+0020-U+007e,U+2013,U+2014,U+2026,U+00a9,U+2122,U+00ae,U+201c,U+201d,U+2018,U+2019,U+00a3,U+20ac,U+00a5" 


	Font.registerFont(fontArial);  

	textfield.embedFonts = true;
	textfield.defaultTextFormat = new TextFormat("_Arial");  


	You may not know this but Adobe has supplied us with sample unicodeRanges in the following file 
	"\Applications\Adobe\Flex Builder 2\Flex SDK 2\frameworks\flash-unicode-table.xml".

	USE THIS TOOL:
	http://www.zenoplex.jp/tools/unicoderange_generator.html

	*

	USING MULTIPLE WEIGHTS/STYLES PER FONT FAMILY:

	Note how that this works (nice!):	

		[Embed(source='../embed/fonts/HelveticaLTStd-Roman.otf', fontName='SiteSans', 
		advancedAntiAliasing="true", mimeType="application/x-font")]  
		public static var ClsFontSans:Class;

		[Embed(source='../embed/fonts/HelveticaLTStd-Bold.otf', fontName='SiteSans',
		fontWeight="bold", advancedAntiAliasing="true", mimeType="application/x-font")]
		public static var ClsFontSansBold:Class;  

		- at this point, "<bold>" works automatically as it should, 
		  as well as "myTextFormat.bold", and "myCss { font-weight:bold; }"

		- fonts don't even have to be installed on system, yay

EMBEDDING TEXT

	[Embed("assets/text/sample.txt", mimeType="application/octet-stream")]
	private static const SampleText : Class;
	byteArray = new SampleText() as ByteArray;
	string = byteArray.readMultiByte(ba.length, "iso-8859-01");
	// or..
	string = byteArray.readUTF();

	* Note on this:
		If you're getting 1 or more garbage characters at the beginning of the string,
		in the text editor, try saving as "UTF-8 without BOM", plus, use 
		readMultiByte() rather than readUTF()... o well

LOADING/USING CSS

Load the css file. Then...

	_css = new StyleSheet();
	_css.parseCSS($e.target.data);

	_textField.styleSheet = _css;
	_textField.htmlText = "<span class='thing'>Hi?</span>";


TEXTRENDERER.setAdvancedAntiAliasingTable()

	Yuk.


OTHER THINGS I SHOULD HAVE ALREADY KNOWN

	EMBEDDING FONTS IN A FLA PROJECT:
	Don't bother with adding a font as a library symbol.
	It appears that you can't control which characters to embed that way.
	Instead, do it the old fashioned way. Textfield on the stage, click 'Character Embedding', etc.


	Embedded textfields and using boldface with htmlText, CSS:

		You have to make sure to embed an extra font library item,
		which is the same font face, but with "bold" checked.
		Then it will automatically use the embedded boldface version
		of the font when you use <b>. Same applies for stylesheets		
		with "font-weight:bold"...

		An example:
		_tfDescription = _form.tfDescription;
		_tfDescription.styleSheet = myStyleSheet; 
		_tfDescription.embedFonts = true;
		_tfDescription.htmlText = "<p class='formLabel'>hello fucking <b>world</b></p>";

fl.* package

	
(Yek.)

Source

	C:\program files (x86)\Adobe\Adobe Flash CS4\Common\Configuration\Component Source\ActionScript 3.0\User Interface\fl\

Using fl components in FlexBuilder

	http://www.moock.org/blog/archives/000253.html

	1) Create a .swc file containing the desired V3 components.
	2) Add the .swc file from Step 1 to the Flex Builder project's Library path.
	3) Import and use the component classes.

	Or:

	Copy the classes you want from:
	C:\Program Files\Adobe\Adobe Flash CS3\en\Configuration\ActionScript 3.0\Classes\fl\*
	or, add that path to Project > Properties > Actionscript Build Path


	See also:
	"Issue: Develop an ActionScript 3 component for Flash CS3 
	that resizes correctly and has a live preview."
	http://flexion.wordpress.com/2007/06/27/building-flash-cs3-components/


ComboBox: 

	Remember, consists of (1) ComboBox, (2) List, and (3) TextInput

	Using embedded fonts:

		$combobox.setStyle("embedFonts", true);
		$combobox.setStyle("textFormat", fmt);
		$combobox.textField.setStyle("embedFonts", true);
		$combobox.textField.setStyle("textFormat", fmt);
		$combobox.dropdown.setRendererStyle("embedFonts", true);
		$combobox.dropdown.setRendererStyle("textFormat", fmt);		


DataGrid - 

	Uses: ScrollBar, HeaderRenderer, CellRenderer, DataGridCellEditor, and ColumnDivider

	Using embedded fonts:

		var f1:TextFormat = FormUtils.getInstance().textformatTitle;
		var f2:TextFormat = FormUtils.getInstance().textformatNormal;

		for each (var column:DataGridColumn in _dg.columns) 
		{
			var headRen:HeaderRenderer = new HeaderRenderer();
			headRen.setStyle("embedFonts", true);
			headRen.textField.antiAliasType = AntiAliasType.ADVANCED;
			column.headerRenderer = headRen;

			var cr:CellRenderer = new CellRenderer();
			cr.textField.antiAliasType = AntiAliasType.ADVANCED;
			cr.setStyle("embedFonts", true);
			cr.setStyle("textFormat", f2);
			column.cellRenderer = cr; 
		}
		_dg.setStyle("headerTextFormat", f1);

TileList - 

	Uses - ImageCell (subclass of CellRenderer), Scrollbar


Beyond the Client

	
POSTING DATA TO A SERVER PAGE

	Summary: Use URLVariables, URLRequest, and then sendToURL or navigateToURL

		var variables:URLVariables = new URLVariables();
		variables.exampleSessionId = new Date().getTime();
		variables.myName = "This is myName";

		var request:URLRequest = new URLRequest("handler.php");
		request.method = URLRequestMethod.POST;		
		request.data = variables;
		navigateToURL(request, "_self"); // ... or use sendToURL()


	SENDTOURL - Sends a URL request to a server, but ignores any response.
	NAVIGATETOURL - Opens or replaces stuff in the current browser window


POSTING DATA TO A SERVER PAGE AND GETTING STUFF BACK	

	Summary: Use URLVariables, URLRequest, and then URLLoader

		var variables:URLVariables = new URLVariables();
		variables.exampleSessionId = new Date().getTime();
		variables.myName = "This is myName";

		var request:URLRequest = new URLRequest("handler.php");
		request.method = URLRequestMethod.POST;		
		request.data = variables;

		var loader:URLLoader = new URLLoader()
		loader.dataFormat = URLLoaderDataFormat.VARIABLES
		loader.addEventListener(Event.COMPLETE, dataOnLoad)
		loader.load(myData)

		function dataOnLoad(evt:Event){
			trace(loader.data.status) 
			//status is a custom flag passed from back-end
		}		


"ROOT"/"LEVEL"

	To test if SWF is at the top level:

		this.parent == this.stage, or
		this.name == "root1" (as long as 'this' hasn't been named explicitly)

		Eg, 
			var isTestMode:Boolean = (this.name == "root1");


	To test if it's running in the browser or standalone.:

		flash.system.Capabilities.playerType == 

		*  "StandAlone" for the Flash StandAlone Player
		* "External" for the Flash Player version used by test movie mode,
		* "PlugIn" for the Flash Player browser plug-in
		* "ActiveX" for the Flash Player ActiveX Control used by Microsoft Internet Explorer


	"root" refers to the current SWF, not the top-level SWF, 
	as was the case with "_root" in AS2.


HTML EMBED/OBJECT TAG STUFF

	base!
		<object>...<param name="base" value="http://www.example.com/pages/">...</object>
		<embed ... base="http://www.example.com/pages/" ... />

		See: http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_04157


PASSING FLASHVARS

	In the HTML:

		<param name="flashvars" value="deeplink=gallery&amp;secDeeplink=image2">
		<embed ... flashvars="deeplink=gallery&amp;secDeeplink=image2" ...>

		-- or, just use querystring.

	In the AS:

		root.loaderInfo.parameters.myFlashVarName


FLASH SHELL SETUP, for the last time, please

	Use latest version of SWFObject.

		Make sure WMODE is _not_ set to opaque for the obvious reasons, plus,
		it kills the mousewheel, for some reason. 

	Use swffit (b/c it works with latest version of SWFObject)

		Add this near the bottom, below the swfobject JS action: 
		swffit.fit("flashcontent", 900, 625);


AVOIDING BROWSER POPUP BLOCKER

	This example shows it all: (right click and do "View Source")
	http://www.easternstorm.net/sassie/example2/example2-swfobject2.html

	Summary: 

	For Firefox, use 
		ExternalInterface.call("window.open" ...);
	For IE, use 
		ExternalInterface.call("function setWMWindow() {window.open('" + url + "');}");
	For everything else, use
		navigateToURL(...)


MORE ON EXTERNALINTERFACE

	Small point: To get a value using ExternalInterface, remember to use 'toString' like here:

		trace(  ExternalInterface.call("window.location.hash.toString")  );
		trace(  ExternalInterface.call("window.location.href.toString")  );

Security stuff


CROSSDOMAIN...

	<?xml version="1.0" encoding="utf-8" ?>
	<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
	<cross-domain-policy>
		<allow-access-from domain="*" />
	</cross-domain-policy>


ALLOWNETWORKING

	Is a param for object/embed tag.
	Is set to "all" by default...


SECURITY.ALLOWDOMAIN("siteA.com");

	...

ALLOW LOCAL SWF TO ACCESS LOCAL FILES

	Properties > Actionscript Compiler > Arguments: -use-network=false


CHECKPOLICYFILE...

	var loaderContext:LoaderContext = new LoaderContext();
	loaderContext.checkPolicyFile = true;
	Loader(_loader).load(_req,loaderContext); 

Flex Builder-related

COMPILER METATAGS

	[SWF(width="800", height="600", frameRate="60", backgroundColor="#8899aa", , pageTitle="DAE Test")]

SDK's

	http://opensource.adobe.com/wiki/display/flexsdk/Download+Flex+3

PROJECT SETTINGS

	Remove auto-generate HTML crap:  

		Project > Properties > AS Compiler > Uncheck 
		"Generate HTML wrapper file"

	Keep Flexbuilder from copying files into the output folder

		Project > Properties > AS Compiler > Uncheck "Copy non-embedded 
		files to output folder

	Using SWC's (of, eg, Flash library assets)

		Project > Properties > AS Build Path > Library path tab > Add SWC ...


EMBEDDING ASSETS IN FLEXBUILDER

	GENERALLY...

		http://dispatchevent.org/roger/embed-almost-anything-in-your-swf/

	IMAGE

		[Embed(source="watermark.png")] 
		public var watermark:Class;

		var imgWm:Bitmap = new watermark();
		addChild(imgWm);

		* note it's a bitmap, not a bitmapdata		


	FLASH SYMBOL 

		[Embed(source="assets.swf", symbol="callout1")]  [*]
		private var clsCallout1:Class;

		private var sprCallout1:Sprite = new clsCallout1(); 
		or
		private var mcCallout1:MovieClip = new clsCallout1(); 

		[*] where the symbol is set to "Export for Actionscript" in the FLA
		[**] The symbol must be more than 1 frame long to be cast as an mc!!



FLEXBUILDER <> FLASH 'INTEROP'

	Best method:

		Create FLA library items that are given class names. Export to SWC.

		Add SWC to Flex project library path.

		Instantiate simply with 

			var skin:MovieClip = new MySkinFromFla as MovieClip;
			(.. identical to how you'd instantiate a library item from Flash);


INSTALLING SUBCLIPSE (SVN PLUGIN)

	eclipse or fb4 >> help > install new software

		add http://subclipse.tigris.org/update_1.6.x

		check:
			coresvnkit library
			jna library
			subclipse > subclipse (req)
			subclipse > subversion client adapter (req)
			subclipse > subversion javahl native lib adapter (req)
			subclipse > subversion revision graph [?? -- 'could not be found']


USING ASDOCS

	Syntax examples:

		/**
		* Function to create widgets.
		*
		* @param $foo Name of widget to create.
		* @param $fah Size of widget
		*
		* @return Returns true if successful.
		*
		* @see killWidget
		*/
		private function createWidget($foo:String, $fah:int):Boolean ...

		If you define a setter method and a getter method, insert a single ASDoc 
		comment before the getter, and mark the setter as @private. Adobe recommends 
		this practice because usually the getter comes 1st. 

	Generating the pages:

		Create a batch file that lives inside your open FlexBuilder project. 
		Eg, "C:\Program Files\Adobe\Flex Builder 3\sdks\3.0.0\bin\asdoc.exe" 
			-doc-sources C:\Lee\worksvn\myProject\src 
			-main-title "Test" -window-title "Test" -output c:\test\

		Run it from inside Flex Builder. That should do it.

SOME SHORTCUTS

	cF8		next perspective

	csL		show shortcuts list

	cE		quick editor select

	f12		focus on editor

	csX/Y	uppercase/lowercase

*


	c/		toggle comments!
	csC		toggle block comments!

	cF11	run (not build and run)

	csT		Open type!

	sF2		go to definition!
	csP		go to matching bracket
	cQ		last edit location
	cD		delete line
	csP		go to matching bracket

	cG		find all declarations in workspace
	csG		find all references in workspace

	csO		organize imports (remove unused imports)

Flash-related

INSTANTIATING LINKED SYMBOLS:

	The regular way to create a new instance of a linked symbol is:
		var mc:MovieClip = new MySymbol() as MovieClip;
	But this code fails to compile outside the FLA to which the class is attached
	("'MySymbol' not found" or whatever)

	Try this instead:
		var class:Class = getDefinitionByName( "mcPostLoadAnimIn" ) as Class;
		var mc:MovieClip = new class() as MovieClip;

Flash IDE-related

'WINDOWSWF'

	C:\Documents and Settings\[user dir]\Local Settings\Application Data\Adobe\Flash CS3\en\Configuration\WindowSWF\

Tips

ON PRELOADERS...

	Method using frame 1 & 2 in FLA:

	(1) Frame 1:

		Put preloader assets on frame 1. Put the preloader logic in the document class:

		(a) this.stop();

		(b) On enterframe, poll root.loaderInfo.bytesLoaded and root.loaderInfo.bytesTotal.
		Update progress bar or whatever accordingly.

		(c) When bytesLoaded == bytesTotal, this.gotoAndStop(2).

	(2) Put everything else on frame 2.

		For all linked library assets that live on the main timeline on frame 2, 
		make sure "Export on first frame" is _unchecked_.

		For any linked library assets that get dynamically instantiated,
		"Export on first frame" must be _checked_! (Big downside...)

		Generate size report to see how big frame 1 is...

Dev Tools

USING CHARLES

	Install Charles.
	Install Charles Firefox extension!


INSTALLING FLASH TRACER

	1.	Install Flash Tracer

			https://addons.mozilla.org/en-US/firefox/addon/3469

	2.	Make sure using debug version of plugin

			http://www.adobe.com/support/flashplayer/downloads.html

	3.	Add mm.cfg to C:\Documents and Settings\Lee

			ErrorReportingEnable=1 TraceOutputFileEnable=1 MaxWarnings=50

	4.	The log gets updated at 

			C:\Documents and Settings\[Username]\Application Data\Macromedia\
				Flash Player\Logs\flashlog.txt

			This location is not changable! 

			If the directory and file are not there, create them!

	5.	Point FlashPlayer to that location!


USING FLEXBUILDER AS DOCS LOCALLY...

	Go to "C:\Program Files\Adobe\Flex Builder 3\plugins\com.adobe.flexbuilder.help_3.0.205647" 
	or whatever.

	Unzip "doc.zip" there. 

	From there, bookmark doc/langref/index.html.

Misc, Uncategorized


SHAREDOBJECT (gist)

	var so:SharedObject = SharedObject.getLocal("stuff");

	Do not assign values directly to the data property of a shared object, 
	as in so.data = someValue; Flash Player ignores these assignments.

	To create private values for a shared object — values that are available 
	only to the client instance while the object is in use and are not stored 
	with the object when it is closed — create properties that are not named data to store them

REFLECTION

	GET CLASS NAME

		getQualifiedClassName(myObject);

	...

	describeType() - returns a description of all events, public properties 
	and methods in XML format

	*** LOOK INTO THIS ***


GET OBJECTS UNDER POINT...

	setInterval(onIntervalDebug, 500);
	...
	private function onIntervalDebug():void
	{
		var pt:Point = new Point(stage.mouseX, stage.mouseY);
		var a:Array = stage.getObjectsUnderPoint(pt);
		var s:String = "";
		for (var i:int = 0; i < a.length; i++) { s += a[i].name + " " + getQualifiedClassName( a[i] ) + " | "; }
		trace(s);			
	}

RANDOM THINGS TO REMEMBER USING

	For strings, 'lastIndexOf' (duh)

	getQualifiedClassName()


'MULTIGRADIENT'

	http://labs.hellokeita.com/2008/01/24/multi-gradient/#comments


DOING FULL SCREEN, GENERALLY

	Add "allowFullScreen" to the HTML: so.addParam("allowFullScreen", "true");

	buttonFullScreen.visible = flashPlayerVersionDoesFullScreen;

	this.stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullScreenChange, false,0,true);

	private function onFullScreenButtonClick($e:Event):void {
		if (this.stage.displayState == StageDisplayState.NORMAL)
			this.stage.displayState = StageDisplayState.FULL_SCREEN
		else
			this.stage.displayState = StageDisplayState.NORMAL;
	}

	private function onFullScreenChange($e:FullScreenEvent):void {
		resize();
	}


	* Serious WTF: 

		If you are using an FLVPlayback component, it will take over the screen by default, so do:
		_flvPlayback.fullScreenTakeOver = false;



REGULAR EXPRESSIONS

	SYNTAX:

	Rem, don't use quotes around it. 
	Eg, s.split(/,|;| /) -- splits a string at a comma or a semicolon or a space

	VERY NICE:
	http://ryanswanson.com/regexp/#start


DESCRIBETYPE

	for..in loops only iterate through dynamic properties (of dynamic classes). 
	If you want to iterate through non-dynamic properties, use describeType.

	The describeType() method returns only public members. The method does not return private members 
	of the caller's superclass or any other class where the caller is not an instance. If you call 
	describeType(this), the method returns information only about nonstatic members of the class. 

	If you call describeType(getDefinitionByName("MyClass")), the method returns information only 
	about the target's static members.

	* Make function to recursively iterate any object (dynamic or not) and print out its values and those of its sub-objects


MOUSEWHEEL, MAC

	http://blog.pixelbreaker.com/flash/as30-mousewheel-on-mac-os-x/


ITERATING THRU A DICTIONARY

	for (var key:Object in groupMap)
	{
	    trace(key, groupMap[key]);
	}

	for each (var item:Object in groupMap)
	{
	    trace(item);
	}


USING FILEREFERENCE.SAVE(), FLASH 10:

	private var _fileRef:FileReference;

	function onSomeKindofUserEvent(e:*):void {
		_fileRef = new FileReference();
		_fileRef.addEventListener(Event.CANCEL, onFileReferenceCancel);
		_fileRef.addEventListener(IOErrorEvent.IO_ERROR, onFileReferenceIoError);
		_fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onFileReferenceSecurityError);
		_fileRef.addEventListener(Event.COMPLETE, onFileReferenceComplete);
		// ...
		_fileRef.save(myByteArray, "filename.xxx");
	}

	private function clearFileReference():void {
		if(_fileRef) {
			_fileRef.removeEventListener(Event.CANCEL, onFileReferenceCancel);
			_fileRef.removeEventListener(IOErrorEvent.IO_ERROR, onFileReferenceIoError);
			_fileRef.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onFileReferenceSecurityError);
			_fileRef = null;
		}
	}

	private function onFileReferenceCancel(event:Event):void {
		clearFileReference();
		// ...
	}

	private function onFileReferenceIoError(event:IOErrorEvent):void {
		clearFileReference();
		// ..
	}

	private function onFileReferenceSecurityError(event:SecurityErrorEvent):void {
		clearFileReference();
		// ..
	}

	private function onFileReferenceComplete(event:Event):void {
		clearFileReference();
		// ..
	}	


FLASH PLAYER VERSION NOTES

	All versions...
	http://kb2.adobe.com/cps/142/tn_14266.html

	9.0.28  - Full screen mode
	9.0.115 - 'Moviestar' h264, etc.

COMPILER NOTES

	COMPILER ARGUMENTS
		http://www.flexdeveloper.eu/forums/flex-builder-flash-builder-eclipse/list-of-flex-compiler-arguments/

Page last modified on August 23, 2010, at 10:43 PM