Wednesday 30 November 2011

Action Script


package
{
    import fl.controls.Button;
    import fl.controls.listClasses.ICellRenderer;
    import fl.controls.listClasses.ListData;
    import flash.events.Event;
    import flash.events.MouseEvent;
    
    public class ButtonCell extends Button implements ICellRenderer
    {
        private var _listData:ListData;
        private var _data:Object;
        
        public function ButtonCell()
        {
            super();
            addEventListener(MouseEvent.CLICK, onButtonClick);
        }
        
        public function set data(d:Object):void
        {
            _data = d;
        }
        
        public function get data():Object
        {
            return _data;
        }
        
        public function get listData():ListData
        {
            return _listData;
        }
        
        public function set listData(value:ListData):void 
        {
            _listData = value;
        }
 
        override public function get selected():Boolean 
        {
            return _selected;
        }
 
        override public function set selected(value:Boolean):void 
        {
            
        }
        
        public function onButtonClick(event:MouseEvent)
        {
            // do something
        }
    }
}
 
 


In your .fla file make sure you have the imports:
import fl.controls.DataGrid;
import fl.controls.dataGridClasses.DataGridColumn;
import fl.controls.listClasses.CellRenderer;
import ButtonCell;

Then, in your .fla file use this to create the column (where 'myDataGrid' is the name of your dataGrid instance):

var btnCol:DataGridColumn = new DataGridColumn("buttonColumnTitle");
btnCol.cellRenderer = ButtonCell;
btnCol.editable = false;
myDataGrid.addColumn(btnCol);
                 

To set the button label, just set the text like you would any other dataGrid cell:
myDataGrid.addItem({buttonColumnTitle:"Button Label"})

Monday 28 November 2011

Action Script


How different is ActionScript 3?

ActionScript 3 is different.  Very different.  So different, in fact, that it requires a completely new virtual machine to run it.  But at its core, its still ActionScript and as ActionScript you'll notice that many of the commands and programming concepts that applied to ActionScript 1 and ActionScript 2 still pretty much apply to ActionScript 3.  Very little, at least syntactically, has changed.  And sometimes the ActionScript 3 equivalent of ActionScript 2 code will look very similar, if not exactly the same. However, this is not always the case.  And in the end, there are enough changes to make a direct conversion between the two often very difficult.
These changes were necessary, though.  ActionScript 3 was built with efficiency and productivity in mind.  Not just efficiency in development (and this point can be argued for smaller projects but larger projects do benefit), but also playback performance where code in ActionScript 3 can be played back in the Flash Player up to 10 times (if not more) faster than ActionScript 2 code. Yes, you will find that many of the same menial tasks in ActionScript 1 and ActionScript 2 now seem to take twice as long to code in ActionScript 3, but in the end the extra speed and functionality.  The casual coder may look to the sky shaking a fist, cursing, but the advanced programmer will jump with glee in rejoice.
Lets take a look at some of the new features ActionScript 3 brings to the table:
  • Runtime exceptions – errors that are thrown at runtime (during SWF playback) to help debug your project
  • Runtime variable typing – typing which goes beyond compilation and persists during playback
  • Sealed classes – classes based on a static definition for additional robustness and performance
  • Method closures – methods are now bound to their respective class instance so 'this' in methods will never change
  • E4X – a new, easy to work with implementation of XML
  • Regular expressions – native support for regular expressions
  • Namespaces – support for namespaces not only in XML but in class definitions to set custom access to class members
  • int and uint data types – new data types for Number values allowing ActionScript to use faster integer-based math for certain calculations
  • New display list model – a new, flexible approach to managing display objects to be viewed on the screen
  • New event model – a new, listener-based event model with support for event propagation

Flash CS3 IDE

Not only has ActionScript changed, but the Flash CS3 authoring environment also sports an entirely new look.  The new interface sleeker and much more flexible than anything Flash has seen before.

Figure: Flash CS3

Note: Screenshot differences

The panel layout of these screenshots may differ from the default (or your custom) panel layout in Flash CS3.
The first thing you should notice with Flash CS3 is a new start screen - the screen that displays common tasks for having just opened Flash. Under the "Create New" column, you now see 2 options for creating FLA files, one for ActionScript 2.0 and one for ActionScript 3.0. Be sure to select the correct one when starting a new file depending on the version of ActionScript you wish to work with. If you already started working on a file and realized you selected the wrong FLA type, it's OK; these settings can always be changed after you start working with the file using File > Publish Settings....
When you start working with Flash and the new interface you'll notice a lot of additions to docking mechanism of the various Flash panels. You can arrange and dock your panels just about anywhere within the Flash window now using drag and drop (those of you having used Flash 5 may reminisce). Additionally, panels can now be collapsed into icons which, when clicked, will open up the panel as a fly out. At any time you can change a group of inconized panels back to their full display using the double arrow within the dock column's titlebar.
The panel enhancements allow for maximum use of space while still retaining easy access to your much needed panels.  For example, you could iconize the Actions panel where ActionScript is written on the right side of the screen and have it open with a single click only when you need to write code.

Figure: ActionScript panel from icon
When you write code in Flash using ActionScript 3, you're only allowed to write code on the timeline. This is a new restriction that was not true with ActionScript 2. With ActionScript 2 you could write code on the timeline as well as selected on objects on the screen such as buttons or movie clips.  Code then would be added within on() or onClipEvent() blocks and related to some kind of event associated with that object like press or enterFrame. All events for such objects in ActionScript 3 would need to be handled strictly within the timeline (or external definitions).

Figure: ActionScript cannot be assigned to selections
As with Flash 8 and Flash MX 2004 before it, Flash allows you to edit not just FLA files, but also external ActionScript (AS) files.  Like before, when editing AS files, a new document window is created that contains the code in an editor very similar to the Actions panel (the Actions panel itself cannot be used to edit external AS files).

Figure: Script file editing within Flash
Each AS document in Flash CS3 has an option in the top left of the interface to be associated with an open FLA document.  When an association is made, you can test the associated FLA when editing the AS document without having to switch over to that FLA.  Be careful, though. Unlike FLA documents, you will need to be sure to save your AS file before testing your movie. Otherwise your changes will not take effect.
When creating AS files for movie clips (class definitions that extend the MovieClip class) you can associate your class with a movie clip symbol in the library just as you did with previous versions of Flash using the linkage properties.  Additional options such as being able to specify a base class now exist for ActionScript 3.

Figure: Linkage properties
New to FLA documents with ActionScript 3 is the additional option of specifying what is known as a document class for the FLA.  This option is available within the property inspector when you have an FLA open with no objects selected.  This is not unlike class association of movie clip symbols with the linkage properties, only here you are specifying a class for the main timeline.

Figure: Property inspector's Document class option
More about working with external scripts and their association with movie clips in the library or the document will be covered later on.

Variables

Variables are words in code that represent or contain different values or data.  When you create a variable in ActionScript 3, you must use the var keyword.
var myVariableName; // var required
The var keyword has been available in ActionScript 1 since Flash 5 but only now, in ActionScript 3 is it required. The only exception is when defining a new variable value in a dynamic object instance (one whose variable definitions are not predefined) using an explicit reference to that object.
aDynamicObject.newVar = value; // only time var not used
In the above example, newVar is a new variable being defined in the aDynamicObject object without the use of var.  In fact, var can never be used with complex references, that is, any reference that requires a dot (.) or bracket access ([]) to reference the variable.
When defining a variable you must only use numbers, letters, dollar signs ($) and underscores (_) and a variable cannot start with a number.  Whereas bits32,_bits32, and $bits32 are valid, 32bits is not valid for a variable name since it starts with a number. These are the same restrictions that applied to ActionScript 2.
You will also have to be sure not to create naming conflicts with your variable names and any internal variable names already defined in the current scope of your script.  For example, when writing code in any timeline, you are writing code that is being defined for a MovieClip instance – the MovieClip instance that is represented by that timeline.  If you try to define a variable with a name that is the same as a predefined MovieClip variable (or function) you will get an error.
// Any timeline script

var name:String = "Joe"; // Error: A conflict exists with inherited definition (name)
Similarly, you should not name variables after top-level objects or functions like Array, XML, or trace or those definitions will no longer be accessible to you.

Note: Case sensitivity

Since Flash Player 7, ActionScript is case sensitive, so the variables Name and name are not the same.  This still applies to ActionScript 3.
The Flash CS3 Actions panel can sometimes be helpful in identifying conflicts since recognized keywords are highlighted as blue. If you are unsure if a variable name you are using is a conflict, check the documentation for MovieClip and see what properties and methods already exist for MovieClip (be sure to include inherited properties and methods)
New to ActionScript 3 is the restriction that you can only declare a variable with var once in any one scope or timeline in code.  In other words, if you declare the variable x at the top of your script and want to use it again at the bottom of your script, you should not use the var keyword for that variable again
var x = value; // ok

… 

var x = differentValue; // error; you can only use var once
When defining variables on the timeline in Flash, this also applies to all frames in the same timeline, not just the current frame. So if you define or declare variable x in frame 1 using var, you cannot use var with that variable again even in a different frame.
When declaring variables with the var keyword (and only with the var [or const] keyword) you have the option of specifying a variable type.  A variable's type describes the kind of value it will be holding.  This was a new feature in ActionScript 2 and continues to exist in ActionScript 3 in the same format.  So, for example, if you wanted the variable x to hold a number value, you would specify it as being of the type Number by using a colon and the term Number directly following the variable name:
var x:Number; // variable x contains number values
In both versions of ActionScript, typing like is optional.  ActionScript 3, however, is different in that it will also retain type information during movie playback, unlike ActionScript 2 which used it strictly for compile-time (during publishing) error checking.  This means that you will have to be much more respective of your type decisions, especially since you cannot redefine a variable with var a second time in ActionScript 3 (doing this in ActionScript 2 would let you use different types for one variable). You will also find that this behavior can be a little troublesome as you start working with type conflicts further down the road.
By not typing a variable at all, you can use any type you want for that variable.  ActionScript 3 also provides a special "untyped" type that represents just that – no type. It is represented by an asterisk (*).
var anyValue:*; // variable can have any type
It's always good to specify some type for your variable as it can lead to better error checking and performance.  By using the untyped type, you can specifically indicate that the variable can have any value without others reading the code to guess.
If you do not supply a variable with a default value, it will be assigned one based on its type.  If no type was supplied, it will be given a value of undefined.  The following list details the default values of different data types in ActionScript 3:
var untyped:*; // (or no typing) undefined

var boolean:Boolean; // false

var number:Number; // NaN

var integer:int; // 0

var unsignedInteger:uint; // 0

var string:String; // null

var object:Object; // null
Any other Object type results in default value of null. It should be noted that values of the type object (any kind of object including arrays and objects created from custom classes) have a default value of null, not undefined.  In fact objects in ActionScript 3 cannot be undefined.  If they have no value, then they are null.  Only with untyped variables or attempting to access variables that do not exist will get a value of undefined.
Number types are now unique in that they can no longer be undefined or null.  If they have no value, they are seen as NaN ("Not a Number").  NaN is a tricky value, however.  You can't really compare NaN with another NaN with the equality operator (==) because they probably won't be the same.  If you ever need to check to see if a number is NaN, you should always use isNaN().
if (isNaN(myNumber))  // checks to see if Number is defined
The int and uint variables types are new in ActionScript 3.  These are special kinds of Numbers that represent 32-bit integers or whole numbers.  The int type is a normal integer and uint is an unsigned integer, or a whole number whose value cannot be negative.  These kinds of numbers can only have whole number values.  They cannot be null, undefined., or even NaN like the Number type on which they are based.  Being that they are based on the Number type, however, you'll notice that they're type identities ("int" and "uint") are not capitalized.  This indicates that there is no specific object type or class definition associated with that type.  Instead, these types essentially share the Number definition with Number types (with the exception of the MIN_VALUE and MAX_VALUE constants which have different values for each type).
Number, int and uint Values
Numeric TypeValues
Number4.9406564584124654e-324 to 1.79769313486231e+308
int-2147483648 to 2147483647 (whole numbers only)
uint0 to 4294967295 (whole numbers only)
There is one other type that is also not capitalized.  This is the special void type.  This was capitalized in ActionScript 2 but is no longer in ActionScript 3 since, like with int and uint, there is no specific definition associated with it.  This type has not been seen so far as it only applies to functions.
New Basic ActionScritpt 3 Data Types
ActionScript 3.0ActionScript 2.0
*(not typed)
intNumber (loosely)
uintNumber (loosely)
voidVoid
Also new to ActionScript 3 is the behavior of the delete keyword. The delete keyword is used to delete variables from an object. Variables defined with var, however, cannot be deleted in ActionScript 3. Only dynamic variables defined within dynamic objects can be deleted with delete. For other variables, the equivalent of deleting would be to set those variables to have a value of null.
As seen above, not all variables can have null values. Variables defined as int, uint, and Number, can only have numeric values (Number also being able to have a value of NaN) which does not include null - the same applying to Boolean values which can be either true or false. For such cases, there is no equivalent to delete. Variables typed as Number could be set to NaN, but int and uint variables have to be numeric at all times and Booleans just either true or false.
// Create a dynamic object with dynamic property

var obj:Object = new Object();

obj.prop = "value";



// delete dynamic property on obj using delete

delete obj.prop



// cannot delete obj, only able to set to null

obj = null;



// int, unit, Number and Boolean

// types cannot be deleted

var intNum:int = 0;

var uintNum:uint = 0;

var numNum:Number = NaN;

var bool:Boolean = false;