Flash MX 2004 preparation guide
Contents:
Part 1: Introduction to Flash
Part 2: Variables in Flash
Part 3: Decision and looping structures
Part 4: Functions
Part 5: Events and their handlers
Part 6: Components
Part 7: Text in Flash
Part 8: Objects in Flash
Part 9: Important core classes in Flash
Part 10: Important movie and communication classes
Part 11: Using XML in Flash
Part 12: Working with other applications
Part 13: Using rich media in Flash
Part 14: Client server communication
Part 15: Flash Remoting
Part 16: Accessing web services from Flash
Part 17: Data binding and connection components
Part 18: Printing in Flash
Part 19: Flash deployment scenarios
Part 20: Development process
Part 21: Other topics
Preface
I have written this short preparation guide as a way for myself to ease studying for the
Macromedia Flash MX 2004 Certification Exam.
I provide this guide as is, without any guarantees, explicit or implied, as
to its contents. You may use the information contained herein in your computer career, however
I take no responsibility for any damages you may incur as a result of following this guide.
You may use this document freely and share it with anybody as long as you provide the
whole document in one piece and do not charge any money for it. If you find any mistakes,
please feel free to inform me about them Tom Kitta. Legal stuff aside,
let us start.
Guide version 1.1 last updated on 07/01/2006.
1. Introduction to Flash
- Timeline - is a visual representation of frames over time. Each movie clip has its own timeline.
- Frames - are units by which we measure time within Flash movie. Keyframes represent change in Stage based
asset and are represented by a rectangle with a solid circle at the bottom (as opposed to regular frames that have a hollow small
rectangle at the bottom of the large rectangle).
- Frame Rate - is measured in Frames Per Second (FPS) and represents the maximum number of frames that can be shown
per second. The root movie (level 0) frame rate overwrites frame rate of any move loaded onto it. Default frame rate is 12 FPS. Loops
execute the same number of times per second as the frame rate. setInterval() function allows for frame rate independent execution.
The maximum allowed frame rate is 120, the minimum is 0.01. Frame rate set by the developer is only an ideal which Flash player will try
to approach, but in reality it might be slower due to client system performance limitations.
- Layers - exist in Flash IDE only and are used to separate assets into independent groups that possess stacking order.
- Levels - used during run time only (not seen in the IDE). Levels are global to the whole project, i.e. there is always only one level 0
which is the root of the main movie. Items on higher level appear
on top of items on lower level, movies loaded into already occupied level overwrite movie that occupies it.
- There are many depths in each level, you can think of levels as top containers for depths.
Movie clips loaded into already occupied depth overwrite movie clips that occupy it - be careful as some system level movie clips
occupy a depth and you can accidentally remove them.
- The following are
transferred from the main movie to the child movie: frame rate, background color and frame size. The child is defined as the
movie clip on higher level than the parent. You can load both SWF and JPG files (as of Flash MX you can load JPG files).
- loadMovie() - is used to load a movie into a target movie. For example, you can create a blank
MovieClip that is used as a target for loading of JPG images or external SWF MovieClips.
- loadMovieNum() - is used for loading of external MovieClip into a specific level. Once a movie is loaded onto
level X, it replaces any previous movie that resided on level X.
- attachMovie() - used to load MovieClips that are located in the library onto the Stage. The clips load
onto some depth on some level. Related methods are duplicateMovieClip() and createEmptyMovieClip(). The first one duplicates
a movie that we already have in the library and the second one creates a new, empty MovieClip (both use depth). To remove a MovieClip use
removeMovieClip() method. In order to use attachMovie() method you must specify the linkage identifier for your movie.
- Depths - used to determine where movie clip will be shown in relation to other movie clips on the same movie clip
timeline (like z-index in CSS (Cascading Style Sheets), behind or in front of other movie clips). The depth has a range of
-16384 to 1048575, lower number movie clip is under higher number movie clip. Depths are relative to a level, they are
contained inside a level like paper sheets in a binder. Some system level objects, like cursors, occupy a depth. To manage
depths use getNextHighestDepth(), highestOccupiedDepth() and instanceAtHighestDepth().
- The DepthManager class lets you manage the relative depth assignments of any component or movie clip, including _root
and reserved depths for system-level services such as the cursor.
- When a SWF file is loaded into another SWF file, the objects contained in the first file, call it A, are not
automatically accessible to the second file, call it B. In order for MovieClip in file B to access objects in MovieClip in
file A and vice versa, you need to export objects for runtime sharing and drag relevant objects from one library
to the other.
- Shared libraries - these are SWF files that contain object that are shared among other Flash movies. Shared objects need
to be downloaded only once. You need to enter proper URL to the asset so that it is found on the web server, however for editing on
your local PC you don't need shared files to be located. Changes made to linked assets are not seen in the main movie's FLA file
during authoring mode - you need to place modified assets back into the main movie to see changes made in the library. Note that
assets that are to be placed on stage using ActionScript cannot be shared assets.
To create shared library follow these steps:
- Drop into your Flash movie all components that you want to share.
- Mark all objects that are to be shared as shared for runtime.
- In the URL box you need to type the path to the library file on web server. This will ensure
that library is found by movies that depend on it.
- Follow these steps to use a shared library:
- For ease of use of your shared library assets in your target file you need to open shared library file using File -> import -> open external library option,
- Copy objects from shared library to your library and enter URL of the shared library in the linkage properties.
- Your Flash FLA file will store copy of all objects taken from the library, however, they will not be compiled into SWF file.
You will need to specify the URL of assets you are importing.
- Changes made to the library file propagate to all files that use it.
- Author-time sharing - one source movie contains library items, however the shared items get re-copied into each user file
every time you do a test your movie clip.
- Symbols - reusable items that are created manually with the exception of movie clips, there are three main types:
graphics, button and movie clip. Lesser-used types are font and video.
- Graphic symbol has its timeline integrated with the document it is in, it has no actions and instances. There may be
problems with synchronization between nested animated graphics symbols. For example a 10-frame graphics symbol nested inside
3-frame symbol will execute only the first 3 frames of its 10-frame animation.
- Button symbol has a timeline that consists of four frames, actions are permitted only on the instance not within
button timeline. The four frames have names, they are: up, over, down and hit. You can nest MovieClip inside any frame of the
button timeline.
- Movie clip symbol has the same properties as the main document.
- Flash projects - flash project file (FLP) is XML based and can handle any file type as project member. It has some
version control built in. So far you can integrate Flash with MS Source Safe only (in Windows only, doesn't work on a Mac).
With AS files you have the ability to view changes that each user made to the file. FLA files are binary and thus changes
made to them by each user are not easily extracted.
- The default document size is 550 by 400 pixels, maximum size is 2880 by 2880 and minimum is 1 by 1. You can set the size in
relation to content size (i.e. to match then content that is in it for example). You can also set it to match current print area.
- Behaviors - snippets of ActionScript code that may be useful for beginners. Behaviors are placed on symbol instances.
Behavior menu is accessible from Window -> Development panels -> Behaviors.
- Timeline effects - these are shortcuts to common animations that are placed on the timeline. By default, they create a
graphic symbol.
- Exporting MovieClips on the first frame adversely affects Flash-streaming ability. You should consider loading MovieClips as they
are needed by your application. Use getBytesLoaded() and getBytesTotal() functions to implement a pre-loader for projects
that take a long time to load.
- The MovieClipLoader class is new in Flash 7, it allows you to implement listener callbacks that provide status information while SWF or JPEG
files are being loaded into movie clips. This class provides is an alternative to mentioned above MoveClip methods.
- Scenes are used to divide movie into logical parts, they are not used often by developers, loading movies as they are
needed by your Flash application is more object oriented.
- Differences between ActionScript version 1.0 and version 2.0:
- ActionScript code can be placed on the object instance, in a separate key frame or imported from a file (AS extension).
You can also use import keyword to import classes. As of ActionScript 2.0 class definitions have to be in AS files.
You can import classes from AS files using the import keyword. You can import whole packages using a wild card notation (*).
- As of version 2.0 ActionScript is fully case sensitive, before only keywords were case sensitive.
- Slash syntax is no longer supported in Flash 7 ActionScript 2.0 as an indicator of target path (depreciated as of Flash 5) you need
to use dot syntax. However, slash is still supported as part of ActionScript 1.0 - thus it will work in Flash 7 if you use ActionScript 1.0.
- ActionScript 1.0 has automatic data type setting based on initial variable value (if there is no value the variable has
type set to undefined). There is also automatic type conversion. In ActionScript 2.0 there is strict variable typing
present, however if you don't state variable type your variable will be assigned one based on they type of the data it is
storing at time of data type check.
- New ActionScript 2.0 keywords: class, implements, extends, interface, static, dynamic, private, public, get, set and import.
- Absolute and relative paths:
2. Variables in Flash
- Variables are names assigned by programmers for ease of programming to memory locations that store data that
changes over time (varies).
- The first character of every variable in Flash has to be one of: letter, underscore or dollar sign. The second and
subsequent characters in variable name can be: letter, underscore, dollar sign or number.
- Variable name should be different from every reserved Flash keyword and it must be unique in its scope. Variables cannot
have same name as Flash keywords. If you name a variable the same as a build in class, that class will not be available.
- Variable in local scope is only accessible from the block of code where it was declared, it is declared using the
var keyword followed by the variable name.
- Variables with timeline scope are attached to some Flash object, for example, they can be part of a MovieClip object.
They can be accessed anywhere in the Flash movie using the target path to the object they are attached to.
- Timeline scoped variables can be declared in two different ways, using assignment, like in blah = 123; or using set()
function, like in set(blah,123);. Set() function is depreciated (it was used together with eval() for dynamic variable management
in Flash 4).
- Timeline scoped variables exist for as long as the object they are attached to exists. If timeline scoped variables are no longer needed but
the object they are attached to is still useful, you can remove them using the delete keyword. The
delete keyword usage prevents (some) memory leaks.
- A property of an object is a variable that is attached to it, that variable belongs to that object.
- Global scoped variables can be accessed from anywhere in the Flash movie using their name only and exist for the
duration of the movie. They are declared using the _global keyword as in _global.blah = 123; Flash will 1st look
for a variable on the local scope, if it doesn't find it there it moves to more general scope and finally to _global scope.
In Flash 6 you had to always use the _global keyword to access global variables.
- A data type is a description of the information that variable can contain
- There are three primitive data types in Flash: 'number', 'string' and 'boolean' their corresponding wrapper classes are: 'Number', 'String' and 'Boolean' - respectively.
- String data type can be enclosed in single or double quotes. Concatenation uses plus sign (+). Escape character is a back slash (\).
- MovieClip and Object are examples of reference data types, they contain pointer to the actual data. There are many
more reference data types, for example Sound or Function. Each Flash object has its own data type.
- Other data types are: null data type, undefined data type and Function.
- Null data type is manually assigned by the programmer. It is a 'value' assigned to a variable that means the variable
has no real value (of its own data type).
- Undefined data type is system assigned and means that the variable with given name doesn't exist or it has no value
assigned to it. In Flash 7 evaluating a variable with type 'undefined' in numeric context returns NaN while in Flash 6 it returns 0. Also variable of
type undefined that is converted to a string returns undefined in Flash 7 while "" (empty string) in previous versions.
- Void data type contains value 'Void' and is used to indicate that function doesn't return anything.
- In ActionScript 2.0 programmers have the ability to use strict data types when declaring new variable names. This is done
in the following way: var blah:Number = 123 - i.e. var variableName:variableDataType. By using a strict data typing you avoid
data type misuse and mistakes related to using wrong data type. Remember that all objects have their own data type, thus you
can declare boo:Date = new Date(); or baa:Function = attachMovie;.
- Casting is supported, with syntax of type(item to convert). Built in conversion functions are Array(), Boolean(), Number(), Object() and String().
- In ActionScript 2.0 all elements are case sensitive, in difference to ActionScript 1.0 where only reserved keywords were
case sensitive.
- The functions set() and eval() are Flash 4 style methods for dynamic variable setting and evaluation,
respectively. Newer methods use the dot operator and array access for dynamic assignment and evaluation.
- Text fields can be assigned a variable that stores the text that the text field to which they were assigned contains.
The variable used by a text box should be different than the instance name assigned to that text box.
- Semicolons are not required in ActionScript except for 'for' loops. They are used for code organization only.
- Use 'var' keyword to define local variables since local variable access is fast. When declaring non-local variables you cannot
use 'var', for example there is no 'var' when declaring a global variable with _global.
- Constant enforcement is not supported by Flash, you cannot define your own constants.
- You can use operator more then once in expression as in: bo = boo = booo = 54;.
- When using increment of variable value as in a++ and ++a please note that the first method evaluates 'a' first then increments,
while the second method increments 1st then evaluates.
- You can use the following shorthand for operations: a+=10; same as a=a+10; a*=2; same as a=a*2;
- _lockroot is used to specify what _root refers to when a SWF file is loaded into a movie clip, undefined by
default, affects only _root. For example if you load file A into B you want to place this._lockroot = true; in file A to make
sure that _root in file A refers to A's _root. By default _root in A would refer to _root in B - by default root refers to the
movie at the bottom of the load stack.
- The ECMA-262 naming convention for constants states that they should have names all in upper case while instance
variable names should start with lower case and have capitalized first letter in every subsequent word in the variable name,
for example, tomsFastComputerSystem. Class names capitalize every first letter of every word in their names. Packages are all
in lower case. Interface and component naming convention is the same as for classes. These standards
are only a suggestion.
3. Decision and looping structures
- The if, else if, else structure evaluates boolean values. The == means equal, != means not equal (as in they
are not the same) while <> means not equal (in mathematical sense), || means or, &&
means and. The strict versions are === for strict equality (where 5 === "5" returns false while 5 == "5" returns true) and
!== for strict inequality. For example:
if (boo == 1) {
trace("boo is equal to 1");
} else if (boo == 2) {
trace("boo is equal to 2");
} else {
trace("boo is not equal to 1 or 2");
}
- There are many more operators, for example, '>>' and '<<' for byte shifting (signed).
- The switch, break, case is used starting from Flash version 5. The syntax is: switch(control_var){ case "some_value":
some_action; break; default: some_other_action; break;} For example:
switch(boo) {
case "Joe":
trace("Joe");
break;
case "Bob":
trace("Bob");
break;
default:
trace("Neither Joe nor Bob");
break;
}
- In the switch, if break statement is missing, the cases will fall through until a break keyword is found. In other words,
code will be executed from all cases till the 'break' keyword is found or the switch statement ends.
- Loops in Flash: while(condition is true), do{ }while(condition is true) - executes at least once, for(variable
declaration,test,variable value change), for(variable declaration in object) - used to loop through internals of an object.
For example:
for(var i=0;i<10;i++) {
trace("i is" + i); //from 0 till 9
}
for(var i in myObject) {
trace("object property type " + i + " is " + myObject[i]);
// i is a place holder for property of myObject; for example if myObject
// had property blah, i will (at some point in loop's execution) equal
// 'blah' and myObject[i] = myObject.blah
}
while (i < 10) {
trace("I is=" + i);
}
do{
trace("i is=" + i);
}while(i < 10)
- Loop iteration is tied to the frame rate of the movie unless you change it with setInterval() function. You can stop
loop iteration using the break keyword.
- The continue keyword restarts loop execution. It moves the execution head to the loop conditional, i.e. for the
while loop it moves to the 'while condition'.
- The frame rate of Flash movie set in Flash IDE is only the desired by programmer rate, actual rate may be equal
to it or be less due to limitations of client computer system.
- To create a constantly executing loop you can use onClipEvent(enterFrame) or onEnterFrame() or setInterval().
- You can catch exceptions using the try-catch block, for example:
try {
// some operation
} catch (myerror:ErrorType) {
// myerror is the expression thrown from a throw statement, instance of error class
// ErrorType is an optional type specifier for the error identifier
// some error correction
} finally {
// the code here executes no matter what, i.e. if there is an error thrown, or not
// it even executes if code above it in the try or catch section uses
// return keyword.
}
- The catch - try construct is used only for errors that are thrown by the programmer using the throw
function.
4. Functions
- If you choose to give function a name, it must be a valid identifier, same rules as for variable naming apply to function
naming. Function name is the identifier to which function code was assigned.
- Identifiers that store function name can be used just as any other identifier in assignment statement. For example,
you can assign to variable blah the function trace as in blah = trace; Now you can trace using blah("boo");.
- Primitive data types (for example strings or numbers) are passed to functions by value. Complex data types (i.e. objects)
are passed to functions by reference (pointer to the actual data structure). This means that complex objects passed to
a function can be changed by that function, while same doesn't hold true for primitive data type variables.
- Functions that don't have a name are called anonymous or function literal. After anonymous function
declaration .call() can be placed to call that function directly. Call() function has been depreciated in Flash 7. More modern
approach for anonymous function execution follow example underneath.
- Here are different methods of function invocation:
_global.booo = function() { ... } // global function
booo = function() { ... } // timeline function without strict data typing
// timeline function with strict data typing:
var booo:Function = function():Void { ... }
function booo():Void { ... } // another way to define a function
// function literal definition without call():
var boo = function(arguments) { ... };
boo(123);
// function literal called with call() function:
function() { ... }.call();
- When functions are created, they are attached to the timeline on which their declaration lies. Function can also be
declared global, for these functions no path is needed when calling them from any timeline in the movie.
- If function is to accept unknown number of parameters, the arguments object must be used. This object is an array
of parameters that are of any type. It also contains two additional properties, caller and callee. The caller is
the reference to the function that called your function (empty if function called directly from timeline), callee is the reference to
the function you are currently in. Inother words caller and callee are pointers to function objects.
- Inside the function keyword 'this' refers to the object function is in (the function becomes that object's method)
or object for which function was assigned as a method. If a function resides on the timeline and is not a method of any
object or an event handler, the 'this' keyword refers to the timeline function is on.
- Upon encountering a return keyword, the function evaluates (if any) expression proceeding the return keyword and
exits. You have to return some value from a function that has a return data type unless function's return data type is Void.
If there is no return data type specified, return keyword is optional and omission of return keyword will force the function to
return "undefined" data type.
- Functions can be called using the path to the object they are the method of, or using the call method, for example:
functionName.call(this object value,argument1,argument2 etc.) For example, if you have a function named myTest(someArg) you
can execute it using myTest.call(this,someArgValue). The 'this' object is the object that specifies the value of 'this'
inside the function body.
- Similar to the call function is the apply function. It is used as in myFunction.apply(object on which myFunction will
act,arguments array);
- Getter and setter methods are commonly known as accessor methods. These methods get and set internal object
properties of the object they are methods of.
- An action is a method that doesn't explicitly state the object it is acting on, it is implicitly is
assumed to act on the object. For example:
myObjectMC.gotoAndPlay("boo"); // here gotoAndPlay method acts on myObjectMC
gotoAndPlay("boo"); // here gotoAndPlay acts on the current MC
- The difference between a function and method is that method is attached to the object it is action on while the function has
the object it works with passed to it as an argument. For example:
myMc.dubplicateMovie("myMc2",10); // method
duplicateMovie("myMc","myMc2",10); // function
- Functions prefixed with the keyword static and placed into a class allow for their use without object instance. I.e. you
have just created a static class that is excellent in the role of library function storage.
- Function that are assigned to a variable can have thier type specified as well: var blah = function():Void { ... }.
- arguments object is an array that exists in the local scope of every function. It has three properties, caller,
callee and length. Used for recursion and anonymous callback.
5. Events and their handlers
- An event is defined as a software or hardware sent impulse that requires response from Flash.
- There are two types of events, user related and Flash system related. System events are generated by Flash,
for example the event, 'enter frame' is generated when Flash player's play head enters new frame.
- Event handlers are functions that are called by the object that they are registred by for a given event when a given event occurs. In other
words, event handlers are called by the object that generates the event and they are registered to (for that event).
The syntax is: object.eventName = function() { event handling code }. It is also acceptable to just assign to the handler
the function name with function body defined separately as in object.eventName = myEventHandlerFunctionName;.
- Any function that has the name of one of the event handlers will override it and become new event handler.
- The onClipEvent() handler is used to control MovieClip type events (such as onLoad) while the on() event handler is used to
control mouse pinter events (such as onClick).
- MovieClip and Button events can use on() and onClipEvent() only if they existed on the stage in authoring environment,
these methods cannot be used if MovieClip or button were created dynamically.
- Both onClipEvent() and on() take as argument the name of the event. The on() can take a comma delimited list of events.
They do not conflict with other event handlers of the same scope - both will run. This method will work with Flash 5+, while
using event names directly will work in Flash 6+. For example:
myMC.onEnterFrame = function() { ... } // Flash 6+
onClipEvent(EnterFrame) { ... } // Flash 5+
- The onClipEvent() and on() don't have local scoped variables like standard event handlers. Variables defined inside
them are attached to the timeline or in the event of on() in a button to the timeline of the movie clip button is on.
- All scripts placed on Button or MovieClip instance (not on the timeline) must be inside event handler (i.e.
they have to be enclosed by on(){scrip here} or onClipEvent(){scrip here}). It is possible to define custom events and
handlers for objects.
- Listeners are objects that listen for events within other objects (broadcast objects). New listeners can be added using
addListener(listener object) method. You can have multiple listeners for a single broadcaster and multiple broadcasters for
a single listener object. This makes it more flexible than the event models where multiple pieces of code can compete for the same
event. Note that this is a MovieClip class method.
- The following ActionScript 1.0 script illustrates event handler and listener (this works if you attach your object dynamically
instead of dropping it directly onto the stage):
var myObject = new Object();
myObject.onPress = function() {
// you add event handlers to the listener object now
trace("My object got loaded"); // for each listener of Stage there can be
// different implementation of onLoad event.
}
// my object will now receive events from the Stage:
Stage.addListener(myObject);
// Note that addListener is a method of MovieClip class but
// other classes also may posses this method (such as Key class)
- To un-register an object as a listener you can use removeListener(listener object name) method of broadcaster object.
- Events that are broadcasted from components are handled by event handler methods of a listener object or methods attached to
component instance name. For example, you can attach to the component instance inside onClipEvent(press) method code. More
common method is to create object that will listen for events transmitted by the component instance - listener/broadcaster model.
You can override event handler functions of components as you can with MovieClip class, to do so you need to add the word 'Handler'
to the event name as in the example that follows.
var myCheckbox:mx.controls.Checkbox;
myCheckbox.clickHandler = function(res:Object) {
// some code
}
Yet another method of handling events is based on the use of 'handleEvent' method. This way of handling events is not
recommended by Macromedia. This special method is used instead of event name attached to the listener object. It catches all
events for which listener object was registered.
Depending on the type of event handler, 'this' keyword has different meaning:
- In on() handler on MovieClip instance 'this' refers to the MovieClip instance event handler is attached to.
- In on() handler on Button instance 'this' refers to the timeline on which the button was placed.
- Inside event handler and event listener method 'this' refers to the object that defines the handler, for example,
thisRefersToMe.onPress = function() { ... }.
- Remember that components are advanced version of a MovieClip, thus their behavior is similar at low level.
6. Components
- There are 31 version 2 components, some of which are only available in Flash Professional
(i.e. data and media components are Flash Professional only), they are grouped into
5 categories: User interface, data components, screen components, media components and managers.
- The addition of first component to the Flash movie increases the size of the Flash movie by about 25kb, subsequent
additions of components don't add much weight to the Flash movie. For file size increase to be minimal after addition of a new
component, all components added to the file should be of the same type - i.e. all for example visual components.
- Most V2 components are larger in size (bytes) than their V1 counterparts, but addition of new components doesn't
translate into noticeable increase of movie file size.
- Version 2 components will work in Flash 6+, for Flash player version under 6.0.65.0 you need to turn off Optimization for
Flash Player 6.r65. ActionScript 2.0 is supported by all Flash 6 player versions.
- To add listeners to V2 components follow this sample code:
var myListObj:Object = new Object();
myListObj.click = function(eventProperties) { ... };
myComp.addEventListener("click",myListObj);
// Note that addEventListner is a method supported by many components
- The Flash version 2 components are SWC (Small Web Component) files, not like version 1 components, which were FLA files. The SWC files are
zipped files generated by Flash authoring environment.
- When installing a new version 2 component, in order for it to appear in the Component panel its SWC file must be placed
in the first run\components folder.
- You can add components by just dragging them onto the stage. To add them at runtime, their instance must already exist
in the Flash movie library.
- Items that are unused but still present in the library are not exported into SWF files unless they are explicitly set to be exported.
You may remove all unused items using a library option for such operation. For components, they are always compiled into SWF if they are present in the library.
- ActionScript component invocation methods: testMc.attachMovie("CheckBox","checkBoxComponent",3); another method:
createClassObject(mx.controls.CheckBox,"checkBoxComponent",3);
- When setting component parameters using ActionScript it is important to wait for the component to load or face undefined
behavior. For example, when using TextArea component for the first time in your movie you need to nest the statement that
sets the text property inside onLoad event handler, if the property is set on a different movie clip then the one containing the
TextArea instance. You don't need to do this for subsequent uses of the component.
this.attachMovie("TextArea","myTextArea",this.getNextHighestDepth());
myTextArea.onLoad = function() {
myTextArea.text = "Some text goes here";
}
- With the exception of Alert component all components send events that programmers can implement listeners for.
- Each component inherits the super classes UIObject and UIComponent.
- The default skin of Flash components is called Halo due to its apparent glow. Unlike version 1 components,
the version 2 components are compiled clips, thus it is not possible to just go and modify their assets in the library.
Instead, a series of theme FLA files containing component skins are located in First run\ComponentFla directory. The other
default theme (alternative to halo) is called sample.
- Theme is a collection of skins and styles.
- Styles are sets of properties that are responsible for component's look. Every theme uses a subset of available styles.
To modify/view component style properties, use setStyle() and getStyle() functions. Flash first looks for a
style on the instance, then styleName property of the instance, class declaration - CSSStyleDeclaration,
_global declaration. Also, there are other (more used) methods to set the component's skin.
- Flash MX style components which are FLA files are still supported in Flash 7.
- You may compile any MovieClip and make it into a compiled clip by right-clicking it in the library and choosing 'compile' option.
Compiled MovieClips decrease application compile time since they are already pre-compiled. However, you loose ability
to edit internal objects of compiled movie clips (through you can edit the original MovieClip and then re-compile it).
- The source files for visual components are included with Flash and can be edited. However, the same is not true for
data components.
- The functionality of media components is restricted to Flash player version 7+. Same restriction applies to the dataSet and
Resolver components.
- You should download updated version 1 components if you want to use them with Flash MX 2004 and Flash player 7.
- You should never mix version 1 and version 2 components in the same movie clip.
7. Text in Flash
8. Objects in Flash
- ActionScript 2.0 is class-based language, while ActionScript 1.0 is prototype-based language.
- Abstraction is the process of extracting only most important properties of an object - for example, what makes x
X not y in the shortest possible number of descriptive words.
- Encapsulation is a process of hiding internal processes of a class. No class should be able to modify other classes
properties without the use of accessor method(s).
- A class is encapsulation of properties (data) and methods (code). A class is like a blueprint for an object, which is an
instance of a class. When class is initiated all of its functions and variables become available to any class instance.
Classes use outside .as file in ActionScript 2.0 while in ActionScript 1.0 they can be defined using a constructor function
in any frame. Class methods and properties are its members. Class names should be different than any identifiers used in
the project. Classes can be extended only in ActionScript 2.0. Note that external class files in ActionScript 2.0 are compiled
into SWF files when the movie they are part of is compiled. Thus, any changes made to the class files require re-compile of the
application they are part of in order for the changes to take effect. External class file name should match exactly the name of
the class which is contained within it. Before classes are compiled into SWF they may be compiled as ASO (ActionScript Object) files
which is an intermediate format. Class compiled size is limited to 32767 bytes, this corresponds to roughly 1500 lines of code.
class MyClass { // ActionScript 2.0 style,
// has to be in a separate AS file
function MyClass() {
// constructor which is optional -
// system will provide one if you don't
}
}
MyClass = function () { // ActionScript 1.0 style, can be
// inside a frame, no need for a separate file
// no need for separate constructor declaration,
// as this is the constructor function
}
Object.registerClass("MyClassSymbol",MyClass);
class MyClassNew extends class MyClass {
// this is how one would extend class MyClass, this is
// only available in ActionScript 2.0
}
- In ActionScript 2.0 when you use a class (create instance of an object) and that class is not one of the built in
classes you need to specify path to the class file. The specification of the path to the class file can be done in a number
of ways:
var boo = new mx.mypackage.myclass(); // full path to the class given
var boo:mx.mypackage.myclass = new myclass(); // path in variable type
import mx.mypackage.myclass; // import the class 1st (cannot use #include)
var boo:myclass = new myclass(); // after import can use the class right away
import mx.mypackage.*; // wild cards are allowed as part of import definition
- A property is an attribute of a class that is defined like a variable. It is located in a class outside of any method of that class.
- A method is a function defined within a class. You can use the prototype keyword to attach method to a class after
its definition. When using 'prototype' keyword, there will be only one copy of the method stored in memory. For example: className.prototype.methodName = function() { }.
- A function is a block of reusable code that can be passed a list of arguments and which can also return a value.
- Properties and methods are known as class members.
- An object is an instance of a class. You can use instanceof keyword to find out of what class a given object is instance of.
// Different ways to define objects:
// ActionScript 1.0:
var myObj = new Object(); // or
var myObj = { };
// ActionScript 2.0 (very similar):
var myObj:Object = new Object(); // or
var myObj:Object = { };
- Interfaces contain only declaration of methods that are implemented in classes (classes implement interfaces). Interfaces are
available only in ActionScript 2.0. Interfaces are commonly used to define a way of communication between classes. For example,
communication methods are defined in an interface which each of classes that are going to communicate with each other implements.
Interface code has to be in a separate AS file, same as for class definition. A class can implement multiple interfaces, thus some
level of multiple inheritance is supported by AS 2.0.
Here is an example of interface declaration:
interface myInterface {
function myFunction1():String;
function myFunction2(someParameter:Boolean):Void;
} // notice only functions are present, no properties
class myImplClass implements myInterface {
var blah:string; // properties are OK here
function myFunction1():String { ... }
function myFunction2(myArgument:Boolean):Void { ... }
}
- Classpath is the list of directories in which Flash IDE will look for class and interface files. There are two
settings in Flash, document-level and global class paths.
- The document-level classpath is only for FLA files and is set in the publish
dialog box. Document-level classpath is searched first.
- The global classpath is for both AS and FLA files and is set in Preferences, $ denotes absolute path. Global class path is used
by Flash to access its built-in classes. All AS class files that are
in project directory are imported automatically without the use of import keyword (available only in ActionScript 2.0).
- Directory that contains one or more class files and is part of class path is known as a package (i.e. a grouping of classes). You may also have
sub-packages. The directory structure is traversed using a dot separator starting with the outermost directory going towards
the class name. For example blah.boob.blogins.
- Inheritance is the process of using existing classes to create new ones. Terminology: super class, subclass,
extends. Original method from overloaded function can be accessed using super keyword as in var boo = super.blah; (blah is
in parent class). Use extends keyword to extend classes (only in external script files). Only single inheritance is
allowed in Flash 7, thus a class can come only from a single parent, there is no multiple inheritance. You can go around this
limitation by using interfaces, a class can implement multiple interfaces.
- By default all class members are public. You can create private members using the private keyword. However, the
private membership is only enforced during compile time not during runtime (i.e. player will not check).
- Properties can be added from within class method's using the addProperty() method.
- Instantiated objects exist for as long as their initialization variables do in their scope. The 'this' keyword refers to
the object itself. The only exception is when objects extends MovieClip class and is initiated using attachMovie()
method or is dragged on stage (in this case the 'this' keyword refers to the timeline of the MovieClip on which object resides).
- Movie clip instances are removed using removeMovieClip() method of MovieClip object. Other objects are deleted
using delete keyword.
- Constructor function in ActionScript 1.0 construct the class itself, in ActionScript 2.0 it is a method that has the
same name as the class. There is only one constructor method per class (only one is allowed)
, it gets called when instance of the class is constructed.
If ActionScript 2.0 class doesn't have a constructor defined by the programmer, then system will provide a blank constructor.
Constructor function should not have a return type.
- Instance properties are added to the class using this keyword inside of a method. These properties can be
manipulated by each instance.
- Static properties are variables that are attached to a global class definition. Their value can be shared and set
without class initialization. Its value is global for all objects (the same).
- The #initclip [number] and #endinitclip are used to denote component initialization actions. The code will
be executed before the frame in which it resides. The [number] is used for order of initialization if more than one block of
code is present, it starts at 0. In order for a subclass to inherit from super class the later one needs to be initialized first.
- Static classes don't need to be initiated, for example, the math class methods can be called without initiating
a math object. Wrapper classes don't need a constructor, since they only provide extra functionality to a primitive type.
- Static members of a class can only access other static members of the class, not instance properties.
- Polymorphism occurs when a subclass (child class) overrides some methods of superclass (parent class) in order to make them more specialized.
- Dynamic class allows you to add properties to a class that were not part of class definition. You create a dynamic class
by using the dynamic keyword before 'class' keyword in class definition. Subclasses of dynamic class are also dynamic, with
the exception of MovieClip class which is dynamic but whose subclasses are not dynamic by default.
- Getter/Setter methods are defined with the use of 'get' and 'set' keywords.
Getter method doesn't take any parameters, while setter method takes exactly one. These special methods are invoked without
parenthesis. For example:
function set myStuff(stuff:string):Void { ... } // declaration
myObject.myStuff = "Some stuff"; // invocation
- To exclude classes from compiled SWF file (for example to save on file size) you need to create a special XML file named
[your FLA file name]_exclude.XML.
- You can attach a class to a Moavieclip symbol. When a class is attached to a MovieClip it will be
initialized each time that MovieClip is initialized. It will act as that MovieClips interface. In order to do the linking, click
on a MovieClip in the library and select "Linkage". Type in AS 2.0 class name - the class you created to interact with your movieClip. Also
check the "Export for ActionScript" checkbox. You can checkout this short tutorial for a working example.
9. Important core classes in Flash
- Build in classes are implemented in compiled language not ActionScript as before.
- There are three main types of build-in classes: ECMAScript classes (core classes), Movie classes and
client/server classes.
- Array class is used to construct indexed arrays that may have infinite number of dimensions (for associative
arrays use object Object). Array construction is CPU intensive operation. Associative array is also known as a structure.
You define new array in this way:
blah = new Array(); // indexed array
blah = new Array('a','b','c'); // another way to initialize array
blah = ['a','b','c']; // yet another way to initialize array
blah[0] = "something"; // this is how you add elements to indexed array
blah = new Object; // associative array
blah.bbb = "something"; // this is how you add elements to
// the associative array (structure)
- Boolean class is created anytime value of true or false is used in a variable. It doesn't use a constructor.
- Date class is used to either manipulate local time and date or UTC time and date (when communicating with
computers that are in another time zone). New date is created using this syntax: myNewDate = new Date(); - ActionScript 1.0.
- Error class is used to display custom error messages. Error objects are created with Error constructor function.
This class is new in Flash 7. Here is an example of error class usage:
throw new Error("Some error explanation"); // this is how you throw errors
try {
// some code that throws errors using method above
} catch(myError) {
trace(myError.message);
/* trace error message or some other action on error */
}
- Math class is a static class that provides access to arithmetic and geometric functions.
- Number class is just a wrapper for primitive data type number, it should not be mistaken for Number function that
is used to convert strings into numbers.
- Object class is used to create new objects, it sits at the root of class hierarchy in Flash.
- String class is a wrapper for primitive string data type.
- System class is used to provide information about the system on which Flash is being run by the end-user.
- Function class is the class representation of all ActionScript functions. This representation includes user and native functions.
10. Important movie and communication classes
11. Using XML in Flash
- Well formed XML document must have all of its attributes in quotes and all tags must have an end tag (or / (slash)
at the end if there is no end-tag). XML documents have only one parent tag inside of which all child tags are nested.
- A set of rules as to what is allowed in your particular flavor of XML is called a schema. XML documents are
validated against the rules of a schema, if they pass, they are valid in that DTD (Data Type Definition).
- XMLconnector component lets programmers create a schema (schema can also be imported using component inspector.
- XML documents are created using initiation of XML class. The constructor for that class can take empty string or
XML containing string. Alternatively you can use parseXML() method or load() and onLoad() methods to load XML
from external data file. Please note that the text inside XML is treated as a separate node instance. For example:
// creates blank XML object
myXMLobject = new XML();
// creates XML object that contains some XML data
myXMLobject = new XML("<sss>some xml here</sss>");
// add (overwrite if needed) XML data to XML object
myXMLobject.parseXML("<sss>some xml here</sss>");
myXMLobject.load("myXMLdataFile.xml"); // load XML data from external file
- New elements of XML document are created using createElement() or createTextNode() methods. New elements
are attached to XML document using appendChild() method. For example:
myXMLobject = new XML(); // create blank XML object
myElement = myXMLobject.createElement("blah"); // create new element
myElement.attributes.someAttribute = "12345"; // add attribute to the element
myTextNode = myXMLobject.createTextNode("some data"); // create new text node
myElement.appendChild(myTextNode); // add text into element
// append element to XML object, we created
// <blah someAttribute="12345">some data</blah>
myXMLobject.appendChild(myElement);
- Navigation can be relative, using firstChild/lastChild/nextSibling/previousSibling properties or using ChildNode arrays.
After the location is targeted the value can be extracted using nodeValue or attributes.name. For example:
// targeting using relative path
someDate = myXMLobject.firstChild.firstChild.nextSibling.nodeValue;
// targeting using childNodes arrays
someData = myXMLobject.childNodes[0].childNodes[0].childNodes[1].nodeValue;
- The sendAndLoad() method allows for POST (not GET) operation of the whole XML document. To simply send XML to the server,
without any response, use send() method.
- The ignoreWhite property of the XML object controls the way the XML parser acts upon the white space data found
between node declarations. The operation is as the name of property suggests. By default it is set to the value of 'false'.
- XMLSocket class creates persistent two-way socket. To use this class a special type of communication server is
required, server needs to be able to accept socket connections on ports above 1024 (high ports). Any text messages can be
passed as long as they are terminated by zero byte. The class has following methods: connect(host,port),
send(data) and close(). The class has following events: onData(data), onXML(xml data), onClose() and
onConnect(result). Socket which is created is persistent and allows for two way communication - Flash 5+.
Flash player 7 will look for a policy file allowing access on the domain that it is connecting to. You can load more than one
policy file using System.security.loadPolicyFile() method.
- XMLConnector component is used to simplify connection to data sources that return or get data through HTTP POST or
GET operations. This is one of the invisible Flash 7 components.
12. Working with other applications
- fscommand() is a function that takes two string arguments and doesn't return any. The first argument is the name
of the command that will be executed, the second is the parameter (or a list of parameters) that will be passed to the called
program. Flash has absolutely no control over called program, the called application has to know what to do with the arguments
passed to it. It is named after 'future splash command'.
- When the fscommand is used from the projector with attribute 'exec' the files being called must reside in the folder named
fscommand.
- Available fscommand commands (in projector) are: quit, allowscale, fullscreen, showmenu, exec, trapallkeys.
- Quit - exits the projector.
- Allowscale - if set to true projector can scale to full window size.
- Fullscreen - if set to true Flash shows movie in full screen mode with no menu items.
- Showmenu - shows or hides Flash context menu depending on whatever true or false is passed.
- Exec - executes outside file.
- Trapallkeys - sends all key events to onClipEvent() when set to true.
- When working with a browser, Flash can pass commands to it using fscommand. All commands are passed to a single javaScript
function that has to be named name_of_movie_in_embed_tag_DoFSCommand. The special function in javaScript takes 2 arguments,
command and args. From flash actions to the javaScript can be passed as in this example: fscommand("alert","Danger Will
Robinson!");
- When you publish your movie with the option of fscommand the Flash IDE will add to your HTML file all needed javaScript
framework. You will have to implement calls to your javaScript functions in the space indicated by comments.
- Another way to execute javaScript code in a browser is to use pseudo-URL format and getURL() function. For example:
getURL("javascript: alert(\"Danger Will Robinson!\")");.
- Java Script API (JSAPI) is new addition to Flash, introduced in Flash version 7. It is used to modify the Flash
authoring environment and has no effect on Flash movies.
- There are commercial product out there that extend the functionality of a flash projector (like screen saver support).
They have their own set of fscommands.
- You can use JavaScript to control many aspects of your Flash movies, like setting variables inside a movie using JavaScript. For
a complete list of options available, see Flash documentation.
13. Using rich media in Flash
- When working with large media files you should be aware that flash players prior to version 6.0.47 are unable to stop
download of streaming media (user needs to close all browser instances).
- When working with sound the Flash IDE should be used for compression, files should be imported uncompressed and of highest
quality.
- MP3's that will be streamed to the user and which are outside Flash movie should be compressed beforehand since Flash
player will not touch them.
- Imported movie clips can be placed on main time line. loadSound() is used to load external (mp3) files.
attachSound() is used with sounds in the library.
- Sound clips that are imported into Flash can be implemented in three ways: as event, streaming and linked.
- Event - load whole file before it starts playing and play it independently of the timeline, for small sounds.
- Stream - play sound with the timeline, drop frames if needed.
- Linkage - sound symbol is made and accessible in ActionScript when fully loaded.
- External sound clips can be implemented also in three ways: as external movie clip, as mp3 load and as mp3 stream.
External files should be already compressed as Flash will not modify them in any way.
- External movie clip - most common way to implement larger sound clips.
- Mp3 load - used to load the whole mp3 file.
- Mp3 stream - users will hear music almost right away, but you are unable to move around in the sound (i.e. skip tracks).
- Flash can access ID3 tags that are present in MP3 files. These tags identify the author, song title and possibly other
comments inside the mp3 file. Flash supports the following sound file formats: WAV, AIFF, MP3, QuickTime 4.
- Video files since Flash 6 are compressed using Sorenson Sparc Codec. What can be done with a movie clip can be
also done with a video clip. Flash IDE might have problems with editing and working with very large video files.
- Flash can export movies outside the FLA file into FLV file (Flash 7 pro only).
- Flash can import the following files: AVI, DV, MPG, MOV and FLV. You cannot edit the video inside Flash. When outside
video file (FLV) changes, you also need to make changes in Flash.
- External FLV files are not bound to the frame rate of the movie (unlike other formats). FLV file playback is not effected
by the original calling movie clip performance problems. FLV allows for large external files due to memory caching. You can
use callback() function to access metadata of FLV files allowing for easy captioning of sounds.
- Many applications can export FLV files that FLash can use. Video files can be implemented in three ways:
- Within SWF file (embedded).
- Progressive FLV file (Flash 7) - this is the same method SWF files are downloaded, its not streaming.
- Streaming Video, communication server needed, true two way communication.
- Flash video import wizard can do limited operations on the video that is being imported, like changing the compression level.
- Flash video is treated in Flash just like any other object. There are three media components provided in Flash Professional
for displaying video.
- Flash has microphone class and camera class that are most useful when combined with communication server.
Devices that are used with these classes can be detected using System.capabilities class methods.
- Real time text, audio and video communication requires communication server.
- The best graphics format to use in Flash is PNG since you still have some ability to edit graphics in Flash. Avoid using
graphics with transparency in Flash animation since it is very processor intensive.
14. Client server communication
- Web was created to be a stateless environment where servers push data to the clients.
- Through the use of XMLSocket object Flash allows for the server to push data to client application.
- There are two methods of requesting data from the server, get and push (get is default).
- Flash is limited to loading data from the same domain as the one from which Flash SWF file was loaded using
loadVariables() method of MovieClip object, LoadVars object and all other data loading methods. This security
restriction can be circumvented if the domain not containing Flash file has crossdomain.xml policy file (note
that these security rules apply only for files placed onto a server, SWF files executed directly on PC don't have
security restrictions placed on them). You are not restricted as to loading SWF files from other domains, just cross domain
scripting.
- Both loadVariables() method and LoadVars object require that the data be in the format of name value
pairs, URL encoded format. It is important to note that any spaces or line breaks will be interpreted as part of the data.
Your data doesn't start with ? (question mark), it is just a list of name value pairs joined by = (equals), separated
with & (ampersand) and URL escaped. The data file starts and ends with & (ampersand).
// loading variables using loadVariables method of MovieClip object
myMC.loadVariables("http://mywebAddress.com/myVars.txt");
// alternative way of using loadVariables method
loadVariables("http://mywebAddress.com/myVars.txt",myMC);
// sending variables to ColdFusion script using POST method
myMC.loadVariables("http://mywebAddress.com/myCFprocessor.cfm",POST);
// lternative way of using loadVariables method to send data
loadVariables("http://mywebAddress.com/myCFprocessor.cfm",myMC,POST);
myVarClass = new LoadVars(); // initialize new LoadVars instance
myVarClass.someVar = "123"; // add variables to the instance that we want to send
// send variables using POST method
myVarClass.sendAndLoad("http://mywebAddress.com/myCFprocessor.cfm",myVarClass,"POST");
- For variable loading from HTML form make sure that the form MIME type is set to 'application/x-www-uniform-encoded'.
- Flash can send all variables in a movie clip on which the loadVariables() method acts on using either POST
or GET method.
- The method loadVariablesNum() method is used to load variables into a level not into a target movie clip.
- Both loadMovie() and loadMovieNum() use HTTP or HTTPS protocol to send data. Other functions that rely on this protocol are
getURL(), loadVariables() and loadVariablesNum(). The loadVars and XML objects also uses this protocol.
- LoadVars class takes away the control over data input and output from MovieClip class, this method is preferred
to loadVariables() method since it gives greater control (like ability to choose which variables are being sent). This class needs to be
initiated before it can be used.
- The LoadVars class has the following methods: load(), send(), onLoad() and
sendAndLoad() among others.
- You can also send data with getURL() method as in the following example:
getURL("scriptURL","_blank","POST or GET");
// all variables on current timeline are sent using either POST or GET method
- Flash can get variables that are sent to it using <embed> tag. There are 2 ways to use this tag to send data to
Flash application:
- <embed src=flash.swf?blah=123&boo=abc&doh=1234> This is Flash 4+ method that is limited to about 1024 characters
per query string (in the src attribute).
- <embed src="flash.swf" flashvars="blah=123&boo=abc&doh=1234"> This method is for Flash 6+.
- Cross domain and subdomain access restrictions between Flash (SWF) files:
- No restrictions in Flash 5
- Cross-domain access restricted based on superdomain matching, no subdomain restrictions - Flash 6.
- In Flash 7 both cross and subdomain access has restrictions: Exact domain matching is needed; explicit permissions
for files accessed with HTTPS protocol to access files retrieved with HTTP or FTP protocols are also needed.
- For example, to access files on www.yoursite.com from files on www.mysite.com you need to use System.security.allowDomain("www.yoursite.com");
using just a superdomain as in: System.security.allowDomain("yoursite.com"); is in-sufficient for Flash 7.
- Files exported for Flash version 6 and viewed with Flash player 7+ will provide a dialog box asking the end user for permission.
- For data (not cross scripting, data is defined as for example XML file) transfer across domains a special XML file is needed
on the domain that has data called crossdomain.xml.
15. Flash Remoting
- Flash remoting is used for communication between Flash and application server such as ColdFusion MX server.
Flash remoting sends data back and forth between the server in binary, compressed format.
- Programmers need to watch the way data type conversion is handled by the Flash Remoting Gateway.
- For remoting to work Flash remoting needs to be installed on the server side, it already comes with ColdFusion server,
users of other server side technology, such as ASP, need to pay extra for Flash remoting. You also need to install Flash
remoting components inside Flash IDE (free of charge).
- The following class is installed as part of Flash remoting extension to Flash 7 IDE: NetServices class. It needs
to be included in the script that will use remoting with #include (hash include).
- The recordSet class is used to modify SQL query results returned from the server. DataGlue class is used
to bind recordset objects to array based UI components.
- NetConnection Debugger is a tool that displays the communication between server and Flash. Service Browser allows
for definition of a valid gateway URL and service name, works only with ColdFusion MX.
- The data returned by function named myFunction on the server side is captured by function named myFunction_result on Flash
side, myFunction_status is used for capturing exceptions that occurred on server side.
- Remember that data returned from the server side may not arrive in order it is called for. Also, to see debug you need to
include NetDebug.as class in addition to NetServices.as.
- The setDefaultGatewayUrl(URL) and createGatewayConnection() of class NetServices are used to
initialize the gateway, getService() method is used to get service (method of the connected gateway object).
- Processing on the server side can drag down client side as client may need to wait for the data from the server.
- Here is an example showing Flash initialization:
#include "NetServices.as" // main Flash Remoting class
// used for debugging only, should be commented out in production:
#include "NetDebug.as"
NetServices.setDefaultGatewayUrl("http://yourserver/flashservices/gateway");
// start connection:
this.myGatewayConnection = NetServices.createGatewayConnection();
// connect to some service:
this.myService = this.myGatewayConnection.getService("myService",this);
// call a function in service just created:
this.myService.someFunction(someArgs);
- Flash MX 2004 Adds Remoting Connector component - it allows the developer to work directly with the new data binding features of Flash.
New service and Connection classes are added and should be used instead of NetConnection class.
More information about Flash remoting can be found at Flash remoting readme.
- Flash Remoting using ActionScript 2.0:
// Code from www.actionscript.com
// Third argument is optional
var remote:RemoteHandler = new RemoteHandler("FlashZen",
"http://www.flashzengarden.com/gateway.php", true);
// remote call:
remote.serve("myMethodName", cacheTimeInMinutes, arg1, arg2, ..., argN);
// standard listener:
var myListener:Object = new Object();
remote.addEventListener("ALL", myListener); //Using GDispatcher
myListener.onMyMethodName = function(obj) {
trace ("\r\r Successful return of results" + obj.result);
}
16. Accessing web services from Flash
- At the heart of web services is XML based SOAP protocol (Simple Objects Access Protocol). This XML based protocol
is platform independent.
- WSDL (Web Services Description Language) is used to describe the service in detail to the client. It allows for
web services to be self-describing.
- UDDI (Universal description, Discovery and Integration) protocol is used as a directory of available web services.
Clients exchange information with UDDI through SOAP requests.
- Flash has the following web service related classes available: SOAPCall class, pendingCall class and log
class. WebServiceConnector component is available only in Flash 7 Pro, and is invisible to the end user.
- Log class is used for step by step view of Flash - web service communication events. The log has three levels of reporting,
brief, verbose (records everything) and debug.
- Pendingcall class is used to interact with pending call object - this object is created and returned when application calls
web service function.
- SOAPCall class is used to interact with WSDL of the web service.
- By default, lazy decoding is enabled in Flash, allowing for large datasets to be retrieved without being decoded
after their arrival. The data is only decoded when it is needed.
- Web service communication is done using text (not binary format like Flash remoting), thus it is a bit slower in some cases.
- Here is a list of limitations placed on web services accessed directly from Flash:
- With WebServiceConnector component Flash doesn't allow for more then one port definition and for more then one service definition.
- Flash also doesn't support non-HTTP and non-SOAP services. Flash doesn't support import tag and REST web service.
17. Data binding and connection components
- Data binding - process of connecting components and allowing them to share data (also update data). To use data
binding add the data binding symbol from the common libraries. To use it during run time, you will need to have
DataBind class instance created. There are seven data binding classes.
- DataProvider API is used by list based classes (such as arrays) for communication with data sources. DataSet
class is used to work with data as a set.
- The following components are used for communication and data transfer: DataSet, RDBMSResolver, XUpdateResolver and
XMLConnector.
- In a typical example of data binding XML data is retrieved by the XMLconnector component, it is bound to the dataSet component
which can: sort, filter, search and store data. The data is displayed in List component.
- DataSet component generates delta packets which external data sources can understand. Delta packets are generated when data
changes.
18. Printing in Flash
- Flash 7 adds new PrintJob class. This class has three important methods: start() - opens system's print
dialog box, addPage() - adds content to the print queue after job has been sent by the user, send() sends all
data gathered using the previous two methods to the print device. When an instance of this class is created, and the start()
method returns true the Flash player begins spooling the document. Deleting the printJob objects also removes the print job
spooler object in operating system's print spool.
- Printing from browsers file menu is common if visible print button is not present inside Flash movie. Programmer has no
way to control printing initiated from browser.
- Users can also print from the Flash context menu, which is enabled by default. Users that print from context menu can
only print frames on the main timeline of the movie. Also, the number of pages that is to be printed can be translated as
the number of frames on the main timeline that were designated as printable.
- Printing is also available to the developer since version 4 of Flash by the way of print actions. There are two print
actions: print (print as vector) and printAsBitmap (print as bitmap). Print as bitmap produces larger print
spool files and inferior quality in most instances. printNum is a version of print action that uses level rather
target movie clip. printAsBitmapNum is a version of printAsBitmap action that uses level rather target movie clip.
- You can change the print area size for print actions using bounding box parameters. By default, without bounding
parameters, the print area is the size of the main stage.
19. Flash deployment scenarios
- Flash running in IE is implemented as ActiveX control that may have transparent background allowing for floating
content. It is implemented as plug-in in other browsers.
- Macromedia Central is a browser for Flash based applications.
- With standard projector any executable file that you want to lunch from your movie must reside in folder named fscommand.
There are third party tools that extend projector's abilities and add support for screen savers.
- System capabilities can be viewed with System.capabilities object.
- Section 508 accessibility guidelines: visual, hearing, mobility and learning disorders.
- Each time text changes in Flash movie, Flash sends change notification to the screen reader, notification can be disabled
with Alt+Shift+M. Avoid to much animation as it sends a lot of change notifications which can be confusing to screen readers.
- Programmer should add keyboard navigation to movie elements. Tab navigation can be set with tabIndex keyword. Also avoid empty movie clips
used as buttons (since they are not recognized as buttons). For ease of use and accessibility, buttons should have key combination shortcuts.
- For acceptability purposes programmer should add descriptions to input fields, buttons, vector graphics and animations.
Text fields are assigned the same description as the text contained within them (i.e. they are self describing).
- Key combinations (multiple keys pressed at the same time) can be detected with the help of Key class.
- All Flash objects that have instance names can have acceptability options attached to them from Accessibility panel. These
are equivalent to the HTML Alt tag in use and function.
- For hearing impaired people you have the option to display captions with text version of sounds.
- Each Flash component has accessibility build in, it has to be enabled using enableAccessibility() function.
- Static text must be converted to dynamic text and graphics to movie clips before accessibility options can be applied.
- Flash uses MSAA (Microsoft Active Accessibility) for communication with screen reader. MSAA is not supported with opaque and
transparent window-less modes.
- The function call System.capabilities.hasAccessibilities returns true if the MSAA client is present, for synchronization
reasons this function should be called 1/2 - 2s after movie start.
- Developer should be aware that there is 1/2 to 2 second delay in screen reader detection by Flash client, thus initial
result of detection might be unreliable.
- When you make object accessible, its contents will be read by screen reader. The shortcut field allows for assigning
shortcuts to objects. Text is read by the reader without making it accessible.
- The tab order may not be the same as reader's reading order, to control reader's reading order you must assign tab index to every
object that is accessible, not just objects that can be focused on. Even if a single object is left out (don't forget to
change static text to dynamic) the system will revert back to the default reading order.
20. Development process
- The trace function is very useful for debugging. However, it cannot display complex objects, it will return
[object Object] as trace if it is used to display contents of an object.
- You can 'simulate' trace function with the help of JavaScript. Use JavaScript 'alert' function to send console alert messages.
You can invoke JavaScript with getURL() method.
- In Flash 7 Actions panel no longer supports 'normal' mode. Code hints, if enabled, will display popups with available
options for the block of code you just entered.
- You can choose the amount of spaces that make up ActionScript indent (which can be automatic). Also ActionScript color
display can be adjusted to programmers visual taste.
- Flash 7 IDE includes new global search and replace functionality.
- If there are many trace functions in your code and if you no longer want to see them all, you may omit them all, decreasing
compiled file size.
- Flash has a build in debugger, it can be activated with ctrl+shift+enter or Control menu. Debugger creates extra file for storage which ends in SWD.
You need to run your movies in Flash player debug version, not regular Flash player to see all debug messages.
- To use remote debug you need to publish your Flash file with remote debug enabled. You need to copy the debug
SWD file together with SWF file to the remote server. You need to use 'debug' version of Flash 7 player, not the
'regular' version.
- History panel shows changes you made to the document since you started working on it. Up to 9999 steps can be stored,
by default there are 100. You can use history panel data to create 'commands' that are used in automation of common Flash tasks.
Commands are created from history panel and are saved as JavaScript files.
- Flash remoting activity can be monitored using NetConnection debugger.
- Bandwidth profiler is very useful utility that can be activated with ctrl+enter. It shows current bandwidth usage
of a Flash movie.
- Escape shortcut keys - when you press 'Esc' and combination of two keys in sequence (not all together at once) you
enter one of pre-defined ActionScript code blocks into ActionScript window.
- Flash version 7 introduces version control which is compatible with Source Safe from Microsoft on Windows (not on Mac).
- Flash applications should be tested for their usability, which is defined as: "the extent to which a product can be used by
a group of users to achieve specific goals with specified effectiveness, efficiency and user satisfaction".
- In order to perform usability testing, you must identify: your target user group and the main purpose of your application.
- The testing is done to check whatever: application servers its purpose well, whatever application is easy to use and what are
opinions of real users regarding the application.
- It is a good idea to: avoiding leading of the test subjects during the test, avoid recruiting of fellow employees - as they are most
likely not part of your target group, avoid giving too specific instruction for the test subjects, let testers think aloud,
take notes and/or video of user actions, don't make your testers feel stupid - its ok to find out that the application is
plain bad.
21. Other topics
- To remove stroke or fill use the No Color button that appears when you create a new oval or rectangle.
- When you create a graphics and you want to add motion tween that graphics will be converted to either a graphics symbol or
a group in order for the tween to be applied to it. You can only apply motion tweens to layers which don't contain objects
that are un grouped.
- When you create a shape tween you do so to a piece of graphics that does't have to be grouped.
- Screens come in two formats,
- Slides - only one screen is displayed at a time
- Forms - more than one screen can be displayed at a time
- Screens are nested in each other like a tree. Each screen has its own timeline. Child screens inherit parent's properties.