20.5. Alphabetical Language Reference
The following entries document ActionScript's objects and
classes. Refer to the index for the operators and statements covered
elsewhere in this book.
Arguments Object | access to function parameters and the current function
|
Availability
Flash 5
Synopsis
arguments[elem]
arguments.propertyName
Properties
- callee
A reference to the function being executed.
- length
The number of parameters passed to the function being executed.
Description
The Arguments object is stored in the local
arguments variable of every function and is
accessible only while a function is executing.
Arguments is both an array and an object. As an
array, arguments stores the values of the
parameters passed to the currently executing function. For example,
arguments[0] is the first passed parameter,
arguments[1] is the second passed parameter, and
so on. As an object, Arguments stores the
callee property, which can be used to identify or
invoke the current function.
See Also
"The arguments Object" in Chapter 9, "Functions"
arguments.callee Property | a reference to the function being executed
|
Availability
Flash 5
Synopsis
arguments.callee
Access
Read/write
Description
The callee property stores a reference to the
function currently executing. We may use this reference to execute
the current function again or to identify the current function
through comparison.
Example
function someFunction ( ) {
trace(arguments.callee == someFunction); // Displays: true
}
// An unnamed recursive function
countToTen = function ( ) {
i++;
trace(i);
if (i < 10) {
arguments.callee( );
}
};
arguments.length Property | the number of parameters passed to an argument
|
Availability
Flash 5
Synopsis
arguments.length
Access
Read/write
Description
The length property stores an integer representing
the number of elements in the arguments array,
which equates to the number of parameters passed to the currently
executing function.
Example
We can use the length property of
arguments to determine whether a function was
invoked with the correct number of parameters. The following example
checks whether two arguments have been passed to
someFunction( ). Checking whether the passed
arguments are of the correct type is left as an exercise to the
reader. (Hint: see the typeof operator.)
Here's the code:
function someFunction (y, z) {
if (arguments.length != 2) {
trace("Function invoked with wrong number of parameters");
return;
}
// Proceed with normal function body...
}
Array
Class | support for ordered lists of data
|
Availability
Flash 5
Constructor
new Array()
new Array(len)
new Array(element0, element1, element2,...elementn)
Arguments
- len
A non-negative integer specifying the size of the new array.
- element0,...elementn
A list of one or more initial values to be assigned as elements of
the array.
Properties
- length
The number of elements in an array (including empty elements).
Methods
- concat( )
Create a new array by appending additional elements to an existing
array.
- join( )
Convert an array to a string.
- pop( )
Remove and return the last element of an array.
- push( )
Add one or more elements to the end of an array.
- reverse( )
Reverse the order of elements in an array.
- shift( )
Remove and return the first element of an array.
- slice( )
Create a new array using a subset of elements from an existing array.
- sort( )
Sort the elements of an array according to the specified rule.
- splice( )
Remove elements from, and/or add elements to, an array.
- toString( )
Convert an array to a string of comma-separated element values.
- unshift( )
Add one or more elements to the beginning of an array.
Description
We use the properties and methods of the Array
class to manipulate the data stored in the elements of an array
object. See Chapter 11, "Arrays", for exhaustive details on
what arrays are and how you can use them, plus detailed definitions
of the terminology used in this section. See also the
[] and . operators, which are
used to access array elements as described in Chapter 5, "Operators".
Usage
If the Array constructor is invoked with a
single integer argument, that argument is used to set the length of
the new array, not the value of the first element. If two or more
arguments are supplied to the constructor or if a single non-numeric
argument is supplied to the constructor, the arguments are used as
the initial values for elements in the array, and the length of the
array is determined by the number of arguments specified.
Array.concat( ) Method | create a new array by extending an existing array
|
Availability
Flash 5
Synopsis
array.concat(value1, value2, value3,...valuen)
Arguments
- value1,...valuen
A list of expressions to be added to the end of
array as new elements.
Returns
A new array containing all the elements of
array followed by the elements
value1,...valuen.
Description
The concat( ) method returns a new array created
by appending new elements to the end of an existing array. The
original array is left unchanged. Use the
push( ), splice( ), or
shift( ) method to modify the original array.
If an array is used as an argument to concat( ),
each element of that array is appended separately. That is, the
result of arrayX.concat(arrayY) will be an array
formed by appending each element of arrayY to the
end of arrayX. The resulting array will have a
length equal to arrayY.length +
arrayX.length. Nested arrays, however, are not similarly
flattened.
Example
// Create an array
myListA = new Array("apples", "oranges");
// Set myListB to ["apples", "oranges", "bananas"]
myListB = myListA.concat("bananas");
// Create another new array
myListC = new Array("grapes", "plums");
// Set myListD to ["apples", "oranges", "bananas", "grapes", "plums"]
myListD = myListB.concat(myListC);
// Set myListA to ["apples", "oranges", "bananas"]
myListA = myListA.concat("bananas");
// Create an array
settings = ["on", "off"];
// Append an array containing a nested array
options = settings.concat(["brightness", ["high", "medium", "low"]]);
// Sets options to: ["on", "off", "brightness", ["high", "medium", "low"]]
// not: ["on", "off", "brightness", "high", "medium", "low"]
See Also
Array.push( ), Array.shift( ), Array.splice( );
Section 11.7.3.4, "The concat( ) method" in Chapter 11, "Arrays"
Array.join( ) Method | convert an array to a string
|
Availability
Flash 5
Synopsis
array.join()
array.join(delimiter)
Arguments
- delimiter
An optional string to be placed between elements in the newly created
string. Defaults to a comma if not supplied.
Returns
A string composed of all the elements of
array converted to strings and separated
by delimiter.
Description
The join( ) method returns a string created by
combining all the elements of an array, as follows:
Convert each element in the array to a string (empty elements are
converted to the empty string).
Add delimiter to the end of each
converted-element string, except the last one.
Concatenate the converted-element strings into one long string.
Note that elements that are themselves arrays are converted to
strings via the toString( ) method, so nested
array elements are always delimited by commas, not the delimiter used
in the join( ) invocation.
Example
fruit = new Array("apples","oranges","bananas","grapes","plums");
// Set fruitString to "apples,oranges,bananas,grapes,plums"
fruitString = fruit.join( );
// Set fruitString to "apples-oranges-bananas-grapes-plums"
fruitString = fruit.join("-");
See Also
Array.toString( ), String.split( )
; Section 11.9.4, "The join( ) Method" in Chapter 11, "Arrays"
Array.length Property | the number of elements in an array
|
Availability
Flash 5
Synopsis
array.length
Access
Read/write
Description
The length property is a non-negative integer
specifying the number of elements in an array. An array with no
elements has a length of 0, an array with 2 elements has a length of
2. Note that the index number of the first element in an array is 0,
so length is always one greater than the index of
the last element in the array.
The length property of an array indicates how many
numbered elements the array currently contains, including empty
elements (those containing null or
undefined). For example, an array may have values
for elements 0, 1, 2, and 9, but elements 3 through 8 may be empty.
Such an array has a length of 10 because it has 10 element positions
(0 through 9) even though only 4 positions are occupied by useful
values.
Setting the length of an array changes the number
of elements in the array. If we increase length,
empty elements are added to the end of the array; if we decrease
length, existing elements are removed from the end
of the array. The length property changes
automatically whenever any elements are added or removed via the
Array class methods. The
length property reflects numbered elements only;
it does not include named array elements, which are treated as
properties of the array.
Example
myList = new Array("one", "two", "three");
trace(myList.length); // Displays: 3
// Loop through the array's elements
for (var i = 0; i < myList.length; i++) {
trace(myList[i]);
}
See Also
"Determining the Size of an Array" in Chapter 11, "Arrays"
Array.pop( ) Method | remove the last element of an array
|
Availability
Flash 5
Synopsis
array.pop()
Returns
The value of the last element of array,
which is also deleted.
Description
The pop( ) method deletes the
last element of an array, reduces the
array's length by 1, and returns the value
of the deleted element. Compare with the shift(
) method, which deletes the first
element of an array.
Example
myList = new Array("one", "two", "three");
trace ("Now deleting " + myList.pop( )); // myList is now: ["one", "two"]
See Also
Array.push( ), Array.shift(
), Array.splice( ); "Removing
Elements from an Array" in Chapter 11, "Arrays",
"The delete Operator" in Chapter 5, "Operators"
Array.push( ) Method | add one or more elements to the end of an array
|
Availability
Flash 5
Synopsis
array.push(value1, value2,...valuen)
Arguments
- value1,...valuen
A list of one or more values to be added to the end of
array.
Returns
The new length of array.
Description
The push( ) method appends a list of values to
the end of an array as new elements. Elements are added in the order
provided. It differs from concat( ) in that
push( ) modifies the original array, whereas
concat( ) creates a new array. It differs from
unshift( ) in that it adds elements at the end
of an array, not the beginning.
Example
myList = new Array (5, 6);
myList.push(7); // myList is now [5, 6, 7]
myList.push(10, 8, 9); // myList is now [5, 6, 7, 10, 8, 9]
See Also
Array.concat( ), Array.pop(
), Array.unshift( ); "Adding
Elements to an Array" in Chapter 11, "Arrays"
Array.reverse( ) Method | reverse the order of elements in an array
|
Availability
Flash 5
Synopsis
array.reverse()
Description
The reverse method reverses the order of
elements in an array, swapping the last element with the first
element, the second-to-last element with the second element, and so
on.
Example
myList = new Array(3, 4, 5, 6, 7);
myList.reverse( ); // myList is now [7, 6, 5, 4, 3]
See Also
Array.sort( )
Array.shift( ) Method | remove the first element of an array
|
Availability
Flash 5
Synopsis
array.shift()
Returns
The value of the first element of array,
which is also deleted.
Description
The shift( ) method deletes the
first element of an array and then moves all the
remaining elements of the array up one position. The affected
array's length is reduced by 1. Note that
shift( ) differs from the pop(
) method, which deletes the last
element of an array.
Example
myList = new Array ("a", "b", "c");
myList.shift( ); // myList becomes ["b", "c"]
See Also
Array.pop( ), Array.splice(
), Array.unshift( ); "Removing
Elements from an Array" in Chapter 11, "Arrays"
Array.slice( ) Method | create a new array using a subset of elements from an existing array
|
Availability
Flash 5
Synopsis
array.slice(startIndex, endIndex)
Arguments
- startIndex
A zero-relative integer specifying the first element in
array to add to the new array. If
negative, startIndex indicates an element
number counting backward from the end of
array (-1 is the last element, -2 is the
second-to-last element, etc.).
- endIndex
An integer specifying the element after the last
element in array to add to the new array.
If negative, endIndex counts backward from
the end of array (-1 is the last element,
-2 is the second-to-last element, etc.). If omitted,
endIndex defaults to
array.length.
Returns
A new array containing the elements of
array from
startIndex to
endIndex-1.
Description
The slice( ) method creates a new array by
extracting a series of elements from an existing array. The new array
is a subset of the elements of the original
array, starting with
array[startIndex]
and ending with
array[endIndex-1].
Example
myList = new Array("a", "b", "c", "d", "e");
// Set myOtherList to ["b", "c", "d"]
myOtherList = myList.slice(1, 4);
// Set anotherList to ["d", "e"]
anotherList = myList.slice(3);
// Set yetAnotherList to ["c", "d"]
yetAnotherList = myList.slice(-3, -1);
See Also
Array.splice( ); Section 11.9.3, "The slice( ) Method" in Chapter 11, "Arrays", Section 5.11.4, "The delete Operator" in Chapter 5, "Operators"
Array.sort( ) Method | sort the elements of an array
|
Availability
Flash 5
Synopsis
array.sort()
array.sort(compareFunction)
Arguments
- compareFunction
A function that dictates how to sort array.
Description
When invoked without any arguments, the sort( )
method temporarily converts the elements of
array to strings and orders the elements
according to the code points of those strings (approximately
alphabetical order). Alphabetic comparisons and code points are
described in "Character order and alphabetic comparisons"
in Chapter 4, "Primitive Datatypes".
When invoked with a compareFunction
argument, sort( ) reorders the elements of
array according to the return value of
compareFunction, which is a user-defined
function that dictates how to arrange any two values in the array.
Your user-defined compareFunction should
be designed to accept two array elements as arguments. It should
return a negative number if the first element should come before the
second element; it should return a positive number if the first
element should come after the second element; and it should return a
if the elements should not be reordered. If additional elements are
added to the array after it has been sorted, they are
not added in sorted order. You must resort the
array to reorder any newly added elements. Note that numbers are
sorted according to their Latin 1 code points by default. Chapter 11, "Arrays"
explains how to sort numbers by their numeric values.
Example
The following example sorts an array of movie clips according to
their horizontal location on screen:
var clips = [clip1, clip2, clip3, clip4];
function compareXposition (element1, element2) {
if (element1._x < element2._x) {
return -1;
} else if (element1._x > element2._x) {
return 1;
} else {
return 0; // The clips have the same x position
}
}
clips.sort(compareXposition);
See Also
Array.reverse( ); "The sort( )
method" in Chapter 11, "Arrays"
Array.splice( ) Method | remove elements from, and/or add elements to, an array
|
Availability
Flash 5
Synopsis
array.splice(startIndex)
array.splice(startIndex, deleteCount)
array.splice(startIndex, deleteCount, value1,...valuen)
Arguments
- startIndex
The zero-relative element index at which to start element deletion
and optional insertion of new elements. If negative,
startIndex specifies an element counting
back from the end of array (-1 is the last
element, -2 is the second-to-last element, etc.).
- deleteCount
An optional non-negative integer representing the number of elements
to remove from array, including the
element at startIndex. If 0, no elements
are deleted. If omitted, all elements from
startIndex to the end of the array are
removed.
- value1,...valuen
An optional list of one or more values to be added to
array at index
startIndex after the specified elements
have been deleted.
Returns
A new array containing the deleted elements (the
original array is modified separately to
reflect the requested changes).
Description
The splice( ) method removes the elements from
array[startIndex]
to
array[startIndex
+
deleteCount-1] and then
optionally inserts new elements starting at
startIndex. The splice(
) method does not leaves gaps in
array ; it moves elements up or down to
ensure the contiguity of elements in the array.
Example
myList = new Array (1, 2, 3, 4, 5);
// Deletes the second and third elements from the list
// and insert the elements "x", "y", and "z" in their place.
// This changes myList to [1, "x", "y", "z", 4, 5].
myList.splice(1, 2, "x", "y", "z");
See Also
Array.slice( ); Section 11.8.3.3, "The splice( ) method" in Chapter 11, "Arrays"
Array.toString
( ) Method | convert an array to a string of comma-separated element values
|
Availability
Flash 5
Synopsis
array.toString()
Returns
A comma-separated list of array 's
elements converted to strings.
Description
The toString( ) method creates a string
representation of array. The string
returned by toString( ) is a list of array
elements converted to strings and separated by commas (the same as is
returned by the join( ) method when
join( ) is invoked without parameters). An
array's toString( ) method is
automatically invoked whenever the array is used in a string context.
Therefore, it is rarely necessary to manually execute
toString( ) on an array. Normally, when we want
a precise string representation of an array, we use the
join( ) method, which offers us more control
over the string we're creating.
Example
myList = new Array("a", "b", "c"); // Create an array
trace(myList.toString( )); // Displays: "a","b","c"
myList = new Array([1, 2, 3], "a", "b", "c"); // Create a nested array
trace(myList.toString( )); // Displays: "1,2,3,a,b,c"
See Also
Array.join( )
Array.unshift( ) Method | add one or more elements to the beginning of an array
|
Availability
Flash 5
Synopsis
array.unshift(value1, value2,...valuen)
Arguments
- value1,...valuen
A list of one or more element values to be added to the beginning of
array.
Returns
The new length of array.
Description
The unshift( ) method adds a series of elements
to the beginning of an array. Elements are added in the order
specified. To add elements at the end of an array, use
push( ) .
Example
myList = new Array (5, 6);
myList.unshift(4); // myList becomes [4, 5, 6]
myList.unshift(7, 1); // myList becomes [7, 1, 4, 5, 6]
See Also
Array.push( ), Array.shift(
); Section 11.7, "Adding Elements to an Array" in Chapter 11, "Arrays"
Boolean( ) Global Function | convert a value to the boolean datatype
|
Availability
Flash 5
Synopsis
Boolean(value)
Arguments
- value
An expression containing the value to be converted to a Boolean.
Returns
The result of converting value to a
primitive Boolean (either true or
false).
Description
The Boolean( ) global function converts its
argument to a primitive Boolean value and returns that converted
value. The results of converting various types of data to a primitive
Boolean are described in Table 3-3. It's
normally not necessary to use the Boolean( )
function; ActionScript automatically converts values to the
boolean type when appropriate.
Usage
Be sure not to confuse the global Boolean( )
function with the Boolean class constructor. The
Boolean( ) function converts its argument to the
boolean datatype, whereas the
Boolean class constructor creates a new Boolean
object. Note that in ECMA-262, all nonempty strings convert to
true. In Flash 5, only strings that can be
converted to a valid nonzero number convert to
true. Therefore, even the string
"true" converts to the Boolean false.
Example
var x = 1;
if (Boolean(x)) {
trace("x is true");
}
See Also
The Boolean class; Section 3.4, "Datatype Conversion" in Chapter 3, "Data and Datatypes"
Boolean Class | wrapper class for primitive Boolean data
|
Availability
Flash 5
Constructor
new Boolean(value)
Arguments
- value
An expression to be resolved and, if necessary, converted to a
Boolean value, then wrapped in a Boolean object.
Methods
- toString( )
Convert the value of a Boolean object to a
string.
- valueOf( )
Retrieve the primitive value of a Boolean object.
Description
The Boolean class creates a
Boolean object which contains a
primitive Boolean value in an
inaccessible, internal property. Boolean objects
are used purely for the sake of manipulating and examining primitive
Boolean values using methods of the Boolean
class. A Boolean object is, hence, known as a
wrapper object because it simply packages a
primitive Boolean value, giving it some object-like methods. Compare
the Boolean class with the
String and Number classes,
which similarly wrap string and
number primitive values, but with more useful
results.
For the most part, Boolean objects are used
internally. They are created automatically by the interpreter
whenever a method is invoked on a primitive Boolean value and are
deleted automatically after each use. We can create
Boolean objects ourselves using the
Boolean constructor, but there is seldom reason
to do so.
Usage
Note that in practice it is much more common to use the
Boolean( ) global function as a
datatype-conversion tool than it is to use the
Boolean class.
See Also
Boolean( ) global function; "The Boolean
Type" in Chapter 4, "Primitive Datatypes"
Boolean.toString( ) Method | the value of the Boolean object converted to a string
|
Availability
Flash 5
Synopsis
booleanObject.toString()
Returns
The string "true" if the primitive value of
booleanObject is true;
"false" if the primitive value of
booleanObject is false.
The value of the Boolean object is specified when the object is
constructed and stored internally thereafter. Although the internal
value of a Boolean object is inaccessible, we can use
toString( ) to convert it to its string
equivalent.
Description
The toString( ) method retrieves the primitive
value of a Boolean object, converts that value to a string, and
returns the resulting string.
Example
x = new Boolean(true);
trace(x.toString( )); // Displays: "true"
See Also
Object.toString( )
Boolean.valueOf( ) Method | the primitive value of the Boolean object
|
Availability
Flash 5
Synopsis
booleanObject.valueOf()
Returns
The Boolean value true if the primitive value of
booleanObject is true;
false if the primitive value of
booleanObject is false.
The value of the Boolean object is specified when the object is
constructed and stored internally thereafter.
Description
The valueOf( ) method returns the primitive
Boolean datum associated with a Boolean object. Although the internal
value of a Boolean object is inaccessible, we can use
valueOf( ) to convert it to its primitive
equivalent.
Example
x = new Boolean(0);
trace(x.valueOf( )); // Displays: false
See Also
Object.valueOf( )
Call( ) Global Function | execute the script of a remote frame
|
Availability
Flash 4; deprecated in Flash 5
Synopsis
call(frameLabel)
call(frameNumber)
Arguments
- frameLabel
A string representing the label of the frame whose script should be
executed.
- frameNumber
The number of the frame whose script should be executed.
Description
The call( ) function executes the script
attached to the frame at frameLabel or
frameNumber. For example, the following
code runs the script on frame 20 of the current timeline:
call(20);
In Flash 4, call( ) was used to create a crude
kind of reusable subroutine (one that could not accept parameters or
return any value). In Flash 5, the function
statement is preferred.
Note that in Flash 5, when a script is executed remotely via
call( ), any variables declared with the
var keyword are considered local to that
execution and expire after the script completes. To create nonlocal
variables in a remotely-executed script, omit the
var keyword:
var x = 10; // Local variable; dies after script completes
x = 10; // Timeline variable; persists after script completes
To invoke call( ) on frames outside the current
timeline, use the tellTarget( ) function. The
following example executes the script on frame 10 of the
box clip:
tellTarget ("box") {
call(10);
}
See Also
Chapter 9, "Functions"; Appendix C, "Backward Compatibility"
Color
Class | control over movie clip color values
|
Availability
Flash 5
Constructor
new Color(target)
Arguments
- target
A string or reference indicating the path to the movie clip or
document level whose color will be controlled by the new object
(references are converted to paths when used in a string context).
Methods
- getRGB( )
Retrieve the current offset values for Red, Green, and Blue.
- getTransform( )
Retrieve the current offset and percentage values for Red, Green,
Blue, and Alpha.
- setRGB( )
Assign new offset values for Red, Green, and Blue, while reducing
percentage values to 0.
- setTransform( )
Assign new offset and/or percentage values for Red, Green,
Blue, and Alpha.
Description
We use objects of the Color class to
programmatically dictate the color and transparency of a movie clip or
main movie. Once we've created an object of the
Color class for a specific
target, we can then invoke the methods of
that object to affect its target's
color and transparency. For example, suppose we have a clip instance
named ball that we want to make red. We first make
a Color object
with a target of ball
and store it in the variable ballColor. Then we
use ballColor.setRGB( ) to assign
ball the color red, as follows:
var ballColor = new Color("ball");
ballColor.setRGB(0xFF0000); // Pass setRGB( ) the hex value for red
The preceding example provides color control for simple applications.
But to handle more complex scenarios, we need to know more about how
color is represented in Flash. Every individual color displayed in a
movie clip is defined by four separate components:
Red,
Green, Blue, and Alpha (or transparency). Those four components are
combined in different amounts to generate each color we see on
screen. The amount of Red, Green, Blue, and Alpha in a given color is
described as a number between 0
and 255. The higher the value of Red, Green, or Blue, the more each
of those colors contributes to the final color. However, remember
that computer color is additive, not subtractive like paint, so
higher values tend to be brighter, not darker. If all three RGB
components are equal, the result is a shade of gray; if they are all
0, the result is black; if they are all 255, the result is white. The
higher the value of Alpha, the more opaque the final color will be.
(A color with an Alpha of
is completely transparent, and a color with an Alpha of 255 is
completely opaque.)
For example, pure red would be described by the following values:
Red: 255, Green: 0, Blue: 0, Alpha: 255
whereas a partially transparent red might have the values:
Red: 255, Green: 0, Blue: 0, Alpha: 130
For the purposes of this discussion, we adopt the so-called
RGB triplet notation
(Red, Green,
Blue) when talking about color values.
Although ActionScript doesn't support decimal RGB triplets such
as (255, 0, 255), it does support the hexadecimal equivalent form
0xRRGGBB, where
RR, GG, and
BB are two-digit hex numbers representing
Red, Green and Blue. We'll also adopt the RGBA
quadlet notation (Red,
Green, Blue,
Alpha) for convenience only in the
following discussion.
The initial Red, Green, Blue, and Alpha values for each color in a
movie clip are set in the Flash authoring tool using the Mixer panel.
(In the Mixer panel, Alpha is shown as a percentage, not a number
from
to 255.) To alter all the colors in a movie clip
via ActionScript, we make universal adjustments (known as
transformations )
to the Red, Green, Blue, and Alpha components of the clip's
color.
We have two means of setting transformations for each color component:
We may specify an amount to offset the
component's original value. The offset is a number between -255
and 255. For example, we may say, "add 20 to all blue values in
this clip," or, using a negative number we may say,
"subtract 30 from all blue values in this clip."
The final value of a color in a transformed clip is determined by
combining its original (author-time) color component values with the
transformation percentages and offsets set through
the
Color object, as follows:
R = originalRedValue * (redTransformPercentage/100) + redTransformOffset
G = originalGreenValue * (greenTransformPercentage/100) + greenTransformOffset
B = originalBlueValue * (blueTransformPercentage/100) + blueTransformOffset
A = originalAlphaValue * (alphaTransformPercentage/100) + alphaTransformOffset
If no transformations have been performed through ActionScript, the
initial transformation percentage for each
component defaults to 100, while the initial
offset defaults to 0.
Let's look at how color transformations work with a practical
example. Suppose that a clip contains an opaque red triangle (R:255,
G:0, B:0, A:255) and an opaque green circle (R:0, G:255, B:0, A:255).
Now further suppose that we apply a universal transformation to the
clip, setting the percentage of Green to 50, the percentage of Alpha
to 80, and the offset of Blue to 100 but leaving the other offsets
and percentages at their defaults (0 or 100). Here's how the
universal transformation affects our red triangle:
R == 255 * (100/100) + 0 == 255 // No change to Red
G == 0 * (50/100) + 0 == 0 // Green reduced to 50%
B == 0 * (100/100) + 100 == 100 // Blue offset by 100
A == 255 * (80/100) + 0 == 204 // Alpha reduced to 80%
The final transformed red triangle has the color value (R:255, G:0,
B:100, A:204). Now here's how the transformation affects our
green circle:
R == 0 * (100/100) + 0 == 0 // No change to Red
G == 255 * (50/100) + 0 == 127.5 // Green reduced to 50%
B == 0 * (100/100) + 100 == 100 // Blue offset by 100
A == 255 * (80/100) + 0 == 204 // Alpha reduced to 80%
The final transformed green circle has the color value (R:0, G:127.5,
B:100, A:204).
To actually apply our hypothetical color transformations to a real
clip, we use a Color object as we saw earlier.
To set a clip's universal color offset and
percentage values we use the setRGB(
) or the setTransform( ) methods (see
the entries for those methods for example code). Conversely, to
examine the current color transformations of a clip, we use the
getRGB( ) and getTransform(
) methods. The Color class methods
can produce animated color effects such as fade-ins, fade-outs, and
tinting. Furthermore, because we can apply tints to each clip
instance individually, the Color class provides
a very efficient way to create diverse graphics with minimal assets.
For example, we could create a scene full of balloons from a single
movie clip that was colorized and tinted in myriad ways, as shown
under the Example heading that follows.
Usage
Some points of interest for Color objects:
Example
The first example shows how to generate
a series of randomly colored balloon movie clips based on an existing
clip called balloon:
// Loop to make 20 duplicates of the clip balloon
for (var i = 0; i < 20; i++) {
// Duplicate this balloon
balloon.duplicateMovieClip("balloon" + i, i);
// Position this balloon on stage
this["balloon" + i]._x = Math.floor(Math.random( ) * 550);
this["balloon" + i]._y = Math.floor(Math.random( ) * 400);
// Create a Color object for this balloon
balloonColor = new Color(this["balloon" + i]);
// Randomly assign this balloon's color using the setRGB( ) method
balloonColor.setRGB(Math.floor(Math.random( ) * 0xFFFFFF));
}
By
setting the Red, Green, and Blue offsets to
the same value, we can effectively brighten or darken a movie clip.
For example, the following code darkens myClip:
brightness = new Color("myClip");
brightnessTransform = new Object( );
brightnessTransform.rb = -30;
brightnessTransform.bb = -30;
brightnessTransform.gb = -30;
brightness.setTransform(brightnessTransform);
This last example contains code that brightens and darkens a clip
according to the mouse position:
onClipEvent (load) {
var brightness = new Color(this);
var brightnessTransform = new Object( );
var stageWidth = 550;
}
onClipEvent (mouseMove) {
brightnessAmount = -255 + (_root._xmouse / stageWidth) * 510;
brightnessTransform.rb = brightnessAmount;
brightnessTransform.bb = brightnessAmount;
brightnessTransform.gb = brightnessAmount;
brightness.setTransform(brightnessTransform);
updateAfterEvent( );
}
Color.getRGB( )
Method | retrieve the current offset values for Red, Green, and Blue
|
Availability
Flash 5
Synopsis
colorObj.getRGB()
Returns
A number representing the current RGB offsets of
colorObj 's target.
Description
The getRGB( ) method
returns a number ranging from -16777215
to 16777215 that represents the current color offsets for the Red,
Green, and Blue components in a clip; to retrieve the color
percentages, you must use getTransform( ).
Because color offset values normally range from 0
to 255, it's convenient to work with the return value of
getRGB( ) in hexadecimal, where each color
offset can be represented by a two-digit hex number. To decipher the
number returned by getRGB( ), we treat it as a
six-digit hex number of the form
0xRRGGBB, where
RR is the Red offset,
GG is the Green offset, and
BB is the Blue offset. For example, if
getRGB( ) returns the number 10092339, we
convert it to the hex number 0x99FF33 from which we derive the color
offsets R:153, G:255, B:51. Or if getRGB( )
returns the number 255, we convert it to the hex number 0x0000FF from
which we derive the color offsets R:0, G:0, B:255. The return value
of getRGB( ) can be converted to hexadecimal
with toString( ), as follows:
// Create a Color object
myColor = new Color("myClip");
// Set the Red offset to 255 (FF in hex)
myColor.setRGB(0xFF0000);
// Retrieve the RGB offset and convert it to hexadecimal
hexColor = myColor.getRGB( ).toString(16);
trace(hexColor); // Displays: ff0000
Hexadecimal color values are familiar to most web developers, as they
are often used in HTML tags. For example, here we use a hexadecimal
number to specify the background color of a page (full values for red
and blue combine to form pink):
<BODY BGCOLOR="#FF00FF">
The hex color format used in HTML tags is, in fact, the same as the
format used by getRGB( ) and setRGB(
). However, it's not mandatory to use hexadecimal to
interpret the return value of getRGB( ); we may
also extract the individual Red, Green and Blue color offsets from
the return value of getRGB( ) using the bitwise
operators:
var rgb = myColorObject.getRGB( );
var red = (rgb >> 16) & 0xFF; // Isolate the Red offset and assign it to red
var green = (rgb >> 8) & 0xFF; // Isolate the Green offset and assign it to green
var blue = rgb & 0xFF; // Isolate the Blue offset and assign it to blue
With the offset values separated into individual variables, we may
examine and manipulate them individually as decimal numbers. However,
when we want to apply any offset value changes to a
Color object, we must reassemble the offsets
into a single number, as shown under the entry for the
setRGB( ) method.
Usage
The getRGB( ) and setRGB( )
methods are convenient when we're directly assigning new colors
to a clip without reference to the clip's original color
values. However, the getTransform( ) and
setTransform( ) methods are better suited to
modifying the RGB components of a clip's color transformation
in relation to the clip's original colors.
Color offsets are most easily read using getTransform(
), which returns each component separately rather than as
a lump sum as getRGB( ) does. This is especially
true when setting negative offsets with setTransform(
) due to the way that negative numbers are represented in
binary.
Example
// Create a new Color object for a clip named box
boxColor = new Color("box");
// Set a new RGB offset for "box"
boxColor.setRGB(0x333366);
// Check the RGB offset for "box"
trace(boxColor.getRGB( )); // Displays: 3355494
See Also
Color.getTransform( ), Color.setRGB(
)
Color.getTransform( ) Method | retrieve both the current offset and percentage values for a clip's Red, Green, Blue, and Alpha components
|
Availability
Flash 5
Synopsis
colorObj.getTransform()
Returns
An object whose properties contain the color transformation values
for the target clip of colorObj.
Description
The getTransform( ) method returns an object
with properties that tell us which transformations are currently
applied to the target of a Color object. The
property names and values of the returned object are described in
Table 20-4.
Table 20-4. Properties of Object Returned by getTransform( )
Property Name |
Property Value |
Property Description |
ra
|
-100 to 100 |
The Red transformation percentage |
rb
|
-255 to 255 |
The Red offset amount |
ga
|
-100 to 100 |
The Green transformation percentage |
gb
|
-255 to 255 |
The Green offset amount |
ba
|
-100 to 100 |
The Blue transformation percentage |
bb
|
-255 to 255 |
The Blue offset amount |
aa
|
-100 to 100 |
The Alpha transformation percentage |
ab
|
-255 to 255 |
The Alpha offset amount |
Usage
Note in Table 20-4 that both the percentage and the
offset can have negative values; however, these are only one factor
in calculating the RGB color components, which always range from 0
to 255. Values outside that range are clipped to the allowable range.
See the Color class description for an
explanation of the calculation used to determine final RGB and Alpha
color components.
Example
We can use getTransform( ) in combination with
setTransform( ) to modify the Red, Green, Blue,
or Alpha components of a color transformation individually. For
example, in the following code, we adjust the Red and Alpha
components of a clip named box:
// Create a new Color object for a clip named box
boxColor = new Color("box");
// Assign the return object of getTransform() to boxTransform
boxTransform = boxColor.getTransform( );
// Now, make some modifications to the transform object's properties
boxTransform.rb = 200; // Set Red offset to 200
boxTransform.aa = 60; // Set Alpha percentage to 60
// Apply the new transformations to box via boxColor
boxColor.setTransform(boxTransform);
See Also
Color.setTransform( )
Color.setRGB( )
Method | assign new offset values for Red, Green, and Blue
|
Availability
Flash 5
Synopsis
colorObj.setRGB(offset);
Arguments
- offset
A number in the range 0
to 16777215 (0xFFFFFF), representing the new RGB offsets of
colorObj 's target clip. May be a
decimal integer or a
hexadecimal integer.
Numbers outside the allowed range are converted to numbers within the
allowed range (using the rules of twos-complement binary notation).
Therefore, setRGB( ) cannot be used to set
negative offset values (as setTransform( )
can).
Description
The setRGB( ) method assigns new transformation
offsets for a movie clip's RGB components. The new
offset is most easily specified as a
six-digit hexadecimal number of the form
0xRRGGBB, where
RR, GG, and
BB are two-digit numbers between 00 and FF
representing the Red, Green, and Blue components. For example, the
RGB triplet (51, 51, 102) is equivalent to the hexadecimal value:
0x333366
Hence, to assign a gray RGB offset to a clip named
menu, we could use:
var menuColor = new Color("menu");
menuColor.setRGB(0x999999);
Web developers comfortable with six-digit hexadecimal color values in
HTML will have an easy time using setRGB( )
using the preceding hexadecimal format. For a primer on decimal,
octal, and hexadecimal numbers see http://www.moock.org/asdg/technotes.
Note that in addition to setting offsets, setRGB(
) also automatically sets the Red, Green, and Blue
percentages of a clip's color transformation to 0, meaning that
color changes performed via setRGB( ) behave as
direct color assignments (not adjustments of the original colors in
the clip). To adjust the color of a movie clip in relation to the
clip's original colors, we must use the setTransform(
) method.
Example
Here's a handy technique for generating a number to use with
the setRGB( ) method. Our custom
combineRGB( ) function shifts the
red and green
numbers into the proper position in a 24-bit number and then combines
the red, green,
and blue values using the bitwise OR
operator (|). We use the result to assign a color
value to the movie clip box:
function combineRGB (red, green, blue) {
// Combine the color values into a single number
var RGB = (red<<16) | (green<<8) | blue;
return RGB;
}
// Create the Color object
var boxColor = new Color("box");
// Set the color of box to the RGB triplet (201, 160, 21)
boxColor.setRGB(combineRGB(201, 160, 21));
For more information on bitwise operations, see Chapter 15, "Advanced Topics".
See Also
Color.getRGB( ), Color.setTransform(
)
Color.setTransform( ) Method | assign new offset and/or percentage values for Red, Green, Blue, and Alpha
|
Availability
Flash 5
Synopsis
colorObj.setTransform(transformObject)
Arguments
- transformObject
An object whose properties contain the new color transformation
values for the target clip of colorObj.
Description
The setTransform( ) method gives us precise
control over the percentage and offset of the Red, Green, Blue, and
Alpha components of a movie clip's color. To use
setTransform( ), we must first create an object
with a series of predefined properties. The transformation we wish to
apply to our Color object is expressed using those
properties, which are listed in Table 20-4 for the
getTransform( ) method (except that
setTransform( ) specifies their values rather
than reading their values).
Once we have created an object with the properties described in Table 20-4, we pass that object to the
setTransform( ) method. The values of the
properties on our transformObject become
the new offset and percentage transform values of
colorObj and, hence,
colorObj's target movie clip. The
final color values in the clip are then determined according to the
calculation discussed under the Color class.
To examine the current offsets and percentages of a particular
Color object, we use the getTransform(
) method.
Example
// Create a new Color object for the box clip
boxColor = new Color("box");
// Create a new anonymous object and store it in boxTransform
boxTransform = new Object( );
// Assign the required properties of boxTransform, setting our
// transformation values as desired
boxTransform.ra = 50; // Red percentage
boxTransform.rb = 0; // Red offset
boxTransform.ga = 100; // Green percentage
boxTransform.gb = 25; // Green offset
boxTransform.ba = 100; // Blue percentage
boxTransform.bb = 0; // Blue offset
boxTransform.aa = 40; // Alpha percentage
boxTransform.ab = 0; // Alpha offset
// Now that our transform object has been
// prepared, pass it to setTransform( )
boxColor.setTransform(boxTransform);
The preceding approach to creating a transform object is fairly
labor-intensive. We may generate a new transform object more easily
using the getTransform( ) method, as follows:
// Create a new Color object for the box clip
boxColor = new Color("box");
// Invoke getTransform( ) on boxColor, retrieving an appropriately
// constructed transform object
boxTransform = boxColor.getTransform( );
// Now alter only the desired properties of boxTransform,
// leaving the others unchanged
boxTransform.rb = 51; // Red offset
boxTransform.aa = 40; // Alpha percentage
// Use our transform object with setTransform( )
boxColor.setTransform(boxTransform);
See Also
Color.getTransform(
)
Date Class | current time and structured support for date information
|
Availability
Flash 5
Constructor
new Date()
new Date(milliseconds)
new Date(year, month, day, hours, minutes, seconds, ms)
Arguments
- milliseconds
The number of milliseconds between the new date and midnight of
January 1, 1970 UTC (Coordinated Universal Time, akin to GMT).
Positive if after; negative if before. Any required local time zone
adjustment is made after the date in UTC time is determined. For
example, specifying a milliseconds
argument of 1000 in Eastern Standard Time would create a date 1
second past midnight on January 1, 1970 in UTC time, which translates
to 7:00:01 p.m. on December 31, 1969 in EST time (5 hours behind UTC
time).
- year
An integer specifying the year. Required when using the
year,...ms
constructor format. If year is one or two
digits, it is treated as the number of years since 1900 (e.g., a
year of 11 always refers to the year 1911,
not 2011). Use four-digit numbers to specify year 2000 or later
(e.g., use 2010, not 10). Three-digit years are treated as pre-1000
A.D. Note that when year is negative or
less than 800, the calculation is unreliable. To specify dates prior
to 1000 A.D., it's safest to use the single
milliseconds constructor format.
- month
An integer specifying the month, from
( January) to 11 (December), not from 1 to 12. Required when using
the
year,...ms
constructor format. Out-of-range months are carried over to the next
or previous year. For example, a month of
13 is treated as February of the following year.
- day
An optional integer specifying the day, from 1 to 31. Defaults to 1
if not specified. Out-of-range days are carried over to the next or
previous month. For example September 31 is treated as October 1 and
September
is treated as August 31.
- hours
An optional integer specifying the hour, from 0
(midnight) to 23 (11 p.m.). Defaults to
if not specified. AM and PM notation are not supported. Out-of-range
hours are carried over to the next or previous day. For example, an
hour of 25 is treated as 1 a.m. of the
following day.
- minutes
An optional integer specifying the minute, from
to 59. Defaults to
if not specified. Out-of-range minutes are carried over to the next
or previous hour. For example, a minute of
60 is treated as the first minute of the following hour.
- seconds
An optional integer specifying the seconds, from
to 59. Defaults to
if not specified. Out-of-range seconds are carried over to the next
or previous minute. For example, a second
of -1 is treated as the last second of the previous minute.
- ms
An optional integer specifying the milliseconds, from
to 999. Defaults to
if not specified. Out-of-range milliseconds are carried over to the
next or previous second. For example, an
ms of 1005 is treated as 5 milliseconds
into the following second.
Class Methods
- UTC( )
Retrieve the number of milliseconds between January 1, 1970 and a
supplied UTC date.
Methods
- getDate( )
Retrieve the day of the month, from 1 to 31.
- getDay( )
Retrieve the day of the week, as a number from 0
0 (Sunday) to 6 (Saturday).
- getFullYear( )
Retrieve the four-digit year.
- getHours( )
Retrieve the hour of the day from 0 to 23.
- getMilliseconds( )
Retrieve the milliseconds.
- getMinutes( )
Retrieve the minutes.
- getMonth( )
Retrieve the month of the year, as a number from 0
(January) to 11 (December).
- getSeconds( )
Retrieve the seconds.
- getTime( )
Retrieve the date in internal format (i.e., the number of
milliseconds between the date and January 1, 1970).
- getTimezoneOffset( )
Retrieve the number of minutes between UTC and local time.
- getUTCDate( )
Retrieve the day of the month in UTC time.
- getUTCDay( )
Retrieve the day of the week in UTC time.
- getUTCFullYear( )
Retrieve the four-digit year in UTC time.
- getUTCHours( )
Retrieve the hour of the day in UTC time.
- getUTCMilliseconds( )
Retrieve the milliseconds in UTC time.
- getUTCMinutes( )
Retrieve the minutes in UTC time.
- getUTCMonth( )
Retrieve the month of the year in UTC time.
- getUTCSeconds( )
Retrieve the seconds in UTC time.
- getYear( )
Retrieve the year, relative to 1900.
- setDate( )
Assign the day of the month.
- setFullYear( )
Assign the year in four-digit format.
- setHours( )
Assign the hour of the day.
- setMilliseconds( )
Assign the milliseconds.
- setMinutes( )
Assign the minutes.
- setMonth( )
Assign the month of the year.
- setSeconds( )
Assign the seconds.
- setTime( )
Assign the date in internal format (i.e., the number of milliseconds
between the date and January 1, 1970).
- setUTCDate( )
Assign the day of the month in UTC time.
- setUTCFullYear( )
Assign the year in four-digit format in UTC time.
- setUTCHours( )
Assign the hour of the day in UTC time.
- setUTCMilliseconds( )
Assign the milliseconds in UTC time.
- setUTCMinutes( )
Assign the minutes in UTC time.
- setUTCMonth( )
Assign the month of the year in UTC time.
- setUTCSeconds( )
Assign the seconds in UTC time.
- setYear( )
Assign the year in four-digit, or in two-digit format for the 20th
century.
- toString( )
A human-readable string representing the date.
- valueOf( )
The number of milliseconds between the date and midnight of January
1, 1970 UTC.
Description
We use objects of the Date class as a mechanism
by which to determine the current time and date and as a means of
storing arbitrary dates and times in a structured format.
In ActionScript, a specific date is represented by the number of
milliseconds before or after
midnight of January 1, 1970. If the number of milliseconds is
positive, the date comes after midnight, January 1, 1970; if the
number of milliseconds is negative, the date comes before midnight,
January 1, 1970. For example, if a date value is 10000, the date
being described is 12:00:10, January 1, 1970. If a date value is
-10000, the date being described is 11:59:50, December 31, 1969.
Normally, however, we needn't worry about calculating the
number of milliseconds to a particular date; the ActionScript
interpreter takes care of that for us. When we construct a
Date object, we simply describe our date as a
year, month, day, hour, minute, second, and millisecond. The
interpreter then converts that point in time to the internal
milliseconds-from-1970 format. We may also ask the interpreter to
create a new Date object using the current time.
Once a Date object is created, we can use the
Date class's methods to retrieve and set
the date's year, month, day, hour, minute, second, and
millisecond.
There are three ways to make a new
Date object:
We may invoke the Date( ) constructor with from
two to seven numeric arguments, corresponding to the year and month
(mandatory) and (optionally) the day, hour, minute, second, and
millisecond of the date we're creating.
Because dates are stored internally as a single number, objects of
the Date class do not have properties to
retrieve and set. Rather, they have methods that we use to access the
various components of a date in human-readable terms (i.e., in more
convenient units). For example, to determine the month of a
particular Date object, we use:
myMonth = myDate.getMonth( );
We cannot use:
myMonth = myDate.month; // There's no such property! We have to use methods.
Many Date methods contain the letters
"UTC," which is an abbreviation for Coordinated Universal
Time. For most purposes, UTC time is directly synonymous with the
more colloquial Greenwich Mean Time, or GMT -- the time as measured on the
Greenwich meridian. UTC is simply a newer standard that is less
ambiguous than GMT, which has had several meanings over history. The
UTC methods allow us to work with times directly in Coordinated
Universal Time without converting between time zones. The equivalent
non-UTC methods all generate values based on local, adjusted time
zones.
Usage
All dates and times are determined according to the settings on the
operating system on which the Flash movie is running (not the web
server) and include regional offsets. Times and dates, therefore, are
only as accurate as the user's system.
Note that the Date( ) constructor may also be
used as a global function to generate a string expressing the current
time in the same format as would be returned by
myDate.toString( ).
In Flash 5 ActionScript, it is not possible to convert a string into
a Date object, as is possible in JavaScript.
Example
Dates can be added and subtracted to come up with cumulative times or
elapsed times. Suppose our friend Graham decides to go traveling for
a little less than a year. While he's gone, we want to keep
track of how many days he's been away and how many days we have
to wait for him to return. The following code takes care of our
countdown:
// Assign the current time to now
var now = new Date( );
// Graham leaves September 7, 2000 (remember, months start at 0
// so September is 8, not 9)
var departs = new Date(2000,8,7);
// Graham comes back August 15, 2001
var returns = new Date(2001,7,15);
// Convert the times to milliseconds for easy comparison.
// Then check how many milliseconds have elapsed between the two times.
var gone = now.getTime() - departs.getTime( );
// Divide the difference between departure date and now by the number
// of milliseconds in a day. This tells us how many days we've been waiting.
var numDaysGone = Math.floor(gone/86400000);
// Use the same technique to determine how many days we have left to wait
var left = returns.getTime() - now.getTime( );
var numDaysLeft = Math.floor(left/86400000);
// Display our days in text fields
goneOutput = numDaysGone;
leftOutput = numDaysLeft;
When adding a day to, or
subtracting a day from, an existing date, we normally assign the
number of milliseconds in a day (86400000) to a variable for
convenient use. The following code adds one day to the current date:
oneDay = 86400000;
now = new Date( );
tomorrow = new Date(now.getTime( ) + oneDay);
// We could also add one day to the date in now like this
now.setTime(now.getTime( ) + oneDay);
To apply custom formatting to a
date, we must manually map the return values of getDate(
), getDay( ), getHours(
), and so on to custom strings as shown in the following
example:
// Takes any Date object and returns a string of the format:
// Saturday December 16
function formatDate(theDate) {
var months = ["January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"];
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday"];
var dateString = days[theDate.getDay( )] + " "
+ months[theDate.getMonth( )] + " "
+ theDate.getDate( );
return dateString;
}
now = new Date( );
trace("Today is " + formatDate(now));
The next example shows how to convert the 24-hour clock return value
of getHours( ) to a 12-hour clock with AM and
PM:
// Takes any Date object and returns a string of the format:
// "2:04PM"
function formatTime(theDate) {
var hour = theDate.getHours( );
var minute = theDate.getMinutes( ) > 9 ?
theDate.getMinutes() : "0" + theDate.getMinutes( );
if (hour > 12) {
var timeString = (hour - 12) + ":" + minute + "PM";
} else {
var timeString = hour + ":" + minute + "AM";
}
return timeString;
}
now = new Date( );
trace("The time is " + formatTime(now));
For an example using the Date class to create an
analog-style clock, see Section 13.9.1, "Building a Clock with Clips" in Chapter 13, "Movie Clips". Note that programming time-based behavior
such as a 10-second pause in a movie is often accomplished more
easily with the global getTimer( ) function.
See Also
Date( ) , Date.UTC( ),
getTimer( )
Date.getDate( ) Method | the day of the month
|
Availability
Flash 5
Synopsis
date.getDate()
Returns
An integer from 1 to 31, representing the day of the month for
date.
Date.getDay( ) Method | the day of the week
|
Availability
Flash 5
Synopsis
date.getDay()
Returns
An integer from 0
0 (Sunday) to 6 (Saturday), representing the day of the week for
date.
Example
The following code loads a .swf file specific to
the current day of the week into the movie clip
welcomeHeader (the seven .swf
files are named in the series sun.swf,
mon.swf, and so on):
now = new Date( );
today = now.getDay( );
days = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
welcomeHeader.loadMovie(days[today] + ".swf");
Date.getFullYear( ) Method | the four-digit year
|
Availability
Flash 5
Synopsis
date.getFullYear()
Returns
A four-digit integer representing the year for
date, for example 1999 or 2000.
Date.getHours( ) Method | the hour of the day
|
Availability
Flash 5
Synopsis
date.getHours()
Returns
An integer from 0
(midnight) to 23 (11 p.m.) representing the hour of the day for
date. A.M. and P.M. notation are not
supported but can be constructed manually as shown in the
Date class examples.
Date.getMilliseconds( ) Method | the milliseconds of a date
|
Availability
Flash 5
Synopsis
date.getMilliseconds()
Returns
An integer from 0
to 999 representing the milliseconds of
date. Note that it does not represent the
milliseconds from 1970 (see getTime( )), but
rather the fractional remainder of the seconds indicated by the
specified Date object.
See Also
Date.getTime( )
Date.getMinutes( ) Method | the minutes of a date
|
Availability
Flash 5
Synopsis
date.getMinutes()
Returns
An integer from 0
to 59 representing the minutes of the hour of
date.
Date.getMonth( ) Method | the month of the year
|
Availability
Flash 5
Synopsis
date.getMonth()
Returns
An integer from 0
(January) to 11 (December), not 1 to 12, representing the month of
the year of date.
Usage
Be careful not to assume that 1 is January! The return value of
getMonth( ) starts at 0, not 1.
Example
Here we convert the number returned by getMonth(
) to a human-readable abbreviation:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sept", "Oct", "Nov", "Dec"];
myDateObj = new Date( );
trace ("The month is " + months[myDateObj.getMonth( )]);
Date.getSeconds( ) Method | the seconds of a date
|
Availability
Flash 5
Synopsis
date.getSeconds()
Returns
An integer from 0
to 59 representing the seconds of the minute of
date.
Date.getTime( )
Method | retrieve the number of milliseconds between January 1, 1970 and the time of a date object
|
Availability
Flash 5
Synopsis
date.getTime()
Returns
An integer expressing the number of milliseconds between the time of
date and midnight, January 1, 1970.
Positive if after January 1, 1970; negative if before.
Description
Internally, all dates are represented as a single number -- the
number of milliseconds between the time of the
date and midnight, January 1, 1970. The
getTime( ) method gives us access to that number
of milliseconds so that we may use it to construct other dates or to
compare the elapsed time between two dates.
Example
Suppose we place the following code on the 10th frame of a movie:
time1 = new Date( );
Then we place the following code on the 20th frame of a movie:
time2 = new Date( );
With the following code, we can determine the amount of time that
elapsed, in milliseconds, between the 10th and 20th frames of our
movie:
elapsedTime = time2.getTime() - time1.getTime( );
Note that Flash's global getTimer( )
function also gives us access to elapsed time in a movie.
See Also
Date.setTime( ), getTimer( )
Date.getUTCDate( ) Method | the day of the month (UTC time)
|
Availability
Flash 5
Synopsis
date.getUTCDate()
Returns
An integer from 1 to 31, representing the day of the month for
date, where
date is treated as a UTC time.
Date.getUTCDay( ) Method | the day of the week (UTC time)
|
Availability
Flash 5
Synopsis
date.getUTCDay()
Returns
An integer from
0 (Sunday) to 6 (Saturday), representing the day of the week for
date, where
date is treated as a UTC time.
Date.getUTCFullYear( ) Method | the four-digit year (UTC time)
|
Availability
Flash 5
Synopsis
date.getUTCFullYear()
Returns
A four-digit integer representing the year for
date, where
date is treated as a UTC time, for example
1999 or 2000.
Date.getUTCHours( ) Method | the hour of the day (UTC time)
|
Availability
Flash 5
Synopsis
date.getUTCHours()
Returns
An integer from 0
(midnight) to 23 (11 p.m.) representing the hour of the day for
date, where
date is treated as a UTC time.
Date.getUTCMilliseconds( ) Method | the milliseconds of a date (UTC time)
|
Availability
Flash 5
Synopsis
date.getUTCMilliseconds()
Returns
An integer from 0
to 999 representing the milliseconds of
date, where
date is treated as a UTC time.
Date.getUTCMinutes( ) Method | the minutes of a date (UTC time)
|
Availability
Flash 5
Synopsis
date.getUTCMinutes()
Returns
An integer from 0
to 59 representing the minutes of the hour of
date, where
date is treated as a UTC time.
Date.getUTCMonth( ) Method | the month of the year (UTC time)
|
Availability
Flash 5
Synopsis
date.getUTCMonth()
Returns
An integer from 0
(January) to 11 (December), not 1 to 12, representing the month of
the year of date, where
date is treated as a UTC time.
Usage
Be careful not to assume that 1 is January! The return value of
getUTCMonth( ) starts at 0, not 1.
Date.getUTCSeconds( ) Method | the seconds of a date (UTC time)
|
Availability
Flash 5
Synopsis
date.getUTCSeconds()
Returns
An integer from 0
to 59 representing the seconds of the minute of
date, where
date is treated as a UTC time.
Date.getYear( ) Method | the year, relative to 1900
|
Availability
Flash 5
Synopsis
date.getYear()
Returns
The value of date.getFullYear(
) -1900. For example, getYear(
) of 1999 is 99, getYear( ) of 2001
is 101, and getYear( ) of 1800 is -100. This
function is most useful for dates in the
20th century.
Date.setDate( ) Method | assign the day of the month
|
Availability
Flash 5
Synopsis
date.setDate(day)
Arguments
- day
An integer from 1 to 31, representing the new day of the month for
date. If you specify a day greater than
the number of days in the current month, it will cause the month to
increment accordingly. For example, if the current
month is 8 (September) and you specify 31
for the new day, it will be treated as
October 1. The day will become 1 and the
month will become 9 (October).
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970.
See Also
Date.getDate( )
Date.setFullYear( ) Method | assign the century and year in four-digit format
|
Availability
Flash 5
Synopsis
date.setFullYear(year, month, day)
Arguments
- year
A four-digit integer representing the new year for
date, for example 1999 or 2000.
- month
An optional integer from 0
(January) to 11 (December), not 1 to 12, representing the new month
of the year of date. Defaults to
if not specified.
- day
An optional integer from 1 to 31 representing the new day of the
month of date. Defaults to 1 if not
specified.
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970.
See Also
Date.setYear( ), Date.getFullYear(
)
Date.setHours( ) Method | assign the hour of the day
|
Availability
Flash 5
Synopsis
date.setHours(hour)
Arguments
- hour
An integer from 0
(midnight) to 23 (11 p.m.) specifying the new hour of the day for
date.
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970.
See Also
Date.getHours( )
Date.setMilliseconds( ) Method | assign the milliseconds of a date
|
Availability
Flash 5
Synopsis
date.setMilliseconds(ms)
Arguments
- ms
An integer from 0
to 999 representing the new milliseconds of
date not the number of milliseconds since
1970. Values above 999 or below
are carried over to the seconds of date .
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970.
See Also
Date.getMilliseconds( ), Date.setTime(
)
Date.setMinutes( ) Method | assign the minutes of a date
|
Availability
Flash 5
Synopsis
date.setMinutes(minute)
Arguments
- minute
An integer from 0
to 59 representing the new minutes of the hour of
date . Values above 59 or below 0
are carried over to the hours of date .
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970.
See Also
Date.getMinutes( )
Date.setMonth( ) Method | assign the month of the year
|
Availability
Flash 5
Synopsis
date.setMonth(month)
Arguments
- month
An integer from 0
(January) to 11 (December), not from 1 to 12, representing the new
month of the year of date. Values above 11
or below
are carried over to the year of date .
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970.
Usage
Be careful not to assume that 1 is January! Months start at 0, not 1.
See Also
Date.getMonth( )
Date.setSeconds( ) Method | assign the seconds of a date
|
Availability
Flash 5
Synopsis
date.setSeconds(second)
Arguments
- second
An integer from 0
to 59 representing the new seconds of the minute of
date . Values above 59 or below 0
are carried over to the minutes of date .
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970.
See Also
Date.getSeconds( )
Date.setTime( ) Method | assign a new date based on the number of milliseconds between January 1, 1970 and the new date
|
Availability
Flash 5
Synopsis
Date.setTime(milliseconds)
Arguments
- milliseconds
An integer expressing the number of milliseconds between the new
desired date and midnight, January 1, 1970. Positive if after January
1, 1970; negative if before.
Returns
The value of milliseconds.
Description
Internally, all dates are represented as the number of milliseconds
between the time of the date and midnight, January 1, 1970. The
setTime( ) method specifies a new date using the
internal millisecond representation. Setting a date using
milliseconds from 1970 is often handy when we're determining
differences between multiple dates and times using getTime(
).
Example
Using setTime( ) in concert with
getTime( ) we can adjust the time of an existing
date by adding or subtracting milliseconds. For example, here we add
one hour to a date:
now = new Date( );
now.setTime(now.getTime( ) + 3600000);
And here we add one day:
now = new Date( );
now.setTime(now.getTime( ) + 86400000);
To improve the readability of our code, we create variables
representing the number of milliseconds in an hour and milliseconds
in a day:
oneDay = 86400000;
oneHour = 3600000;
now = new Date( );
// Subtract one day and three hours.
now.setTime(now.getTime( ) - oneDay - (3 * oneHour));
See Also
Date.getTime( ), Date.setMilliseconds(
), Date.UTC( ), getTimer(
)
Date.setUTCDate( ) Method | assign the day of the month (UTC time)
|
Availability
Flash 5
Synopsis
date.setUTCDate(day)
Arguments
- day
An integer from 1 to 31, representing the new day of the month for
date in UTC time. If you specify a day
greater than the number of days in the current month, it will cause
the month to increment accordingly. For example, if the current
month is 8 (September) and you specify 31
for the new day, it will be treated as
October 1. The day will become 1 and the
month will become 9 (October).
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970 in UTC time.
Date.setUTCFullYear( ) Method | assign the century and year infour-digit format (UTC time)
|
Availability
Flash 5
Synopsis
date.setUTCFullYear(year)
Arguments
- year
A four-digit integer representing the new year for
date in UTC time, for example 1999 or
2000.
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970 in UTC time.
Date.setUTCHours( ) Method | assign the hour of the day (UTC time)
|
Availability
Flash 5
Synopsis
date.setUTCHours(hour)
Arguments
- hour
An integer from 0
(midnight) to 23 (11 p.m.) representing the new hour of the day for
date in UTC time.
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970 in UTC time.
Date.setUTCMilliseconds( ) Method | assign the milliseconds of a date (UTC time)
|
Availability
Flash 5
Synopsis
date.setUTCMilliseconds(ms)
Arguments
- ms
An integer from 0
to 999 representing the new milliseconds of
date in UTC time.
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970 in UTC time.
Date.setUTCMinutes( ) Method | assign the minutes of a date (UTC time)
|
Availability
Flash 5
Synopsis
date.setUTCMinutes(minute)
Arguments
- minute
An integer from 0
to 59 representing the new minutes of the hour of
date in UTC time.
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970 in UTC time.
Date.setUTCMonth( ) Method | assign the month of the year (UTC time)
|
Availability
Flash 5
Synopsis
date.setUTCMonth(month)
Arguments
- month
An integer from 0
(January) to 11 (December), not from 1 to 12, representing the new
month of the year of date in UTC time.
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970 in UTC time.
Usage
Be careful not to assume that 1 is January! Months start at 0, not 1.
Date.setUTCSeconds( ) Method | assign the seconds of a date (UTC time)
|
Availability
Flash 5
Synopsis
date.setUTCSeconds(second)
Arguments
- second
An integer from 0
to 59 representing the new seconds of the minute of
date in UTC time.
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970 in UTC time.
Date.setYear( ) Method | assign the year, relative to 1900
|
Availability
Flash 5
Synopsis
date.setYear(year, month, day)
Arguments
- year
A required integer specifying the new year of date
. If one or two digits are supplied, the year is
assumed to be in the 20th century. For example, 1 is the year 1901,
and 99 is the year 1999. Three-digit years are assumed to be pre-1000
A.D. Use four digits to specify the year 2000 and later.
- month
An optional integer from 0
(January) to 11 (December), not from 1 to 12, representing the new
month of the year of date.
- day
An optional integer from 1 to 31 representing the new day of the
month of date.
Returns
An integer representing the number of milliseconds between the new
date and midnight, January 1, 1970.
Description
setYear( ) is identical to setFullYear( ) except that it interprets one- and two-digit years as being relative to 1900 whereas setFullYear( ) interprets them as being relative to 0 A.D.
See Also
Date.getYear( ), Date.setFullYear(
)
Date.UTC( ) Class
Method | retrieve the number of milliseconds between January 1, 1970 and a supplied UTC date
|
Availability
Flash 5
Synopsis
Date.UTC(year, month, day, hours, minutes, seconds, ms)
Arguments
- year,...ms
A series of numeric values describing the date and time but supplied
in UTC time, not local time. For descriptions of each argument see
the Date( ) constructor.
Returns
The number of milliseconds between the specified date and midnight,
January 1, 1970.
Description
The Date.UTC( ) method takes the same arguments
as the Date( ) constructor, but instead of
returning an object for the specified date, Date.UTC(
) returns a number indicating the date in the internal
milliseconds-from-1970 format. The returned number is typically used
to construct a new Date object in UTC or to
assign a UTC time to an existing Date object via
the setTime( ) method.
Example
The following code shows how to measure the milliseconds elapsed
between midnight 1970 and midnight 2000 in UTC time:
trace(Date.UTC(2000, 0) + " milliseconds passed between 1970 and 2000.");
// Displays: "946684800000 milliseconds passed between 1970 and 2000."
Here we use those elapsed milliseconds to construct a UTC-time-based
Date object:
nowUTC = new Date(Date.UTC(2000, 0));
If that code were invoked in EST (Eastern Standard Time), which is 5
hours behind UTC, nowUTC would represent the local
time 7p.m. on December 31, 1999. When we check the hour using the
non-UTC method getHours( ), we get the local
hour, 19 (7p.m. in a 24-hour clock):
trace(nowUTC.getHours( )); // Displays: 19
But when we check the hour using the UTC method
getUTCHours( ), we get the correct UTC hour,
(midnight in a 24-hour clock):
trace(nowUTC.getUTCHours( )); // Displays: 0
See Also
Date( ), Date.setTime( ),
the Date class
Date.valueOf( )
Method | the number of milliseconds between January 1, 1970 and the time of the Date object
|
Availability
Flash 5
Synopsis
date.valueOf()
Returns
An integer expressing the number of milliseconds between the time of
the Date object and midnight, January 1, 1970.
Positive if after January 1, 1970; negative if before.
Description
In practice, Date.valueOf( ) is equivalent to
Date.getTime( ).
See Also
Date.toString( )
duplicateMovieClip( ) Global Function | create a copy of a movie clip
|
Availability
Flash 4 and later
Synopsis
duplicateMovieClip(target, newName, depth)
Arguments
- target
A string indicating the path to the movie clip to duplicate (known as
the seed clip ). Nested
clips may be referred to with dot syntax, as in
duplicateMovieClip("_root.myClip", "myClip2",
0). Because a movie clip reference is converted to a path
when used in a string context, target may
also be a movie clip object reference, as in
duplicateMovieClip(myClip, "myClip2", 0).
- newName
A string that will become the instance name of the duplicated clip.
The string used must adhere to the rules for creating an identifier
outlined in Section 14.5, "Identifiers" in Chapter 14, "Lexical Structure".
- depth
An integer indicating the level in the programmatic clip stack on
which to place the duplicated clip. Clips on lower levels are placed
visually behind clips on higher levels. The movie clip with the
highest depth in a stack obscures all the
clips below it. For example, a clip on
depth -1 appears behind a clip on
depth 0, which appears behind a clip on
depth 1. If the assigned
depth is occupied, the occupant clip is
removed, and the new duplicate takes its place. See Chapter 13, "Movie Clips" for additional details. Negative depths are
functional, but not officially supported by ActionScript; to ensure
future compatibility, use depths of 0
or greater.
Description
The duplicateMovieClip( ) function is one way to
create a new movie clip during movie playback (the other is
attachMovie( )). duplicateMovieClip(
) creates an identical copy of
target and places the copy in
target's clip stack on layer
depth. The duplicated clip begins playing
at frame 1 no matter what the frame of
target is when duplication occurs.
A duplicated clip inherits any transformations (rotation, scale,
etc.) that had been applied to target but
does not inherit the timeline variables of
target. The global function
duplicateMovieClip( ) is also available as a
movie clip method, though when used in that form, the
target argument is not used.
Example
// Copies the ball clip and names the copy ball2
duplicateMovieClip(ball, "ball2", 0);
// Moves the new ball2 clip over so we can see it
ball2._x += 100;
See Also
MovieClip.duplicateMovieClip( ),
removeMovieClip( ); Section 13.3.2.2, "Creating instances with duplicateMovieClip( )", Section 13.4.2.2, "How clips generated via duplicateMovieClip( ) are added to the stack",
and Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
eval( ) Global Function | convert a string to an identifier
|
Availability
Flash 4 and later
Synopsis
eval(stringExpression)
Arguments
- stringExpression
A string or an expression that yields a string. Should match the name
of some identifier.
Returns
The value of the variable represented by
stringExpression or a reference to the
object, movie clip, or function represented by
stringExpression. If
stringExpression does not represent a
variable or a movie clip, undefined is returned.
Description
The eval( ) function provides a means of
constructing a dynamic reference to an identifier based on a string
of text. eval( ) converts a string to a
variable, movie clip, object property, or other identifier and then
evaluates that identifier. For example, here we use the return value
of eval( ) to set the value of a variable:
name1 = "Kathy";
count = 1;
currentName = eval("name" + count); // Sets currentName to "Kathy"
And here we control a dynamically-named movie clip,
star1:
eval("star" + count)._x += 100; // Move star1 right 100 pixels
But we may also use an eval( ) invocation in
place of an identifier that is the lefthand operand of an assignment
expression, as in:
eval("name" + count) = "Simone"; // Sets name1 to "Simone"
Note that, unlike its JavaScript cousin, eval( )
in ActionScript does not allow for the compiling and execution of
arbitrary blocks of code in a string. Full support of eval(
) would require an ActionScript compiler in the Player,
which would cause too great an increase in the Player size.
Usage
As of Flash 5, eval( ) is rarely needed for
dynamic variable access. When managing multiple pieces of data, use
arrays and objects instead.
Example
The eval( ) function is often used to convert
the MovieClip._droptarget
string property to a movie clip object reference. In the following
example, suppose we have a series of cartoon face clips. When the
user drops a food clip onto one of the faces, we
retrieve the path to the face in question using
_droptarget, then we use eval(
) to retrieve an object reference to that face. Finally,
we send the face to a frame showing the mouth full of food:
// Convert _droptarget string to a reference
theFace = eval(food._droptarget);
// Control appropriate face clip using converted reference
theFace.gotoAndStop("full");
See Also
See Section 4.6.10, "Executing Code in a String with eval" in Chapter 4, "Primitive Datatypes"
_focusrect Global Property | the highlight state used for buttons activated via the keyboard
|
Availability
Flash 4 and later
Synopsis
_focusrect
Access
Read/write
Description
When the mouse hovers over a button in Flash, the content of the
button's Over state is displayed. Buttons can also gain
keyboard focus when the user presses the Tab key. When a button has
keyboard focus, Flash places a yellow rectangle over that button,
which is not always aesthetically desirable. You can turn off the
yellow highlight rectangle using the _focusrect
global property, like so:
_focusrect = false;
When _focusrect is set to
false, Flash displays the Over state of
keyboard-focused buttons. When _focusrect is set
to true (its default), Flash displays the yellow
rectangle.
Usage
Though _focusrect is used in a Boolean sense, it
actually stores a number, not a Boolean. Although there's
rarely a reason to do so, if we examine the value of
_focusrect, it returns either 1 (indicating
true) or
(indicating false).
fscommand( ) Global Function | send a message to the standalone Player or to the Player's host application
|
Availability
Flash
3
and later (enhanced in Flash 5 to
include trapallkeys)
Synopsis
fscommand(command, arguments)
Arguments
- command
A string passed to the host application, often the name of a
JavaScript function.
- arguments
A string passed to the host application, often an argument to the
function named by command.
Description
With the fscommand( ) function, a Flash movie
can communicate with the standalone Player or with the Player's
host application -- the environment in which the Flash Player is
running (e.g., a web browser or Macromedia Director). The
fscommand( ) function is typically used in one
of three ways:
When used with the standalone Player, fscommand(
) takes one of the built-in sets of command
/argument pairs, as shown in
Table 20-5.
Table 20-5. command/argument Pairs in Standalone Player
Command |
Argument |
Description |
"allowscale" |
"true" or "false" |
When "false", prevents the contents of a movie
from growing or shrinking in relation to the window size of the
Player. "allowscale" is often used in combination
with "fullscreen" to create a Projector that
occupies the entire screen while maintaining the movie's
original size. |
"exec" |
"application_name" |
Launches an external application. The path to the application is
specified in the string application_name.
The path is resolved relative to the Flash movie unless
application_name is specified as an
absolute path such as: "C:/WINDOWS/NOTEPAD.EXE".
Note that the path uses forward slashes (
/ ), not backslashes ( \ ). |
"fullscreen" |
"true" or "false" |
When "true", causes the Player window to maximize,
filling the user's entire screen. |
"quit" |
not applicable |
Closes the movie and exits the Flash projector (standalone Player). |
"showmenu" |
"true" or "false" |
When "false", suppresses the display of the
controls in the context menu of the Player, leaving only the About
Macromedia Flash Player option. The context menu is accessed via
right-click on Windows and Ctrl-click on Macintosh. |
"trapallkeys" |
"true" or "false" |
When "true", causes all keystrokes -- even
keyboard shortcuts -- to be sent to the Flash movie.
trapallkeys is used to disable the control keys in
the standalone Player (e.g., Ctrl-F or Command-F for Full Screen
mode, Ctrl-Q or Command-Q for Exit, Esc for Stop/exit Full Screen
mode, etc.). Added to fscommand in Flash 5. |
When used in a browser, the execution of an fscommand(
) function in a movie causes the invocation of a special
JavaScript function (Netscape) or VBScript function (Internet
Explorer) on the page that contains the movie. The name of this
special function takes the general form
movieID_DoFSCommand
where movieID is the name specified in the
movie's OBJECT ID attribute (Internet
Explorer) or EMBED NAME attribute (Netscape) from
the host HTML document. When
movieID_DoFSCommand(
) is invoked, the values of the fscommand( )
's command and
arguments parameters are passed to the
movieID_DoFSCommand(
) function as arguments. If no
movieID_DoFSCommand(
) function exists in the host page, fscommand(
) fails silently.
Note that in order for fscommand( ) to work with
Netscape, the swLiveConnect attribute of the
movie's EMBED tag must be set to
"true". For example:
<EMBED
NAME="testmovie"
SRC="myMovie.swf"
WIDTH="100%"
HEIGHT="100%"
swLiveConnect="true"
PLUGINSPAGE="http://www.macromedia.com/go/flashplayer/"
</EMBED>
Usage
It is not possible to communicate with a browser
via fscommand( ) under the following system
configurations:
Note that fscommand( ) does not always provide
the best means of communicating with a Director movie from Flash. The
preferred director communication device is a getURL(
) function with either the event: or
lingo: protocol. For details, see the
getURL( ) function or the following Macromedia
tech notes:
http://www.macromedia.com/support/director/ts/documents/flash_xtra_sending_events.htm
http://www.macromedia.com/support/director/ts/documents/flash_xtra_lingo.htm
http://www.macromedia.com/support/director/ts/documents/flash_tips.htm
Example
To quit a
standalone Projector, use:
fscommand("quit");
To create a standalone Projector that runs fullscreen, use:
fscommand("fullscreen", "true");
To create a standalone Projector that runs fullscreen but maintains
the original movie's size, use:
fscommand("fullscreen", "true");
fscommand("allowscale", "false");
For information on launching a movie in a fullscreen
web browser window, see
http://www.moock.org/webdesign/flash/launchwindow/fullscreen.
To launch Notepad on most Windows systems, use:
fscommand("exec", "C:/WINDOWS/NOTEPAD.EXE");
The following code shows an HTML page with the JavaScript and
VBScript needed to respond to a simple fscommand(
) from a movie. Notice that the VBScript function simply
calls the JavaScript function; this allows us to handle both Internet
Explorer and Netscape with a single JavaScript function:
<HTML>
<HEAD>
<TITLE>fscommand demo</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function testmovie_DoFSCommand(command, args) {
alert("Here's the Flash message " + command + ", " + args);
}
//-->
</SCRIPT>
<SCRIPT LANGUAGE="VBScript">
<!--
Sub testmovie_FSCommand(ByVal command, ByVal args)
call testmovie_DoFSCommand(command, args)
end sub
//-->
</SCRIPT>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<OBJECT
ID="testmovie"
CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
WIDTH="100%"
HEIGHT="100%"
CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
<PARAM NAME="MOVIE" VALUE="flash-to-javascript.swf">
<EMBED
NAME="testmovie"
SRC="flash-to-javascript.swf"
WIDTH="100%"
HEIGHT="100%"
swLiveConnect="true"
PLUGINSPAGE="http://www.macromedia.com/go/flashplayer/"
</EMBED>
</OBJECT>
</BODY>
</HTML>
To invoke the preceding testmovie_DoFSCommand( )
JavaScript function from the
flash-to-javascript.swf movie, we'd use:
fscommand("hello", "world");
See Also
For more information on fscommand( ) and
controlling Flash with JavaScript, see:
http://www.moock.org/webdesign/flash/fscommand
http://www.macromedia.com/support/flash/publishexport/scriptingwithflash
getProperty( ) Global Function | retrieve the value of a movie clip property
|
Availability
Flash 4; deprecated in Flash 5
Synopsis
getProperty(movieClip, property)
Arguments
- movieClip
An expression that yields a string indicating the path to a movie
clip. In Flash 5, this may also be a movie clip reference because
movie clip references are converted to paths when used in a string
context.
- property
The name of the built-in property to retrieve. Must be an identifier,
not a string (e.g., _x, not
"_x").
Returns
The value of movieClip's
property.
Description
The getProperty( ) function retrieves the value
of one of a movie clip's built-in properties. Though
getProperty( ) was the only way to access object
properties in Flash 4, the . and
[] operators are the preferred property-access
tools in Flash 5 and later.
Example
Each of the following getProperty( ) invocations
retrieve the values of the _x property of a movie
clip named ball on the main movie timeline:
getProperty(ball, _x); // Relative movie clip reference
getProperty(_root.ball, _x); // Absolute movie clip reference
getProperty("ball", _x); // Relative path in string
getProperty("_root.ball", _x); // Dot path in string
getProperty("/ball", _x); // Slash path in string
The following code shows similar property access using the dot and [
] operators:
ball._x;
_root.ball._x;
ball["_x"];
_root["ball"]["_x"];
See Also
setProperty( ) ; Section 13.1, "The "Objectness" of Movie Clips" in Chapter 13, "Movie Clips"
getTimer( ) Global Function | determine the age of a movie, in milliseconds
|
Availability
Flash 4 and later
Synopsis
getTimer()
Returns
The number of milliseconds that have passed since the movie started
playing.
Description
The getTimer( ) function indicates how long a
movie has been playing, in milliseconds. We can use multiple
getTimer( ) checks to govern the timed execution
of a block of code or to add time-based features to a movie, such as
a countdown in a video game. For example, when attached to a movie
clip that contains a text field named
counterOutput, the following code counts down from
60 to 0:
onClipEvent (load) {
// Record the current time
var startTime = getTimer( );
// Set the number of seconds to count down
var countAmount = 60;
// Initialize a variable to keep track of how much time has passed
var elapsed = 0;
}
onClipEvent (enterFrame) {
// Check how much time has passed
elapsed = getTimer( ) - startTime;
// If the time passed is less than the length of our countdown...
if (elapsed < countAmount * 1000) {
// ...set the text field to show the amount of time left
counterOutput = countAmount - Math.floor(elapsed / 1000);
} else {
// ...otherwise, our countdown is done, so tell the user
counterOutput = "Time's UP!";
}
}
To determine the number of full seconds that have passed in a movie
(rather than milliseconds), divide the return of getTimer(
) by 1000 and trim off the decimal portion with either
Math.floor( ), Math.round(
), or Math.ceil( ). For example:
numSeconds = Math.floor(getTimer( )/1000);
Example
The following code loops between two frames until a movie is more
than 10 seconds old and then plays the movie:
now = getTimer( );
if (now > 10000) {
play( );
} else {
gotoAndPlay(_currentframe - 1);
}
See Also
Date( ), the Date class
getURL( ) Global Function | load a document into a browser, execute server-sidescripts, or trigger Macromedia Director events
|
Availability
Flash 2 and Flash 3; enhanced in Flash 4 to
include method parameter; Flash 5
Synopsis
getURL (URL)
getURL (URL, window)
getURL (URL, window, method)
Arguments
- URL
A string specifying the absolute or relative location of the document
to load or external script to run.
- window
An optional string specifying the name of the browser window or frame
into which to load the document. May be a custom name or one of the
four presets: "_blank",
"_parent", "_self", or
"_top".
- method
An optional string specifying the method by which to send the current
timeline's variables to an external script -- either
"GET" or "POST". This parameter
must be a literal string, not a variable or other expression. The
standalone version of the Flash Player always uses the
"GET" method, regardless of the
method specified.
Description
The getURL( ) function is used to:
To load a document into the current window or frame, simply specify
the URL of the document without supplying a
window or
method argument. Naturally, Flash supports
absolute URLs (those that contain a protocol such as
"http:" plus a server name or hardware device) and
relative URLs (those that are relative to the current location):
getURL("http://www.moock.org/"); // Absolute URL to web page
getURL("file:///C|/WINDOWS/Desktop/index.html"); // Absolute URL to local file
getURL("/whatever/index.html"); // Relative URL, http protocol
//is assumed
To load a document into a named window or frame, supply the window or
frame name as the window argument. For
example:
getURL("http://www.moock.org/", "contentFrame"); // Load into named frame
getURL("http://www.moock.org/", "remoteWin"); // Load into named window
To replace the frameset that contains the current movie, use
"_ parent" as the value of the
window argument. For example:
getURL("http://www.moock.org/", "_parent");
To replace all framesets in a web page with a
loaded document, use "_top" as the value of the
window argument. For example:
getURL("http://www.moock.org/", "_top");
To open a loaded document in a new, anonymous browser window, use
"_blank" as the value of the
window argument. For example:
getURL("http://www.moock.org/", "_blank");
Note that launching a new window with "_blank"
does not give us any control over the appearance of the new window
(size, toolbar configuration, location, etc.). To launch customized
windows with getURL( ), we must invoke a
JavaScript function on the movie's host page. JavaScript
window-launching techniques are described at http://www.moock.org/webdesign/flash.
The getURL( ) function may also be used to send
variables to a remote server application or script. To send the
current movie clip's timeline variables to an external script,
specify the name of the script as the URL
argument, and use either "GET" or
"POST" as the value of the
method argument. For example:
getURL("http://www.someserver.com/cgi-bin/search.pl", "resultsFrame", "GET");
When invoked as a movie clip method, getURL( )
sends the timeline variables of that clip, as in:
// Sends myClip's variables to search.pl
myClip.getURL("http://www.server.com/cgi-bin/search.pl", "resultsFrame", "GET");
The results of the script execution will appear in the window or
frame specified in the getURL( ) 's
window argument (which is required when
variables are submitted).
To load the results of a script execution into the current frame or
window, use "_self" as the
window argument value, as in:
getURL("http://www.someserver.com/cgi-bin/search.pl", "_self", "GET");
When the method argument is
"GET", the current movie clip timeline variables
are sent as a query string attached to the script URL in an HTTP GET
request. Query strings are composed of variable name/value pairs,
separated by ampersands (&). For example:
http://www.someserver.com/cgi-bin/search.pl?term=javascript&scope=entiresite
When the method argument is
"POST", the current movie clip timeline variables
are sent to the script as a separate block of data after the HTTP
POST-request header (exactly like a regular HTML form that uses the
POST method). Note that "POST" is not available in
the standalone Flash Player.
Because most web servers restrict the length of URLs to between 255
and 1024 characters, use "POST" instead of
"GET" to transfer larger amounts of data.
Note that any returned information sent by a script invoked by
getURL( ) is displayed as regular web content in
the browser, not in Flash. To accept the results of a script
execution into Flash, use loadVariables( ).
The getURL( ) function can also be used with
protocols other than "http:" as shown in Table 20-6.
Table 20-6. Supported Protocols for getURL
Protocol |
Format |
Purpose |
event |
"event: eventName
params" |
Send an event to Director if the Flash asset is a Director sprite. |
file |
"file:///driveSpec/folder/filename" |
Access a local file. |
ftp |
"ftp://server.domain.com/folder/filename" |
Access a remote file via FTP (file transfer protocol). |
http |
"http://server.domain.com/folder/filename" |
Access remote file via HTTP (hypertext transfer protocol). |
javascript |
"javascript: command " |
Perform JavaScript command in browser. |
lingo |
"lingo: comand " |
Perform Lingo command if Flash asset is a Director sprite. |
print |
"print:", "targetClip " |
Prints in Flash 4, prior to the availability of the print(
) function in Flash 5. |
vbscript |
"vbscript: command " |
Perform VBScript command in browser. |
As Table 20-6 shows, if the Flash asset is imported
into a Macromedia Director file, getURL( ) can
be used to trigger Lingo events or execute a Lingo command. (Lingo is
Director's scripting language, akin to ActionScript). For
example, you can add a frame event of this form:
getURL ("event: eventName params");
which will cause the Lingo event handler named on
eventName to be called in Director. Here is a
getURL( ) statement that generates an event
named "myEvent" and passes it the string "A".
Note that the " character is escaped using the
sequence \":
getURL ("event: myEvent \"A\""); // Send an event to Director
Here is the Lingo
sprite event handler that should be attached
to the Flash sprite asset in Director in order to receive the event.
Note that a Director sprite is roughly equivalent to a Flash movie
clip instance; the Lingo keyword put is akin to
ActionScript's trace( ) command, and
&& is Lingo's string concatenation
operator:
on myEvent msg
put "The message received from Flash was " && msg
end
You can also trigger Lingo to be executed from a Flash sprite within
Director using the "lingo:" keyword, such as:
getURL ("lingo: beep"); // Tell Director to play a beep sound
Note that Director 8.0 cannot import Flash 5
.swf files, but an updated Flash asset Xtra is
expected to be available by the time you read this.
Finally, getURL( ) can also be used to execute
JavaScript code. Here we invoke a simple JavaScript
alert using getURL( ):
getURL ("javascript: alert('hello world');");
Note that execution of JavaScript code from a URL does not work in
Internet Explorer 4.5 for Macintosh.
Example
Here's the code for a standard button that links to a web page:
on (release) {
getURL("http://www.macromedia.com/");
}
Bugs
Internet Explorer 4.5 (IE 4.5) and older versions on Macintosh do not
support the "POST" method of a getURL(
) call. To service those browsers, use
"GET" instead of "POST"
(subject to the length limitations cited earlier).
In most browsers, getURL( ) relative links are
resolved relative to the HTML file that contains the
.swf file. In IE 4.5 and older versions on
Macintosh, relative links are resolved relative
to the location of the .swf file, not the HTML
file, which causes problems when the two are in different
directories. To avoid the problem, either place the
.swf and the .html file in
the same directory or use absolute URLs when invoking
getURL( ), such as:
getURL ("http://www.someserver.com/")
See Also
loadVariables(
), MovieClip.getURL( ), movieClip.loadVariables(
); Section 18.5.7, "< A> (Anchor or Hypertext Link)" in Chapter 18, "On-Screen Text Fields"
getVersion( ) Global Function | examine the platform and version of the Flash Player
|
Availability
Flash 5
Synopsis
getVersion()
Returns
A string containing version and platform information for the Flash
Player hosting the current movie.
Description
The getVersion( ) function tells us the platform
and Flash Player version being used to view a movie. It can be used
to conditionally execute different code for specific versions of the
Flash Player or on certain operating systems. The string returned by
getVersion( ) takes the form:
platform majorVersion,minorVersion,buildNumber,patch
Where platform is a code indicating the
platform ("WIN", "MAC", or
"UNIX"), followed by the major version number, the
minor version number, and the build (a.k.a. revision) number. The
last item, patch, is typically 0. For
example:
WIN 5,0,30,0 // Version 5.0, Build 30 (5.0r30) on Windows
MAC 5,0,41,0 // Version 5.0, Build 41 (5.0r41) on Macintosh
UNIX 4,0,12,0 // Version 4.0, Build 12 (4.0r12) on Unix
Despite the Macromedia documentation's claim to the contrary,
getVersion( ) does work in the Flash authoring
tool's Test Movie mode. It reports the version number of the
Player embedded in the authoring tool (which is
not the same as the version of the authoring tool itself). For
example, the Flash 5 authoring tool embeds the 5.0 r30 version of the
Player, so its getVersion( ) function reports:
WIN 5,0,30,0
or
MAC 5,0,30,0
Any time a major or minor version of the authoring tool is created,
the buildNumber restarts at 0. However, in
the typical development cycle of the Flash authoring tool, many
builds of the Flash Player are produced before the final version of
the authoring tool is released. The build number of the first new
major version of a Player is, hence, usually greater than 0. For
example, the Flash 5 Player was first officially released at Build
30. Presumably, when Flash 6 is introduced, the Flash 6 Player will
return something like:
WIN 6,0,xx,0
but if a movie created in Flash 6 is played back in the Flash 5
Player, getVersion( ) would still return:
WIN 5,0,30,0
Typically, we're concerned with only the platform, the major
version, and the build number of a Player. To extract the portion of
the getVersion( ) string we're after, we
may use the string manipulation tools described in Chapter 4, "Primitive Datatypes", or we may construct a custom object with each
component of the getVersion( ) string assigned
to a property of that object as shown in the next example.
Unless we need to produce internal blocks of ActionScript code for a
specific version of the Flash Player, JavaScript and VBScript provide
better tools for version detection, browser sniffing, and automatic
page redirection. Furthermore, you can't use
getVersion( ) unless the user already has
version 5.0 or later of the Player. For details on detecting the
Flash Player's presence and version with JavaScript and
VBScript, see http://www.moock.org/webdesign/flash/detection/moockfpi.
Example
The following code extracts the various portions of the string
returned by getVersion( ) and stores them as the
properties of an object for easy access:
// Split up the getVersion( ) string into usable pieces
var version = getVersion( );
var firstSpace = version.indexOf(" ");
var tempString = version.substring(firstSpace + 1, version.length);
var tempArray = tempString.split(",");
// Assign the various parts of the getVersion( ) string to our object.
// Note that we convert the version number portions to integers.
var thePlayer = new Object( );
thePlayer.platform = version.substring(0,firstSpace);
thePlayer.majorVersion = parseInt(tempArray[0]);
thePlayer.minorVersion = parseInt(tempArray[1]);
thePlayer.build = parseInt(tempArray[2]);
thePlayer.patch = parseInt(tempArray[3]);
// Now use our object to perform version-specific code
if (thePlayer.platform == "WIN") {
// Perform Windows-specific code here.
} else if (thePlayer.platform == "MAC") {
// Perform Mac-specific code here.
} else if (thePlayer.platform == "UNIX") {
// Perform Unix-specific code here.
}
if ((thePlayer.majorVersion == 5) && (thePlayer.build == 30)) {
trace ("I recommend upgrading your player to avoid text display bugs");
}
See Also
$version; Appendix C, "Backward Compatibility"
gotoAndPlay( ) Global Function | move the playhead to a given frame, then play the current clip or movie
|
Availability
Flash 2 and later
Synopsis
gotoAndPlay(frameNumber)
gotoAndPlay(frameLabel)
gotoAndPlay(scene, frameNumber)
gotoAndPlay(scene, frameLabel)
Arguments
- frameNumber
A positive
integer indicating the number of
the frame to which the playhead of the current timeline should
proceed before playing. If frameNumber is less
than 1 or greater than the number of frames in the timeline, the
playhead is sent to either the first or last frame, respectively.
- frameLabel
A string indicating the label of the frame to which the playhead of
the current timeline should proceed before playing. If
frameLabel is not found, the playhead is
sent to the first frame of the timeline.
- scene
An optional string indicating the name of the scene that contains the
specified frameNumber or
frameLabel. If not supplied, the current
scene is assumed.
Description
When invoked without a scene argument,
gotoAndPlay( ) sends the playhead of the current
timeline to the frame specified by either the
frameNumber or
frameLabel and then plays the timeline
from that point. The "current timeline" is the movie clip
or movie from which the gotoAndPlay( ) function
is invoked.
If two arguments are specified in the gotoAndPlay(
) function call, the first argument is assumed to be the
scene. If only one argument is specified,
it is treated as a frameNumber or
frameLabel, and the current scene is
assumed.
When invoked with a scene argument,
gotoAndPlay( ) moves the playhead to the frame
number or label in the specified scene and then plays that scene. If
a scene argument is used, the
gotoAndPlay( ) function
must be invoked from the
_root timeline; otherwise, the operation fails
silently and the playhead is not sent to the destination frame. Note
that scenes are flattened into a single timeline during movie
playback. That is, if scene 1's timeline contains 20 frames,
and scene 2's timeline contains 10 frames, then we can send the
playhead to frame 5 of scene 2 using
gotoAndPlay(25);.
TIP
I recommend against using scenes when working with
ActionScript-intensive movies. Unlike movie clips, scenes are not
represented by objects and cannot be manipulated directly by most
built-in functions. It's normally better to use labels and
movie clips as pseudo-scenes in your timeline instead of
Flash's scene feature.
The global gotoAndPlay( ) function affects only
the current timeline. The frames or state of other movie clips within
the current timeline are not affected. To cause other movie clips to
play, you must issue a separate play( ) or
gotoAndPlay( ) command for each movie clip. To
apply the gotoAndPlay( ) function to a clip
other than the current movie clip, use the movie clip method form,
myClip.gotoAndPlay( ).
Bugs
In Build 5.0r30 of the Flash Player,
gotoAndPlay( ) did not work when used in an
onClipEvent( ) handler with a string literal for
frameLabel. To work around the bug, use
the movie clip variation of the function using
this to indicate the current clip, as in
this.gotoAndPlay("myLabel"), rather than
gotoAndPlay("myLabel").
Example
// Go to frame 5 of the current timeline and play it
gotoAndPlay(5);
// Go to frame 10 of the exitSequence scene, and play it
gotoAndPlay("exitSequence", 10);
// Go to frame "goodbye" of the exitSequence scene, and play it
gotoAndPlay("exitSequence", "goodbye");
// Caution! This plays the frame labeled "exitSequence" in the current scene.
gotoAndPlay("exitSequence");
// This plays frame 1 of the exitSequence scene
gotoAndPlay("exitSequence", 1);
See Also
gotoAndStop( ), MovieClip.gotoAndPlay(
), play( ), stop(
)
gotoAndStop( ) Global Function | move the playhead to a given frame and stop the current clip
|
Availability
Flash 2 and later
Synopsis
gotoAndStop(frameNumber)
gotoAndStop(frameLabel)
gotoAndStop(scene, frameNumber)
gotoAndStop(scene, frameLabel)
Arguments
- frameNumber
A positive integer indicating the number of the frame to which the
playhead of the current timeline should proceed. If
frameNumber is less than 1 or greater than the
number of frames in the timeline, the playhead is sent to either the
first or last frame, respectively.
- frameLabel
A string indicating the label of the frame to which the playhead of
the current timeline should proceed. If
frameLabel is not found, the playhead is
sent to the first frame of the timeline.
- scene
An optional string indicating the name of the scene that contains the
specified frameNumber or
frameLabel. If not supplied, the current
scene is assumed.
Description
When invoked without a scene argument,
gotoAndStop( ) sends the playhead of the current
timeline to the frame specified by either the
frameNumber or
frameLabel argument. The "current
timeline" is the movie or movie clip from which the
gotoAndStop( ) function is invoked. The playhead
will stop at the target frame; it will not advance automatically
after arriving at the target frame.
If two arguments are specified in the gotoAndStop(
) function call, the first argument is assumed to be the
scene. If only one argument is specified,
it is treated as a frameNumber or
frameLabel, and the current scene is
assumed.
When invoked with a scene argument,
gotoAndStop( ) moves the playhead to the frame
number or label in the specified scene and then halts playback. If a
scene argument is used, the
gotoAndStop( ) function
must be invoked from the
_root timeline; otherwise, the operation fails
silently and the playhead is not sent to the destination frame.
The global gotoAndStop( ) function affects only
the current timeline. The frames or state of other movie clips within
the current timeline are not affected. To move the playhead of other
movie clips, you must issue a separate gotoAndStop( )
command for each movie clip. To apply the
gotoAndStop( ) function to a clip besides the
current movie clip, use the movie clip method of the form
myClip.gotoAndStop( ).
Bugs
In Build 5.0r30 of the Flash 5 Player,
gotoAndStop( ) did not work when used in an
onClipEvent( ) handler with a string literal for
frameLabel. To work around the bug, use
the movie clip variation of the function using
this to indicate the current clip, as in
this.gotoAndStop("myLabel"), rather than
gotoAndStop("myLabel").
Example
// Go to frame 5 of the current timeline and stop there
gotoAndStop(5);
// Go to frame 20 of the introSequence scene and stop there
gotoAndStop("introSequence", 20);
// Go to frame "hello" of the introSequence scene, and stop there
gotoAndStop("introSequence", "hello")
// Caution! This goes to the frame labeled "introSequence" in the current scene
gotoAndStop("introSequence")
// This goes to frame 1 of the introSequence scene
gotoAndStop("introSequence", 1)
See Also
gotoAndPlay(
), MovieClip.gotoAndStop(
), play( ), stop(
)
_highquality Global Property | the rendering quality of the Player
|
Availability
Flash 4; deprecated in Flash 5 in favor of _quality
Synopsis
_highquality
Access
Read/write
Description
The _highquality global property stores an integer
between 0
and 2 that dictates the rendering quality of the Flash Player as
follows:
- 0
Low quality. Neither bitmaps nor vectors are antialiased (smoothed).
- 1
High quality. Vectors are antialiased. Bitmaps are antialiased when
no animation is occurring.
- 2
Best quality. Both bitmaps and vectors are always antialiased.
As of Flash 5, _highquality has been superseded by
_quality, which may be used to set a movie's
quality to "Medium", as well as "Low",
"High", and "Best".
See Also
_quality, toggleHighQuality( )
#include Directive | import the text of an external ActionScript file
|
Availability
Flash 5
Synopsis
#include path
Arguments
- path
A string indicating the name and location of the script file to
import, which may be specified relative to the
.fla file or as an absolute path (see samples
under Example). Note that forward slashes, not backslashes should be
used in the path. Script files should be named with the
.as file extension.
Description
The #include directive brings
script text from an external text file (preferably one with the
.as extension) into the current script, placing
it directly where the #include command occurs in
the script. The #include operation is performed
at compile time, meaning that the text included in a movie is the
text that existed at the time the movie was tested, exported, or
published from the authoring tool. If the external file changes after
the movie is exported, the changes will not be reflected in the
movie. In order for the changes to be added to the movie, the movie
must be re-exported.
The #include directive is used to incorporate the
same block of code in multiple scripts or across Flash projects (much
as you'd use an external asset library). You would do this in
order to centralize your code, when maintaining code in a
version-control system tool (such as CVS or Microsoft Visual Source
Safe), or when using an external text editor that you prefer over the
ActionScript editor. It is also handy when a programmer is working
separately from, say, a graphic artist creating the Flash animations.
External files lend themselves well to code repositories, such as a
library of functions that are independent of the current timeline or
movie clip. They tend to be less useful for code that needs to be
tightly integrated with the Flash file.
Usage
Note that an #include directive begins with a
pound sign (#), does not use parentheses, and must
not end in a semicolon. Any
#include statements that end in a semicolon will
cause an error and will not successfully import an external script.
If the file can't be found at the specified path, the directive
will cause an error and no external text will be included. The text
in the external file is also checked when performing a syntax check
using the Check Syntax command (Ctrl-T or Command-T) in the Actions
panel menu (found under the arrow button in the upper-right corner of
the panel).
Example
The following code imports an external .as file
named myScript.as into the current
.fla file. When using a relative path,
myScript.as would have to be in the same folder
as the .fla file containing the include
directive:
#include "myScript.as"
We can construct a relative path including a subdirectory. The
following assumes that myScript.as is one level
down from the current .fla file in a
subdirectory named includes:
#include "includes/myScript.as"
Use two dots to indicate the folder above the current folder. The
following assumes that myScript.as is one level
up from the current .fla
file:
#include "../myScript.as"
The following assumes that myScript.as is in a
subdirectory named includes adjacent to the
subdirectory containing the current .fla file:
#include "../includes/myScript.as"
You can also specify an absolute path to any folder, such as:
#include "C:/WINDOWS/Desktop/myScript.as"
but absolute paths are not cross-platform and may need to be changed
if you compile the .fla file on a different
machine with different directories. Note the differences in the drive
letter specification:
#include "C:/WINDOWS/Desktop/myScript.as" // Windows
#include "Mac HD:Desktop folder:working:myScript.as" // Macintosh
See Also
See Section 16.7, "Externalizing ActionScript Code" in Chapter 16, "ActionScript Authoring Environment"
Infinity Global Property |
a constant representing an infinite number
|
Availability
Flash 5
Synopsis
Infinity
Access
Read-only
Description
Any number in ActionScript that exceeds the maximum allowed numeric
range is represented by the numeric constant
Infinity. The largest value allowed in
ActionScript is represented by Number.MAX_VALUE
(1.7976931348623157e+308).
Example
The result of a calculation that exceeds the largest allowed number
is Infinity. For example:
Number.MAX_VALUE * 2; // Yields Infinity
Infinity also results when dividing a positive
number by zero:
1000 / 0; // Yields Infinity
Usage
Infinity is shorthand for
Number.POSITIVE_INFINITY.
See Also
-Infinity,
Number.POSITIVE_INFINITY; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
-Infinity Global Property | a constant representing an infinitely negative number
|
Availability
Flash 5
Synopsis
-Infinity
Access
Read-only
Description
Any number in ActionScript that exceeds the allowed
negative numeric range is represented by the
numeric constant -Infinity. The smallest negative
value (the one with the largest absolute value) allowed in
ActionScript is -Number.MAX_VALUE, which is
equivalent to -1.7976931348623157e+308.
Example
The result of a calculation that is smaller than (i.e., more negative
than) the smallest allowed negative number is
-Infinity. For example:
-Number.MAX_VALUE * 2; // Yields -Infinity
-Infinity also results when dividing a negative
number by zero:
-1000 / 0; // yields -Infinity
Usage
-Infinity is shorthand for
Number.NEGATIVE_INFINITY.
See Also
Infinity,
Number.NEGATIVE_INFINITY; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
int( ) Global Function | truncate the decimal portion of a number
|
Availability
Flash 4; deprecated in Flash 5 in favor of analogous
Math methods
Synopsis
int(number)
Arguments
- number
A number or an expression that yields a number, typically a number
with a fractional (decimal) portion.
Returns
The integer portion of number.
Description
The int( ) function was used in Flash 4 as a
brute-force means of extracting the integer portion of a number. It
effectively rounds positive numbers down and rounds negative numbers
up. The int( ) function works only for numbers
in the range -2147483648 (-231) to
2147483647 (231-1); it produces undefined
results for numbers outside this range. If
number is a string composed of only
numbers, int( ) converts the string to a number
before operating on it. If number is the
Boolean value true, int( )
returns the value 1. For all other non-numeric data (including
undefined and null),
int( ) returns the value 0.
Usage
The int( ) function has been deprecated in favor
of the more precise and standard Math.floor( ),
Math.ceil( ), and Math.round(
) methods. Use parseInt( ) or
Number( ) to convert non-numeric data to an
integer or number.
Example
int(4.5) // Yields 4
int(-4.5) // Yields -4
int(3.999) // Yields 3
The int( ) function is useful to check if a
number is a whole number by comparing the original number to the
result of the int( ) function:
if (int(x) != x) {
trace ("Please enter a whole number for your age in years");
}
See Also
Math.ceil( ), Math.floor(
), Math.round( ), Number(
), parseFloat( ), parseInt(
)
isFinite( ) Global Function | check if a number is less than Infinity and greater than -Infinity
|
Availability
Flash 5
Synopsis
isFinite(number)
Arguments
- number
Any numeric value or expression that yields a numeric value.
Returns
A Boolean value; true if the number falls between
Number.MAX_VALUE and
-Number.MAX_VALUE (inclusive),
false if not. If number
does not belong to the number datatype,
number is converted to the
number type before isFinite(
) executes.
Description
The isFinite( ) function simply checks if a
number is in the legal numeric value range of ActionScript. Use
isFinite( ) before executing code that requires
a legitimate number to operate properly.
Example
if (!isFinite(x * y)) { // Test if the number is not finite
trace ("The answer is too large to display. Try again.");
}
isFinite(-2342434); // Yields true
isFinite(Math.PI); // Yields true
isFinite(Number.MAX_VALUE * 2) // Yields false
See Also
-Infinity, Infinity,
isNan( ),
Number.MAX_VALUE,
Number.MIN_VALUE; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
isNaN( ) Global Function | equality test for the special NaN value
|
Availability
Flash 5
Synopsis
isNaN(value)
Arguments
- value
The expression to test.
Returns
A Boolean value: true if
value is the special numeric value
NaN; otherwise, false.
Description
To test whether or not a value is equal to the special numeric value
NaN, we must use the isNaN( )
function because NaN does not test equal to itself
in an ordinary equality test. For example, the expression:
NaN == NaN;
yields the value false. The isNaN(
) function is often used to check whether a mathematical
error (such as zero divided by itself) has occurred in a phrase of
code or whether converting a value to a legitimate number has failed.
Because isNaN( ) returns true
when the expression is not a valid numeric
expression, you'll often use the logical NOT operator
(!) along with isNaN( )
(something that is not not a number
is a number). Note that 0/0 yields
NaN, but all positive numbers divided by
yield Infinity, and all negative numbers divided
by
yield -Infinity.
Example
// Set a value
var x = "test123";
// Check if x is a legitimate number before using it is in a math expression.
// This is a handy technique for user input in text fields, which always a string.
if (!isNaN(parseFloat(x))) {
var y = parseFloat(x) * 2;
}
See Also
isFinite( ), NaN; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
Key Object | determine the state of keys on the keyboard
|
Availability
Flash 5
Synopsis
Key.property
Key.methodName()
Properties
Table 20-7 lists the properties of the
Key object.
Table 20-7. Key Object Keycode Properties
Methods
- getAscii( )
Returns the ASCII value of the last key pressed
- getCode( )
Returns the keycode of the last key pressed
- isDown( )
Checks if a specific key is currently depressed
- isToggled( )
Checks if the Num Lock, Caps Lock, or Scroll Lock keys are activated
Description
The Key object is used to determine which keys
are currently depressed and which key was last depressed. We can use
it to build interfaces controlled by the keyboard, such as a game
with a spaceship moved via the arrow keys.
Because not all keyboards are identical, keyboard-controlled
interfaces can sometimes be tricky to create. By choosing our
scripting tools correctly, however, we can ensure that all users have
the same experience.
There are two general approaches to detecting
keyboard commands:
We may check if a key is currently depressed via the
isDown( ) method. This is recommended for cases
in which keyboard input is constantly required, such as in video
games. We may check which key was last depressed using the
getCode( ) and getAscii( )
methods. This is recommended for typical keyboard-driven interfaces
in which specific operations are performed when keys are pressed. You
would ordinarily use these methods within a
keyDown event handler in order to distinguish
between different keys. There is no need to constantly check (i.e.,
poll) for the last key pressed. In fact, doing
so would lead to erroneously repeating some operation even if a key
wasn't pressed repeatedly. That is, you should generally check
getCode( ) and getAscii( )
within a keyDown event handler only because the
handler is guaranteed to be called once and only once for each
keystroke.
The so-called Windows virtual
keycode (or simply,
keycode) returned by getCode(
) and required by isDown( ) is a
number representing the physical keys on the keyboard, not the
symbols on those keys. By using the keycode, we can identify keys
even when a movie is running on different operating systems or when
two keyboards use different languages or have different symbol
layouts.
On most keyboards the keycodes of the
keys A to Z are the same as the code points (65-90) for the
equivalent uppercase Latin 1 letters. The keycodes of the keys
to 9 are, likewise, the same as the Latin 1 values for those numbers
(48-57). The key codes of other keys do not match Latin 1 code
points. However, many of the non-letter and non-number keycodes are
available as properties of Key. For example, we
don't have to remember that the up arrow uses keycode 38, we
simply use the Key.UP property. The following code
checks whether the up arrow key is currently depressed:
if (Key.isDown(Key.UP)) {
trace("The up arrow is being pressed");
}
When working with a keycode that is not a letter or a number and is
not available as a property of Key -- such as
those of the function keys (F1, F2, etc.) -- it's safest to
create a quick test movie to check the keycode of the desired key, as
follows:
trace(Key.getCode( ));
The keycodes are listed in Appendix B, "Latin 1 Character Repertoire and Keycodes".
See Also
Section 10.11.5, "keyUp" and Section 10.11.4, "keyDown" in Chapter 10, "Events and Event Handlers", and
Appendix B, "Latin 1 Character Repertoire and Keycodes"
Key.getAscii( ) Method | returns the ASCII value of the last key pressed
|
Availability
Flash 5
Synopsis
Key.getAscii()
Returns
An integer representing the ASCII value of the last key pressed.
Description
The getAscii( ) method returns the ASCII value
of the last key that was pressed. Since not all keys have an ASCII
value, getAscii( ) is normally used for
detecting letters and numbers from the Latin 1 character set (Western
European languages). Unlike getCode( ),
getAscii( ) distinguishes between upper- and
lowercase letters. But unlike getCode( ), it
cannot differentiate between two keys with the same ASCII value, such
as the 8 key on the main keyboard and the 8 key on the numeric
keypad.
To detect the pressing of specific keys relative to their physical
location on a keyboard rather than their ASCII value (such as would
be desirable when using four keys in a diamond pattern to control
game play), use getCode( ).
Example
The following example demonstrates keystroke detection for a simple
hangman word game. It uses a keyDown event
handler to identify the pressing of a key and adds that key to a list
of user guesses:
onClipEvent (keyDown) {
var lastKey = Key.getAscii( );
guessNum++;
userGuesses[guessNum] = String.fromCharCode(lastKey);
}
See Also
Key.getCode( ); Appendix B, "Latin 1 Character Repertoire and Keycodes",
and Section 10.11.4, "keyDown" in Chapter 10, "Events and Event Handlers"
Key.getCode( ) Method | returns the keycode of the last key pressed
|
Availability
Flash 5
Synopsis
Key.getCode()
Returns
An integer representing the keycode of the last key pressed.
Description
The getCode( ) method returns the keycode of the
last key that was pressed, which is an arbitrary number representing
the physical location of a key on the keyboard. On non-Windows
operating systems, the native keycode system is translated
automatically by Flash to the Windows equivalent, so
getCode( ) provides a cross-platform means of
referring to specific keys. The getCode( )
method can also be used to differentiate between two keys with the
same ASCII value. For example, it can differentiate between the 8 key
on the main keyboard and the 8 key on the numeric keypad, whereas
getAscii( ) cannot. However, getCode(
) cannot differentiate between upper- and lowercase
letters (for example, A and
a use the same keycode because they are produced
using the same key).
Many common keycode values are available as properties of the
Key object (e.g., Key.UP,
Key.BACKSPACE). To determine the keycode of a
particular key, see Appendix B, "Latin 1 Character Repertoire and Keycodes" or construct a
keycode tester as follows:
Create a new Flash
document.
At frame 2 of the timeline, add a
frame.
On frame 1, add the following code:
trace(Key.getCode( ));
Select Control Test Movie.
Click the movie's Stage.
Press a key. The key code for that key will appear in the Output
window.
Example
Unlike isDown( ), getCode(
) is useful for creating interfaces where an individual
key press has a single, direct result. For example, the user may be
able to skip a movie's intro by pressing the spacebar. When the
spacebar is depressed, we send the playhead to the main interface of
the movie (on the main timeline) as follows:
// Code on intro clip
onClipEvent (keyDown) {
if (Key.getCode( ) == Key.SPACE) {
_root.gotoAndStop("mainInterface");
}
}
See Also
Key.getAscii( ), Key.isDown(
); Appendix B, "Latin 1 Character Repertoire and Keycodes", and Section 10.11.4, "keyDown" in Chapter 10, "Events and Event Handlers"
Key.isDown( ) Method | check whether a specific key is currently depressed
|
Availability
Flash 5
Synopsis
Key.isDown(keycode)
Arguments
- keycode
A number representing the keycode of the key to check. May also be
one of the Key constants (e.g.,
Key.UP, Key.BACKSPACE).
Returns
A Boolean indicating whether the key specified by
keycode is pressed
(true) or not pressed (false).
Description
The isDown( ) method tells us whether the key
specified by keycode is currently being
pressed. It offers arbitrary, immediate access to the state of the
keyboard and is best used with systems that require constant
key-based input or that detect the pressing of simultaneous keys.
One important advantage of isDown( ) over
getCode( ) and getAscii( )
is its ability to detect the simultaneous pressing of multiple keys.
By checking for both Key.UP and
Key.RIGHT, for example, we may determine that a
spaceship in a game should be moved diagonally. Depending on the
placement of the specific keys being tested, the maximum number of
keys that can be simultaneously detected may be as low as three.
Example
The isDown( ) method is normally used to create
systems that undergo a constant update with each passing frame. In
the following code, we rotate and thrust a spaceship on any frame
where the appropriate arrow keys are being pressed. Note that if you
need to detect two keys simultaneously, you should use separate
if statements. In this example, the state of the
right arrow key is ignored if the left arrow key is also being
depressed. But regardless, the state of the up arrow key is always
checked in a separate if statement. A working
version of this spaceship example is available from the online Code
Depot:
// Code on a spaceship clip
onClipEvent (enterFrame) {
if (Key.isDown(Key.LEFT)) { // Left arrow
_rotation -= 10;
} else if (Key.isDown(Key.RIGHT)) { // Right arrow
_rotation += 10;
}
if (Key.isDown(Key.UP)) { // Up arrow
thrust += 10;
}
}
See Also
Key.getCode( ); Section 10.11.4, "keyDown" in Chapter 10, "Events and Event Handlers"
Key.isToggled( ) Method | check whether the Caps Lock, Num Lock, or Scroll Lock keys are activated
|
Availability
Flash 5
Synopsis
Key.isToggled(keycode)
Arguments
- keycode
An integer keycode, usually the keycode of the Caps Lock key (20),
Num Lock key (144), or Scroll Lock key (145). May also be the key
constant Key.CapsLock.
Returns
A Boolean indicating whether the key specified by
keycode is on (true) or
off (false).
Description
The isToggled( ) method detects the state of the
special Caps Lock, Num Lock, or
Scroll Lock keys. Unlike other
keys, these keys have an "on" state and an
"off" state indicating whether or not the feature they
represent is active. The return of isToggled( )
tells us if the key's feature is in effect or not. (Though
isToggled( ) actually works for any keycode, its
return value is useful only for special keys that support a toggle
feature. To detect the state of other keys, use isDown(
), getCode( ), or getAscii(
).)
_leveln
Global Property | a document level in the Player
|
Availability
Flash 3 and later
Synopsis
_level0
_level1
_level2
...
_leveln
Access
Read-only
Description
Multiple .swf files may be loaded into the Flash
Player for simultaneous display. Each loaded
.swf resides on its own level in the document
level stack. (A .swf file on a higher level
number will obscure lower levels if they occupy the same portion of
the Stage.) The _leveln
property stores a reference to the main timeline of a
.swf loaded into a document level in the Player.
Each document level is represented by a numbered property, such as
_level0, _level1,
_level2, and so on.
The original document loaded into any Flash Player is considered
_level0.
Example
A _leveln reference is
normally used to control movies on other levels of the document
stack. For example, here we play the movie on level 2:
_level2.play( );
We can also use _leveln in
combination with movie clip references to control clips contained by
a movie on any level in the document stack. For example:
_level1.orderForm.titleBar.play( );
A _leveln reference may also
be used as the value of the target
argument of several functions, including loadMovie(
), unloadMovie( ),
loadVariables( ) and print(
). If the level does not yet exist, you should specify the
level reference within quotes. If used without quotes, a nonexistent
level is considered undefined and may cause the
command to operate on the current timeline instead of the new,
undefined level. For example, when executed from the main timeline of
_level0, the following will replace the movie in
_level0 if _level1 has not yet
been defined:
loadMovie("myMovie.swf", _level1);
The following is a safer approach if you can't guarantee that
the level already exists:
loadMovie("myMovie.swf", "_level1"); // Works even if _level1 doesn't exist
Of course, from other levels, you may wish to refer to the original
level, using _level0, such as:
startDrag(_level0, true);
See Also
loadMovie( ), unloadMovie(
), -root; Section 13.3.4, "Importing External Movies" and Section 13.4, "Movie and Instance Stacking Order"
in Chapter 13, "Movie Clips"
loadMovie( ) Global Function | load an external .swf file into the Player
|
Availability
Flash 4 and later. The loadMovie( ) function in
Flash 5 corresponds to the Flash 4 Load Movie
with a target path.
Synopsis
loadMovie(URL, target)
loadMovie(URL, target, method)
Arguments
- URL
A string specifying the absolute or relative file path to the
external .swf file to load. All URLs must use
forward slashes, and absolute URLs must include either the
http:// or file|/// protocol
reference.
- target
A string indicating the movie clip or document level that will host
the external .swf file. May also be a reference
to an existing movie clip or document level (references are converted
to paths when used in a string context).
- method
An optional string indicating the method by which to send variables
to an external script. The legal values for
method are "GET" and
"POST". This parameter must be
a literal, not a variable or other expression. The standalone version
of the Flash Player always uses the "GET" method
regardless of the method specified.
Description
The loadMovie( ) function imports the
.swf file located at
URL into the Flash Player.
If target is a reference to an existing
movie clip or a string indicating the path to a movie clip, the
loaded .swf file is placed into the specified
clip (causing the eviction of any previous content). To load a movie
into the current movie clip, use the empty
string as the target parameter, as in:
loadMovie("myMovie.swf", "")
If target is a reference to an existing
document level (such as _level2) or a string
indicating the path to a document level (such as
"_level2"), then the .swf is
placed into the specified document level. Loading a movie into
_level0 clears the Player of all content and
places the new .swf file into
_level0.
It is possible to send variables along with a loadMovie(
) invocation, in which case URL
is normally the location of a script that returns a
.swf file based on the variables sent. To send
variables with a loadMovie( ) call, we include
the method argument (set to either
"GET" or "POST").
"GET" sends the current movie clip timeline
variables as a query string attached to the script
URL. "POST" sends the
current movie clip timeline variables after the HTTP POST-request
header. The "POST" method is not available in the
standalone Flash Player. Because most web servers restrict the length
of URLs to between 255 and 1024 characters, use
"POST" instead of "GET" to
transfer larger amounts of data.
Over a web server, loadMovie( ) invocations that
use the "GET" method can pass variables to a
loaded movie without the help of an intervening script. Here, we load
the external movie myMovie.swf into level 1 of
the Player document stack, passing it the variables from the current
timeline:
loadMovie("myMovie.swf", "_level1", "GET");
Variables passed to the loaded movie are defined on that
movie's main timeline. This technique works only when the
loadMovie( ) request is handled by a web server.
Attempts to use the "GET" method with
loadMovie( ) using local files will cause an
"Error opening URL" error.
Usage
Be careful when using movie clip and level references as the
target argument of loadMovie(
). If a loadMovie( ) 's
target argument yields
undefined, the loadMovie( )
function uses the current timeline as its
target. Similarly,
target references that yield the empty
string cause loadMovie( ) to operate on the
current timeline. In particular, this causes problems for loading
movies onto new, unoccupied levels. Consider the following code:
loadMovie("myMovie.swf", _level1);
If no _level1 object exists prior to the execution
of that statement, that code will load
myMovie.swf into the timeline that contains the
loadMovie( ) statement, not
_level1! To avoid the problem, you can use
loadMovieNum( ) instead. Alternatively, you can
use a string for the target parameter to
loadMovie( ), as in:
loadMovie("myMovie.swf", "_level1");
In that case, the level will be created if it doesn't already
exist (only _level0 exists by default in all
movies). For more information, see Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips".
Example
loadMovie("myMovie.swf", "_level1"); // Place myMovie.swf on level 1
loadMovie("myMovie.swf", "_level0"); // Place myMovie.swf on level 0
loadMovie("myMovie.swf", "myClip"); // Place myMovie.swf into myClip
// Replace the contents of the Player with
// coolmovie.swf, using an absolute path
loadMovie("http://www.yourflashsite.com/coolmovie.swf", "_level0");
// Load a movie into level 1 from the Windows desktop. Note the
// file:/// protocol and the forward slashes.
loadMovie("file:///C|/WINDOWS/Desktop/animation.swf", "_level1");
See Also
loadMovieNum( ), MovieClip.loadMovie(
), unloadMovie( ); Section 13.3.4, "Importing External Movies" in Chapter 13, "Movie Clips"
loadMovieNum( ) Global Function | load an external .swf file into a document level
|
Availability
Flash 3; enhanced in Flash 4 to include the
method parameter; available in Flash 5.
The loadMovieNum( ) function corresponds with
Flash 3's Load Movie, which accepted only
level numbers.
Synopsis
loadMovieNum(URL, level)
loadMovieNum(URL, level, method)
Arguments
- URL
A string specifying the absolute or relative file path of the
external .swf file to load.
- level
A non-negative integer, or an expression that yields one, indicating
the document level that will host the external
.swf file.
- method
An optional string indicating the method by which to send variables
to an external script. The legal values for
method are "GET" and
"POST". This parameter must be a literal, not a
variable or other expression. The standalone version of the Flash
Player always uses the "GET" method regardless of
the method specified.
Description
The loadMovieNum( ) function is nearly identical
to loadMovie( ) except that it requires the
target level of the load operation to be
specified as a number rather than as a string. This means that
loadMovieNum( ) can load movies only into
document levels, not host clips. If the specified level doesn't
exist, it will be created. If the specified level does exist, its
occupant is replaced by the new .swf file. It is
valid to load a movie into _level2 even if
_level1 hasn't been created.
The loadMovieNum( ) function can be used when we
wish to dynamically assign the level of a loaded movie, as in:
var x = 3;
loadMovieNum("myMovie.swf", x);
which could also be achieved via a string concatenation expression
with the regular loadMovie( ) function:
loadMovie("myMovie.swf", "_level" + x);
See Also
loadMovie( ), MovieClip.loadMovie(
)
loadVariables( ) Global Function | retrieve an external set of variables
|
Availability
Flash 4 and later
Synopsis
loadVariables(URL, target)
loadVariables(URL, target, method)
Arguments
- URL
A string specifying the path to a variable source -- either a
server-side script that returns variables or a text file containing
variables.
- target
A string indicating the path to the movie clip or document level on
which the loaded variables will be defined. May also be a reference
to a movie clip or document level (references are converted to paths
when used in a string context).
- method
An optional string indicating the method by which to send variables
to an external script. If specified, the variables from the current
timeline are sent to the script and target
receives the loaded variables. If omitted, variables are retrieved
but none are sent. The legal values for
method are "GET" and
"POST". This parameter must be a literal, not a
variable or other expression. The standalone version of the Flash
Player always uses the "GET" method regardless of
the method specified.
Description
Normally, we define variables inside our movies using ActionScript.
However, using loadVariables( ), we may also
import variables into a movie from a text file or a server-side
application such as a Perl script. Variables loaded via
loadVariables( ) are scoped to the movie clip or
level specified by target and are always
of the string datatype. To attach loaded
variables to the current timeline, use the empty string as the value
of the target argument. For example:
loadVariables("myVars.txt", ""); // Loads the variables from myVars.txt onto
// the current timeline
Whether the variables to be loaded reside in a text file or are
composed by a script, they must be formatted according to the rules
of URL encoding, as follows:
Any character that is not a space, a number (1-9), or an unaccented
Latin 1 letter (a-z, A-Z) should be replaced by a hexadecimal escape
sequence of the form %xx, where
xx is the hex Latin 1 code point of the character.
For example, the following code shows the contents of a text file to
be imported into Flash via loadVariables( ). The
imported variables are name and
address, which have the values
"stephen" and "65 nowhere st!",
respectively:
name=stephen&address=65+nowhere+st%21
A text file for use with loadVariables( ) is
simply a regular text file containing URL-encoded variables, as shown
previously. To load variables from an external text file, we specify
the path of the file as the URL argument
in our loadVariables( ) function invocation. For
example:
// Load the variables from myVariables.txt into the main movie timeline
loadVariables("myVariables.txt", "_root");
loadVariables( ) may also be used with a script
or server application that outputs URL-encoded variables. When a
script sends data to a Flash movie in response to a
loadVariables( ) function, the script should set
the MIME type of the data as:
"application/x-www-urlform-encoded". Here's
a typical MIME-setting statement from a Perl script:
print "Content-type: application/x-www-urlform-encoded\n\n";
Though the name
loadVariables( ) suggests only a single
direction of variable transmission, it may also be used to
send variables to a server-side script. To send
all the variables defined on the current timeline to a script, we set
the method argument of a
loadVariables( ) function invocation to either
"GET" or "POST". Variables are
sent in URL-encoded format. If method is
set to "GET", the variables are sent as a query
string of the script URL. If
method is set to
"POST", the variables are sent after the HTTP
POST-request header. The "POST" method is not
available in the standalone Flash Player. Because most web servers
restrict the length of URLs to between 255 and 1024 characters, use
"POST" instead of "GET" to
transfer larger amounts of data.
For security reasons, loadVariables(
) works only with hosts in the domain from
which the movie was downloaded. The rules that govern
loadVariables( ) usage are listed in Table 20-8. These security measures affect the Flash
Player browser plugins and ActiveX controls only; variables may be
loaded from any domain in the standalone Player.
Table 20-8. Domain-Based loadVariables( ) Security Restrictions
Domain of Movie Origin |
Host to Connect to |
Permitted? |
www.somewhere.com |
www.somewhere.com |
Yes |
www.somewhere.com |
other.somewhere.com |
Yes |
www.somewhere.com |
www.somewhere-else.com |
No |
www.somewhere.com |
somewhere.com |
Yes |
somewhere.com |
www.somewhere.com |
Yes |
Domain restriction is an intentional security feature of Flash, but
it can be circumvented with either a proxy script running on siteX
that acts as a go-between for Flash and siteY, or a DNS alias on
siteX that points to siteY. For more information, see:
http://www.macromedia.com/support/flash/ts/documents/loadvars_security.htm
Usage
The results of multiple loadVariable( ) calls to
the same script URL may be cached on some browsers to the point that
new data is never loaded from the server. To avoid this problem,
append a dummy variable to each loadVariables( )
call so that the URL is unique. For example, here we generate a
unique URL by appending the time in milliseconds:
loadVariables("http://www.mysite.com/cgi-bin/myScript.pl?cacheKiller="
+ getTimer( ), serverResponse);
Bugs
The POST method is not supported by Internet Explorer 4.5 on
Macintosh. This problem was fixed in Version 5 of the browser.
See Also
loadVariablesNum( ) ,
MovieClip.loadVariables( ); Chapter 17, "Flash Forms"
loadVariablesNum( ) Global Function | attach an external set of variables to a document level
|
Availability
Flash 5. Use the Load Variables Action in Flash
4 to place variables on a document level.
Synopsis
loadVariablesNum(URL, level)
loadVariablesNum(URL, level, method)
Arguments
- URL
A string specifying the path to a variable source -- either a
server-side script that returns variables or a text file containing
variables.
- level
A non-negative integer, or an expression that yields one, indicating
the document level on which the loaded variables will be defined.
- method
An optional string indicating the method by which to send variables
to an external script. If specified, the variables from the current
timeline are sent to the script, and level
receives the loaded variables. If omitted, variables are retrieved
but none are loaded. The legal values for
method are "GET" and
"POST". This parameter must be a literal, not a
variable or other expression. The standalone version of the Flash
Player always uses the "GET" method regardless of
the method specified.
Description
The loadVariablesNum( ) function is nearly
identical to loadVariables( ) except that it
requires the target level to be specified
as a number rather than as a string. This means that
loadVariablesNum( ) can attach variables to
document levels only, not movie clips. The target
level can be specified dynamically, as in:
var myLevel = 2;
loadVariablesNum("myVars.txt", myLevel);
A similar effect could be achieved using string concatenation with
the regular loadVariables( ) function:
loadVariables("myVars.txt", "_level" + myLevel);
See Also
loadVariables( )
Math
Object | access to mathematical functions and constants
|
Availability
Flash 5
Synopsis
Math.propertyName
Math.methodName()
Properties
- E
The constant e, the base of natural logarithms,
approximately 2.71828.
- LN10
The natural logarithm of 10 (loge10),
approximately 2.30259.
- LN2
The natural logarithm of 2 (loge2),
approximately 0.69315.
- LOG10E
The base-10 logarithm of e, approximately
0.43429.
- LOG2E
The base-2 logarithm of e, approximately
1.44270. See bug noted in detailed listing.
- PI
The ratio of a circle's circumference to its diameter,
approximately 3.14159.
- SQRT1_2
The reciprocal of the square root of 2, approximately 0.70711.
- SQRT2
Square root of 2, approximately 1.41421.
Methods
- abs( )
Compute the absolute value of a number.
- acos( )
Compute the arc cosine of a number.
- asin( )
Compute the arc sine of a number.
- atan( )
Compute the arc tangent of a number.
- atan2( )
Compute the angle of a point, relative to the x-axis.
- ceil( )
Round a number up to the next integer.
- cos( )
Compute the cosine of an angle.
- exp( )
Raise e to a specified power.
- floor( )
Return the closest integer less than or equal to the input.
- log( )
Compute the natural logarithm of a number.
- max( )
Determine the larger of two numbers.
- min( )
Determine the smaller of two numbers.
- pow( )
Raise a number to a specified power.
- random( )
Retrieve a random floating-point number between 0 and 1.
- round( )
Calculate the closest integer to a number.
- sin( )
Compute the sine of an angle.
- sqrt( )
Compute the square root of a number.
- tan( )
Compute the tangent of an angle.
Description
The Math object provides access to built-in
mathematical functions (accessed through methods) and constant values
(accessed through properties). These functions and constants are used
to perform potentially complex calculations with relative ease.
Note that the properties and methods of the Math
object may be used in movies exported to the Flash 4 format, in which
case Flash will approximate the calculations. The resulting values
are reasonable approximations but not necessarily identical to the
native Flash 5 functions. The Flash 4 values are sufficiently
accurate for "close-enough" applications such as graphics
display but are not accurate enough for critical financial or
engineering calculations.
Note that the trigonometric functions require angles to be measured
in radians whereas Flash's
MovieClip._rotation property
is measured in degrees. There are 2 radians in a circle (1
radian is approximately 57.3 degrees). To convert from radians to
degrees, use the formula:
degrees = (radians / Math.PI) * 180;
To convert from degrees to radians, use the formula:
radians = (degrees / 180) * Math.PI;
See Also
Math.atan2( ), Math.cos( );
Section 4.1, "The Number Type" in Chapter 4, "Primitive Datatypes"
Math.abs( ) Method | compute the absolute value of a number
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.abs(x)
Arguments
- x
A positive or negative number.
Returns
The absolute value of x (a positive number
of magnitude x).
Description
The abs( ) method calculates the distance
between x and
(also known as the absolute value of
x). It leaves positive numbers unchanged
and converts negative numbers into positive numbers of the same
magnitude. It is useful for calculating the difference between two
numbers without regard to which is larger than the other. For
example, it is useful when calculating the distance between two
points because distances are always positive.
Example
Math.abs(-5); // Returns 5
// Calculate the difference between two numbers
function diff (num1, num2) {
return Math.abs(num1-num2);
}
diff(-5, 5); // Returns 10
Math.acos( ) Method | compute the arc cosine of a number
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.acos(x)
Arguments
- x
A number between -1.0 and 1.0 (the cosine of an angle).
Returns
The angle, in radians, whose cosine is x .
If x is not in the range -1.0 to 1.0,
returns NaN.
Description
The arc cosine function (sometimes written as
cos-1) is the inverse of the cosine
function. It returns the angle whose cosine has the specified value,
in radians. The return value is in the range
to (i.e.,
to 3.14159...).
Example
trace (Math.acos(1.0)); // Displays: 0
trace (Math.acos(0.0)); // Displays: 1.5707... (i.e., pi/2)
See Also
Math.asin( ), Math.atan( ),
Math.cos( )
Math.asin( ) Method | compute the arc sine of a number
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.asin(x)
Arguments
- x
A number between -1.0 and 1.0 (the sine of an angle).
Returns
The angle, in radians, whose sine is x .
If x is not in the range -1.0 to 1.0,
returns NaN.
Description
The arc sine function (sometimes written as
sin-1) is the inverse of the sine
function. It returns the angle whose sine has the specified value, in
radians. The return value is in the range -/2 to /2
radians.
Example
trace (Math.asin(1.0)); // Displays: 1.5707... (i.e., pi/2)
trace (Math.asin(0.0)); // Displays: 0
See Also
Math.acos, Math.atan,
Math.sin
Math.atan( ) Method | compute the arc tangent of a number
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.atan(x)
Arguments
- x
A number between -Infinity and
Infinity, inclusive (the tangent of some angle).
Returns
The angle, in radians, whose tangent is x .
Description
The arc tan function (sometimes written as
tan-1) is the inverse of the tangent
function. It returns the angle whose tangent has the specified value,
in radians. The return value is in the range -/2 to /2.
Example
trace (Math.atan(1.0)); // Displays: 0.78539...
trace (Math.atan(0.0)); // Displays: 0
trace (Math.atan(-Infinity)); // Displays: -1.5707... (i.e., -pi/2)
See Also
Math.acos( ), Math.asin( ),
Math.tan( )
Math.atan2( ) Method | determine an angle based on a point
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.atan2(y, x)
Arguments
- y
The y-coordinate of the point.
- x
The x-coordinate of the point.
Returns
The angle, in radians, of the point (x,
y) from the center of a circle, measured
counterclockwise from the circle's positive horizontal axis
(i.e., the X-axis). Ranges from to -. (Negative values
indicate angles below the X-axis).
Description
The atan2() method, like atan(
), performs an arc tangent calculation but uses x- and
y-coordinates, rather than their ratio, as arguments. That is,
calculating an arc tangent with atan2( ) as:
Math.atan2(9, 3); // Yields 1.24904577239825
is equivalent to calculating the arc tangent with atan(
), using the ratio of 9/3 (or 3), as follows:
Math.atan(3); // Same thing
Usage
Note that the y -coordinate is passed as the
first argument to atan2( ), whereas the
x-coordinate is passed as the second argument.
This is intentional and required. It mirrors the structure of
tangent, which is the ratio of the side opposite an angle (y) divided
by the side adjacent to the angle (x).
Example
The atan2( ) method can be used to make a
movie
clip point toward a moving target. The
following example, available at the online Code Depot, shows code
that rotates the current clip toward the mouse pointer. It can be
used to orient an enemy spaceship toward a player's spaceship:
// Rotate movie clip toward mouse
onClipEvent (load) {
// Convert radians to degrees. There are 2*pi radians per 360 degrees.
function radiansToDegrees(radians) {
return (radians/Math.PI) * 180;
}
}
onClipEvent (enterFrame) {
// Create a point object that stores the x- and y- coordinates of
// this clip relative to its parent's registration point
point = {x:_x, y:_y};
// Convert our local (parent) coordinates to global (Stage) coordinates
_parent.localToGlobal(point);
// Measure the distance between the registration
// point of this clip and the mouse
deltaX = _root._xmouse - point.x;
deltaY = _root._ymouse - point.y;
// Calculate the angle of the line from the registration point
// of this clip to the mouse
rotationRadian = Math.atan2(deltaY, deltaX);
// Convert the radian version of the angle to degrees
rotationAngle = radiansToDegrees(rotationRadian); // See earlier function
// Update the rotation of this clip to point to the mouse
this._rotation = rotationAngle;
}
Math.ceil( ) Method | round a number up to the next integer
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.ceil(x)
Arguments
- x
A number.
Returns
The next integer greater than or equal to
x.
Description
The ceil( ) (i.e., ceiling) method converts a
floating-point number to the first integer greater than or equal to
x.
Example
Math.ceil(1.00001); // Returns 2
Math.ceil(5.5); // Returns 6
Math.ceil(-5.5); // Returns -5
See Also
Math.floor( ), Math.round( )
Math.cos( ) Method | compute the cosine of an angle
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.cos(theta)
Arguments
- theta
An angle, in radians (not degrees), in the range 0 to 2.
Returns
The cosine of theta (the result is in the
range -1.0 to 1.0).
Description
The cos( ) function returns the trigonometric
cosine of an angle. In a right triangle, the cosine of an angle is
the result of dividing the length of the side adjacent to the angle
by the triangle's hypotenuse.
Usage
Note that cos( ) expects angles to be provided
in radians, not degrees.
Example
trace (cos(0)); // Displays: 1.0
trace (cos(Math.PI)); // Displays: -1.0
The cos( ) function can be used along with
sin( ) to calculate a point on a circle, which
we use in the following example to move a movie clip in a circular
path. Given the radius of a circle, r, and an
angle, , measured counterclockwise from the positive horizontal
axis, a point's location is (r*cos, r*sin):
// CODE ON FRAME 1
var radius = 100; // Radius of circle path
var centerX = 275; // Horizontal center of circle path
var centerY = 200; // Vertical center of circle path
var rotAngleDeg = 0; // Angle of object in degrees, measured
// counterclockwise from the horizon (x-axis)
var rotAngRad; // Radian version of rotAngleDeg
// Convert degrees to radians. There are 2*pi radians per 360 degrees.
function degreesToRadians(degrees) {
return (degrees/180) * Math.PI;
}
// CODE ON FRAME 2
// Increase the rotation angle by 5 degrees
rotAngleDeg += 5;
// Place the object. Note that Flash inverts the Y-axis of Cartesian coordinates
// so we decrement y to obtain our new location
rotAngRad= degreesToRadians(rotAngleDeg);
ball._x = centerX + Math.cos(rotAngRad) * radius;
ball._y = centerY - Math.sin(rotAngRad) * radius;
// CODE ON FRAME 3
// Go back to frame 2 where we move the ball again
gotoAndPlay(2);
See Also
Math.acos( ), Math.sin( ),
Math.tan( )
Math.exp( ) Method | raise the constant e to a specified power
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.exp(x)
Arguments
- x
The exponent to which to raise Math.E.
Returns
Math.E to the power x .
Math.floor( ) Method | round a number to down to the previous integer
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.floor(x)
Arguments
- x
A number.
Returns
The closest integer less than or equal to
x.
Description
The floor method converts a floating-point
number to the first integer less than or equal to x
.
Example
Math.floor(1.99999); // Returns 1
Math.floor(5.5); // Returns 5
Math.floor(-5.5); // Returns -6
function minutesToHHMM (minutes) {
var hours = Math.floor(minutes/60);
minutes -= hours * 60;
minutes = minutes < 10 ? "0" + minutes : minutes;
return hours + ":" + minutes;
}
See Also
Math.ceil( ), Math.round( )
Math.LN10 Property | natural logarithm of 10 (loge10), approximately 2.30259
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.LN10
Description
The LN10 property represents the natural logarithm
of 10 (the base-e logarithm of 10), a constant
equaling approximately 2.30259.
Math.LN2 Property | natural logarithm of 2 (loge2), approximately 0.69315
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.LN2
Description
The LN2 property represents the natural logarithm
of 2 (the base-e logarithm of 2), a constant
equaling approximately 0.69315
Math.log( ) Method | compute the natural logarithm of a number
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.log(x)
Arguments
- x
A positive integer.
Returns
The natural logarithm of x .
Description
The log( ) method calculates the natural
logarithm (i.e., the base-e logarithm) of a
number. See the following example to calculate the base-10 logarithm.
Example
trace (Math.log(Math.E)); // Displays: 1
// Compute the base-10 logarithm of a number
function log10 (x) {
return (Math.log(x) / Math.log(10));
}
Math.LOG10E Property | base-10 logarithm of e, approximately 0.43429
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.LOG10E
Description
The LOG10E property represents the common
logarithm of e (the base-10 logarithm of
e), a constant equaling approximately 0.43429.
Math.LOG2E Property | base-2 logarithm of e, approximately 1.44270
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.LOG2E
Description
The LOG2E property represents the base-2 logarithm
of e
(log2e), a constant
equaling approximately 1.44270.
Bugs
In Flash 5r30, LOG2E erroneously returns the value
of LN2 (0.69315).
Math.max( ) Method | determine the larger of two numbers
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.max(x, y)
Arguments
- x
A number.
- y
A number.
Returns
The larger of x and
y.
Example
Math.max(5, 1); // Returns 5
Math.max(-6, -5); // Returns -5
This example constrains a value to the specified range:
function constrainToRange (checkVal, minVal, maxVal) {
return Math.min(Math.max(checkVal, minVal), maxVal);
}
// Constrain the slider to the stage area
mySlider._x = constainToRange (mySlider._x, 0, 550);
This example returns the maximum value in an array:
function maxInArray (checkArray) {
maxVal = -Number.MAX_VALUE; // Initialize maxVal to a very small number
for (var i = 0; i < checkArray.length; i++) {
maxVal = Math.max(checkArray[i], maxVal);
}
return maxVal;
}
trace(maxInArray([2,3,66,4,342,-90,0])); // Displays: 342
See Also
Math.min( )
Math.min( ) Method | determine the smaller of two numbers
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.min(x, y)
Arguments
- x
A number.
- y
A number.
Returns
The smaller of x and
y.
Example
Math.min(5, 1); // Returns 1
Math.min(-6, -5); // Returns -6
Reader Exercise: Modify the example under Math.max(
) to return the minimum value in an array rather than the
maximum.
See Also
Math.max( )
Math.PI Property | the ratio of a circle's circumference to its diameter, approximately 3.14159
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.PI
Description
The PI property represents the constant , the
ratio of the circumference of a circle to its diameter.
Example
Math.PI is most famously used in calculating the
area of a circle:
function circleArea (radius) {
// PI times the radius squared could also be
// written as Math.PI * Math.pow(radius, 2)
return Math.PI * (radius * radius);
}
Math.pow( ) Method | raise a number to a specified power
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.pow(base, exponent)
Arguments
- base
A number representing the base of the exponential expression.
- exponent
A number representing the power (i.e., exponent) to which to raise
base.
Returns
The base raised to the power
exponent.
Description
The pow( ) method can be used to raise any
number to any power. If exponent is
negative, pow( ) returns 1 /
(baseabs(exponent)).
If exponent is a fraction, pow(
) can be used to take, say, the square root or cube root
of a number (in which case it returns the positive root, although,
mathematically, there may also be a negative root).
Example
Math.pow(5, 2); // Returns 25 (5 squared)
Math.pow(5, 3); // Returns 125 (5 cubed)
Math.pow(5, -2); // Returns 0.04 (1 divided by 25)
Math.pow(8, 1/3); // Returns 2 (cube root of 8)
Math.pow(9, 1/2); // Returns 3 (square root of 9)
Math.pow(10, 6); // Returns 1000000 (can also be written as 1e6)
Bugs
Build 30 of the Flash 5 Player did not correctly calculate
Math.pow( ) for negative values of
base. For example, Math.pow(-2,
2) was calculated as NaN whereas it
should be 4.
See Also
Math.exp( ), Math.sqrt( ),
Math.SQRT2, Math.SQRT1_2
Math.random( ) Method | generate a random number from 0 to 1.0
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.random()
Returns
A floating-point number greater than or equal to 0.0 and less than
1.0.
Description
The random( ) method provides a way to produce
random numbers, which can be used to choose randomly between actions
in a script. The random( ) method generates a
random value between 0
and .99999... inclusive, which we can scale according to our needs.
For example, to obtain a random number between 0
and 5, we use:
Math.floor(Math.random( ) * 6)
And to obtain a random number between 1 and 6, we use:
Math.floor(Math.random( ) * 6) + 1
This custom function returns an integer number in a specified range
rather than a floating-point number in the range 0
to 1:
// Returns a number in the range minVal to maxVal, inclusive
function myRandom (minVal, maxVal) {
return minVal + Math.floor(Math.random( ) * (maxVal + 1 - minVal));
}
// Invoke the function
dieRoll = myRandom(1, 6); // Emulates a six-sided die
trace(dieRoll);
// Note that to simulate two dice, you can use this:
twoDice = myRandom(2, 12); // The minimum value is 2, not 1
// To return the die values separately, use an array
function rollTwoDice ( ) {
return [myRandom(1, 6), myRandom(1, 6)];
}
Due to a bug in Build 30 of the Flash 5 Player, this approach is
prone to an extremely rare, but potentially important inaccuracy. In
Build 30, random( ) generates values in the
range 0.0 to 1.0, inclusive. When we multiply the return of
random( ) by an integer, n,
we produce values in the range 0.0 to n. In our
example, we multiplied Math.random( ) by 6, so
that the returned value ranges from 0.0 to 6.0. By invoking
floor( ) on the adjusted value, we produce
integers in the range
to n (0 to 6 in our example). This leads to an
inaccurate distribution of random numbers -- the chance of
producing n is much smaller than the chance of
producing any other number in the series.
The following version of the myRandom( )
function avoids the problem by simply discarding the value 1.0 if it
happens to be chosen by Math.random( ):
// Returns an integer in the range minVal to maxVal, inclusive
function myRandom (minVal, maxVal) {
do {
r = Math.random( ); // Keep picking a number until it is not 1.
} while (r == 1);
return minVal + Math.floor(r * (maxVal + 1 - minVal));
}
// Invoke the function
dieRoll = myRandom(1, 6); // Emulates a six-sided die safely in Build 30
// of the Flash 5 Player
Usage
Math.random( ) replaces the deprecated Flash 4
random function.
Example
Math.random( ) is often used to cause the
playhead to jump to a random frame in the timeline. The following
code invokes the myRandom( ) function from the
preceding example and then sends the playhead to the randomly chosen
frame:
// Invoke the function; pick a random number between 10 and 20
var destinationFrame = myRandom(10, 20);
// Now send the playhead to that frame
gotoAndStop(destinationFrame);
Math.round( ) Method | calculate the closest integer to a number
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.round(x)
Arguments
- x
A number.
Returns
The integer mathematically closest to x
(or x itself, if
x is an integer). If the fractional
component of x is exactly 0.5
(x is equidistant from the two closest
integers), round( ) returns the first integer
greater than x.
Description
The round( ) method performs traditional
rounding; it converts a floating-point number to the nearest integer.
Positive numbers with a fractional portion less
than 0.5 and negative numbers with a fractional portion
greater than 0.5 are rounded
down. Positive numbers with a fractional portion
greater than or equal to 0.5 and negative
numbers with a fractional portion less than or
equal to 0.5 are rounded up.
Example
Math.round(1.4); // Returns 1
Math.round(1.5); // Returns 2
Math.round(1.6); // Returns 2
Math.round(-5.4); // Returns -5
Math.round(-5.5); // Returns -5
Math.round(-5.6); // Returns -6
See Also
int( ), Math.ceil( ),
Math.floor( )
Math.sin( ) Method | compute the sine of an angle
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.sin(theta)
Arguments
- theta
An angle, in radians (not degrees), in the range 0 to 2.
Returns
The sine of theta (the result is in the
range -1.0 to 1.0).
Description
The sin( ) method returns
the trigonometric sine of an angle. In a right triangle, the sine of
an angle is the result of dividing the length of the side opposite
the angle by the triangle's hypotenuse.
Usage
Note that sin( ) expects angles to be provided
in radians, not degrees.
Example
trace (Math.sin(0)); // Displays: 0
trace (Math.sin(Math.PI/2)); // Displays: 1.0
The sin( ) function can be used along with
cos( ) to calculate a point on a circle. See the
example under Math.cos( ).
See Also
Math.asin( ), Math.cos( ),
Math.tan( )
Math.sqrt( ) Method | calculate the square root of a number
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.sqrt(x)
Arguments
- x
A non-negative integer.
Returns
The square root of x, or
NaN if x is less than
0.
Description
The sqrt( ) method returns the positive root of
its operand (even though there may also be a mathematically valid
negative root). It is equivalent to:
Math.pow(x, 0.5)
Example
Math.sqrt(4); // Returns 2, although -2 is also a valid root
Math.sqrt(36); // Returns 6, although -6 is also a valid root
Math.sqrt(-20); // Returns NaN
See Also
Math.pow( ), Math.SQRT2,
Math.SQRT1_2
Math.SQRT1_2 Property | the reciprocal of the square root of 2, approximately 0.70711
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.SQRT1_2
Description
The SQRT1_2 property is a constant approximating
the value 1/Math.SQRT2 (the reciprocal of the
square root of 2), equaling approximately 0.70711.
See Also
Math.SQRT2
Math.SQRT2 Property | the square root of 2, approximately 1.41421
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.SQRT2
Description
The SQRT2 property is a constant approximating the
square root of 2, an irrational number, equaling approximately
1.41421.
See Also
Math.SQRT1_2
Math.tan( ) Method | compute the tangent of an angle
|
Availability
Flash 5; may be used when exporting Flash 4 movies
Synopsis
Math.tan(theta)
Arguments
- theta
An angle, in radians (not degrees), in the range -/2 to /2.
Returns
The tangent of theta (the result is in the
range -Infinity to Infinity).
Description
The tan( ) method returns the trigonometric
tangent of an angle. In a right triangle, the tangent of an angle is
the result of dividing the length of the side opposite the angle by
the length of the side adjacent to the angle. This is also the same
as the ratio Math.sin(theta)/Math.cos(theta), so
as cos(theta) approaches zero,
tan(theta) approaches
Infinity. Therefore,
tan(theta) is not calculable for the values
-/2, /2, -3/2, 3/2, etc.
Example
trace (Math.tan(0)); // Displays: 0
trace (Math.tan(Math.PI/4)); // Displays: 1
See Also
Math.atan( ), Math.cos( ),
Math.sin( )
maxscroll Property | the last legal top line of a text field
|
Availability
Flash 4 and later
Synopsis
textField.maxscroll
Returns
A positive integer representing the line number of the last legal top
line of a text field.
Description
The maxscroll property tells us the largest
allowed scroll value for a text field. It
represents the number of the last line in a text field that may be
used as the top line in its viewable region.
The maxscroll property can be used with the
scroll property to manage a scrolling-text field.
See Also
scroll; Section 18.4.2, "The maxscroll Property" in
Chapter 18, "On-Screen Text Fields"
Mouse.hide( ) Method | make the mouse pointer disappear
|
Availability
Flash 5
Synopsis
Mouse.hide()
Description
The hide( ) method causes the normal mouse
pointer (usually an arrow) to disappear when the mouse is over any
part of the Player. The normal system pointer reappears when the
mouse passes outside the Flash Player's active stage area.
Usage
Note that in Flash 5, even after Mouse.hide( )
has been invoked, the normal system text I-beam cursor will appear
when the mouse hovers over a text field.
Example
The hide( ) method is used to conceal the
default system mouse pointer, typically in order to replace it with a
custom pointer. In Flash, a custom pointer is nothing more than a
movie clip that follows the mouse. Using the
mouseMove event, we can cause a movie clip to
follow the mouse by updating the clip's _x
and _ y properties with each passing frame. The
following code demonstrates the technique:
// Code on the clip that acts as the custom pointer
onClipEvent (load) {
Mouse.hide( );
}
onClipEvent (mouseMove) {
_x = _root._xmouse;
_y = _root._ymouse;
updateAfterEvent( );
}
It may also be desirable to hide the custom pointer when the mouse is
inactive, say, because the pointer has left the Flash Player's
active stage area, in which case the system pointer appears and there
are two pointers on screen. The following code shows how to adapt the
previous code to hide the cursor after 5 seconds of inactivity:
onClipEvent (load) {
Mouse.hide( );
}
onClipEvent (enterFrame) {
if (getTimer( ) - lastMove > 5000) {
_visible = false;
} else {
_visible = true;
}
}
onClipEvent (mouseMove) {
_x = _root._xmouse;
_y = _root._ymouse;
lastMove = getTimer( );
updateAfterEvent( );
}
To change a custom pointer to a custom "hand" icon when
the mouse hovers over a button, use the button's
rollOver event to set the custom pointer clip to
a frame containing the custom hand, and use the
rollOut event to set the custom pointer back to
the default, as follows:
on (rollOver) {
_root.customPointer.gotoAndStop("hand");
}
on (rollOut) {
_root.customPointer.gotoAndStop("default");
}
In all cases, remember to place the custom pointer on the top layer
of your movie so it appears above all other content. Alternatively,
use duplicateMovieClip( ) or
attachMovie( ) to dynamically generate the
custom pointer clip and assign it a very high depth.
See Also
Mouse.show( ),
MovieClip._xmouse,
MovieClip._ymouse
Mouse.show( ) Method | make the mouse pointer appear
|
Availability
Flash 5
Synopsis
Mouse.show()
Description
The show( ) method causes the default system
mouse pointer to reappear after Mouse.hide( )
has been invoked. It can be used to provide a normal pointer at
necessary times in a movie, such as when the user is expected to fill
in a form. This is one way to handle the unfortunate appearance of
the text I-beam when the system pointer is hidden.
See Also
Mouse.hide( )
MovieClip "Class" | class-like datatype for main movies and movie clips
|
Availability
Flash 3 and later
Constructor
None. Movie clip symbols are created manually in the Flash authoring
tool. Movie clip instances can be created with attachMovie(
) and duplicateMovieClip().
Properties
Movie clip properties provide
descriptions of, and control over, various physical features of movie
clips and main movies. Properties are accessed using the dot
operator, as with any object. See Section 13.1, "The "Objectness" of Movie Clips"
in Chapter 13, "Movie Clips", for details on using movie clip
properties.
Two property-related issues to note:
Table 20-9 lists the movie clip properties. Note
that all built-in movie clip properties begin with an
underscore. This make them easy to
distinguish from custom properties that you can add to your movie
clip and which by convention should not begin with an underscore. In
the Access column of Table 20-9,
R/W indicates
that a property's value may be both retrieved and set (i.e.,
read/write), and RO indicates that it can be
retrieved but not set (i.e., read-only). Some
read-only properties can sometimes be set indirectly through the
authoring tool or via some related function (e.g.,
gotoAndStop( ) sets the
_currentframe property), but only read/write
properties can be set directly via ActionScript. The
Type column describes the datatype of each
property's value. The Property Description
column gives a quick summary of the property's purpose, but the
full descriptions that follow later provide important details. With
the exception of the _name and
_parent properties, the properties in Table 20-9 apply to both movie clip instances and the
main movie (i.e., _root). However, a
property's value may differ markedly depending on whether it is
checked from a movie clip instance or the main movie and may also
differ depending on where the clip is attached. For example, a movie
clip's _x property differs depending on
whether it is attached to the main timeline or as a child of a parent
clip. Furthermore, all properties of the current timeline may be
accessed without an explicit reference to it, as in
_alpha versus myClip._alpha.
Table 20-9. Movie Clip Property Summary
Property Name |
Access |
Type |
Property Description |
_alpha |
R/W |
number |
Opacity percentage: 0 is transparent; 100 is opaque |
_currentframe |
RO |
number |
Frame number at which playhead resides |
_droptarget |
RO |
string |
Target path of the clip over which a dragged clip hovers or has been
dropped, in slash notation |
_framesloaded |
RO |
number |
Number of frames that have been downloaded |
_height |
R/W |
number |
Height, in pixels, of the current contents |
_name* |
R/W |
string |
Identifier of an instance as a string (not a reference) |
_ parent* |
RO |
MovieClip reference |
A reference to the instance or movie that contains the current
instance |
_rotation |
R/W |
number |
Degrees of rotation |
_target |
RO |
string |
Target path in absolute terms, in slash notation |
_totalframes |
RO |
number |
Number of frames in the timeline |
_url |
RO |
string |
Disk or network location of the source .swf file |
_visible |
R/W |
boolean |
Visibility: true if shown;
false if hidden |
_width |
R/W |
number |
Width, in pixels, of the current contents |
_x |
R/W |
number |
Horizontal position, in pixels |
_xmouse |
RO |
number |
Horizontal location of mouse pointer, in pixels |
_xscale |
R/W |
number |
Horizontal scaling percentage |
_y |
R/W |
number |
Vertical position, in pixels |
_ ymouse |
RO |
number |
Vertical location of mouse pointer, in pixels |
_ yscale |
R/W |
number |
Vertical scaling percentage |
*Applies to movie clip instances; does not apply to the main timeline.
Methods
Movie clip methods may be invoked on any
movie clip instance and, in most cases, on any main movie timeline.
Many of the movie clip methods provide the same functionality as
analogous global functions but simply use the convenient
MovieClip.method( ) dot syntax format.
Those that do not correspond to a global function may be applied to
the current clip without an explicit reference to it, as in
attachMovie( ) versus myClip.attachMovie(
). Table 20-10 lists the movie clip
methods.
Table 20-10. Movie Clip Method Summary
Method Name |
Method Description |
attachMovie( ) |
Creates a new instance based on an exported symbol from the current
document's Library. Places the new instance in the host clip or
the movie's programmatically generated clip stack. |
duplicateMovieClip(
)* |
Creates a copy of the current instance and places the copy in the
appropriate programmatically generated clip stack (see Section 13.4.2.2, "How clips generated via duplicateMovieClip( ) are added to the stack" in Chapter 13, "Movie Clips".) |
getBounds( ) |
Returns an object whose properties give the coordinates of the
bounding box that defines the visual region occupied by the clip. |
getBytesLoaded( ) |
Returns the number of downloaded bytes of an instance or a movie. Not
applicable for use with internal clips. |
getBytesTotal( ) |
Returns the physical byte size of an instance or a main movie. |
getURL( ) |
Loads an external document (usually a web page) into the browser. |
globalToLocal( ) |
Converts the properties of a coordinates object
from Stage coordinates to instance coordinates. Has no effect when
invoked on a main movie object (such as _root),
because the original and target coordinate spaces are identical. |
gotoAndPlay( ) |
Moves the playhead of an instance or movie to a specific frame, and
then plays the instance or movie. |
gotoAndStop( ) |
Moves the playhead of an instance or movie to a specific frame and
then stops the playhead. |
hitTest( ) |
Returns a Boolean indicating whether or not a clip intersects with a
given point or another clip. |
loadMovie( ) |
Brings an external .swf file into the Player. |
loadVariables( ) |
Retrieves external data composed of variable names and values and
converts that data into equivalent ActionScript variables. |
localToGlobal( ) |
Converts the properties of a coordinates object
from an instance's coordinates to main movie coordinates. |
nextFrame( ) |
Moves the playhead of instance or movie ahead one frame and stops it
there. |
play( ) |
Starts the playhead of instance or movie in motion (i.e., plays the
clip). |
prevFrame( ) |
Moves the playhead of instance or movie back one frame and stops it
there. |
removeMovieClip( )* |
Deletes a duplicated or attached instance. |
startDrag( ) |
Causes instance or movie to physically follow the mouse pointer. |
stop( ) |
Halts the playback of instance or movie. |
stopDrag( ) |
Ends any drag operation currently in progress. |
swapDepths( )* |
Alters the position of an instance in an instance stack. |
unloadMovie( ) |
Removes an instance or main movie from a document level or host clip. |
valueOf( ) |
Represents the path to the instance in absolute terms, using dot
notation. |
*Applies to movie clip instances; does not apply to the main timeline.
Events
Movie clip
instances support event
handlers,
which respond automatically to a predefined set of events (e.g.,
mouse or keyboard interaction or movie playback). The supported movie
clip event handlers are listed in Table 20-11. See
Chapter 10, "Events and Event Handlers", for details on each.
Table 20-11. Movie Clip Event Handler Summary
Description
MovieClip is not actually a class in
ActionScript but rather a unique ActionScript datatype used to
represent information about, and allow control of, movies and movie
clips. For most purposes, we treat movie clips and movies as objects;
we may create and access movie clip properties, and we may create and
invoke movie clip methods.
Because MovieClip is not a true class, we do not
use a constructor to create new MovieClip
instances. Instead, we create movie clip symbols in the authoring
tool and place instances on the Stage manually. Some methods,
however, allow us to copy existing clips
(duplicateMovieClip( )), or add new clips to the
Stage programmatically (attachMovie( )).
Not all MovieClip objects are equal; some
MovieClip methods and properties apply only to
movie clip instances, not to main movies (a main movie is the
_root timeline of a .swf
document). In our consideration of the MovieClip
properties and methods, we'll note cases in which functionality
is limited to one type of MovieClip object. Note
that we use the word MovieClip to refer to the
"class" of the objects, and the word
movieclip (lowercase) to refer to the
ActionScript datatype; we use movie clip,
clip, or instance to refer
to a particular movie clip, and we use movie to
refer to the main movie of a .swf file. In the
synopsis for each detailed property and method entry, the
abbreviation mc stands in for the name of
a clip or main movie. For many properties and methods,
mc is optional -- if omitted, the
current timeline is used.
Throughout this MovieClip section, when talking
about coordinates,
we need to refer to the location of movie
clips. We measure the position of a clip in reference to one
representative point, its so-called registration
point , as marked by a crosshair in the
clip's Library symbol.
When a clip resides on the main Stage, we describe its location
relative to the top-left corner of the Stage, which corresponds to
the point (0,0). When a clip resides within another clip, we describe
its location relative to the registration point of the parent clip,
which again corresponds to the point (0,0). The point (0,0) in both
cases is the origin point (or simply origin) of
the coordinate space being used to plot the location of the clip.
We'll see how the localToGlobal( ) and
globalToLocal( ) methods can convert between
these two coordinate spaces.
TIP
Flash's coordinate system inverts the Y-axis of Cartesian
coordinates; that is, y values increase in a downward direction, not
upward. For example, a y-coordinate of 100 indicates a point 100
pixels below the X-axis.
We'll often use the coordinate-related properties and methods
to move a clip, determine where a clip is, or determine whether it
intersects another object or point. The last technique is referred to
as collision
detection because it is often used to determine whether to
change the direction in which a clip is animating, as if it bounced
off another object (see the MovieClip.hitTest( )
method).
Note that ActionScript doesn't have a native datatype to
represent a point (i.e., an x- and y-
coordinate). See MovieClip.globalToLocal( ) for
an explanation of how to create a point object from a generic object.
See Also
For a full consideration of the MovieClip class,
see
Chapter 13, "Movie Clips"
MovieClip._alpha Property | opacity of a clip or movie
|
Availability
Flash 4 and later
Synopsis
mc._alpha
Access
Read/write
Description
The floating-point _alpha property specifies the
opacity (or conversely the transparency) of
mc as a percentage -- 0 is completely
transparent whereas 100 is completely opaque. Setting the
_alpha of mc affects
the visual transparency of all clips nested inside
mc but does not affect their
_alpha properties. That is, if we have a clip,
square, that contains another clip,
circle, and we set
square._alpha to 50, then
circle will be 50% transparent on-screen but will
have an _alpha of 100.
Usage
Note that setting the _alpha of a movie clip
affects the aa property of the object returned by
Color.getTransform( ).
Example
ball._alpha = 60; // Make ball partially transparent
ball._alpha = 0; // Make ball invisible
The following clip event handler makes a clip more transparent as the
mouse moves down on the screen:
onClipEvent(enterFrame) {
_alpha = 100 - (_root._ymouse / 400) * 100;
}
See Also
The Color Class;
MovieClip._visible
MovieClip.attachMovie( ) Method | create a new movie clip instance from an exported Library symbol
|
Availability
Flash 5
Synopsis
mc.attachMovie(symbolIdentifier, newName, depth)
Arguments
- symbolIdentifier
A string specifying the linkage identifier of an exported movie clip
symbol, as set in the Library under Options Linkage.
- newName
A string specifying the new instance name of the clip being created.
The name must adhere to the rules for creating an identifier outlined
under Section 14.5, "Identifiers" in Chapter 14, "Lexical Structure".
- depth
An integer specifying the level on which to place the new clip in the
programmatic clip stack above mc. A depth
of -1 is below 0, 1 is in front of 0, 2 is in front of 1, and so on.
See Section 13.4.2.1, "How clips generated via attachMovie( ) are added to the stack" in Chapter 13, "Movie Clips" for more details. Negative depths are
functional but not officially supported by ActionScript; to ensure
future compatibility, use depths of
0 or greater.
Description
The attachMovie( ) method creates a new instance
called newName based on the exported movie
clip symbol specified by symbolIdentifier.
If mc is the main movie, the new instance
is placed in the top-left corner of the Stage. If
mc is a movie clip instance, the new
instance is placed on mc's
registration point. In either case, the new instance is placed above
mc in a stack of
programmatically-generated clips.
See Also
duplicateMovieClip( ),
MovieClip.duplicateMovieClip( ); Section 13.3.2.3, "Creating instances with attachMovie( )" and Section 13.4.2.1, "How clips generated via attachMovie( ) are added to the stack"
in Chapter 13, "Movie Clips"
MovieClip._currentframe Property | the frame number of the playhead of a clip or movie
|
Availability
Flash 4 and later
Synopsis
mc._currentframe
Access
Read-only
Description
The integer _currentframe property represents the
frame number at which the playhead of mc
currently resides. Note that the first frame is 1, not 0; therefore,
_currentframe ranges from 1 to
mc._totalframes.
Example
// Send a playhead back two frames from its current location
gotoAndStop(_currentframe - 2);
See Also
MovieClip.gotoAndPlay( ),
MovieClip.gotoAndStop( )
MovieClip._droptarget Property | the path to the clip or movie on which a dragged clip was dropped
|
Availability
Flash 4 and later
Synopsis
mc._droptarget
Access
Read-only
Description
If mc is being dragged,
_droptarget stores a string indicating the path to
the clip over which mc hovers (if any). If
mc is not hovering over a clip,
_droptarget stores undefined.
If mc was previously dragged and then
dropped on a clip, _droptarget stores a string
indicating the path to the clip upon which
mc was dropped. The path is provided in
slash notation. A movie clip is considered to be "over"
another clip if the registration point of the dragged clip overlaps
any portion of the target clip.
Example
The _droptarget property is convenient for
creating drag-and-drop interfaces. The following example demonstrates
how to create a simple shopping-basket interface using
_droptarget (when an item clip
is dropped onto the basket clip, the
item is allowed to stay in the
basket; otherwise, the item is
returned to its original location):
// CODE ON FRAME ONE OF item
var origX = _x;
var origY = _y;
function drag( ) {
this.startDrag( );
}
function drop( ) {
stopDrag( );
if (_droptarget != "/basket") {
_x = origX;
_y = origY;
}
}
// CODE ON A BUTTON IN item
on (press) {
drag( );
}
on (release) {
drop( );
}
Note that _droptarget stores a string, not a clip
reference. To convert a _droptarget string to a
movie clip reference, use the technique shown in the example for
eval( ).
See Also
MovieClip.startDrag( ),
MovieClip.stopDrag( )
MovieClip.duplicateMovieClip( ) Method | create a copy of a movie clip
|
Availability
Method form introduced in Flash 5 (global form introduced in Flash 4)
Synopsis
mc.duplicateMovieClip(newName, depth)
Arguments
- newName
A string that will become the instance name of the duplicated clip.
The name must adhere to the rules for creating an identifier outlined
under Section 14.5, "Identifiers" in Chapter 14, "Lexical Structure".
- depth
An integer specifying the level on which to place the new clip in the
programmatically generated clip stack above mc
. A depth of -1 is below 0, 1 is in front of 0, 2 is in
front of 1, and so on. See Section 13.4.2.2, "How clips generated via duplicateMovieClip( ) are added to the stack" in
Chapter 13, "Movie Clips" for more details. Negative depths are
functional but not officially supported by ActionScript; to ensure
future compatibility, use depths of
0 or greater.
Description
The MovieClip.duplicateMovieClip( ) method is an
alternative to the global duplicateMovieClip( )
function. When invoked as a MovieClip method,
duplicateMovieClip( ) takes no
target parameter -- it duplicates
mc. The method syntax is less prone to
user error than its global function counterpart.
For usage instructions, see the global duplicateMovieClip(
) function.
See Also
MovieClip.attachMovie( ),
duplicateMovieClip( )
MovieClip._framesloaded Property | the number of frames of a clip or movie that have downloaded to the Player
|
Availability
Flash 4 and later
Synopsis
mc._framesloaded
Access
Read-only
Description
The integer _framesloaded property indicates how
many frames of mc have been loaded into
the Player (from
to mc._totalframes). It
is normally used to create
preloaders that pause playback
until a sufficient number of frames have downloaded. For a movie
clip, the _framesloaded property always equals
_totalframes (because clips are loaded in their
entirety before playing) unless the instance is
in the process of loading an external .swf file
due to a loadMovie( ) invocation. The
_framesloaded property is, therefore, useful only
with main movies or external .swf files loading
into instances or levels.
Preloader code is traditionally placed directly on the main timeline
of the movie being preloaded. A simple approach is to loop between
frames 1 and 2 until the movie has loaded, at which point we go to
the movie's start frame. For example:
// CODE ON FRAME 1
if (_framesloaded > 0 && _framesloaded == _totalframes) {
gotoAndPlay("beginMovie");
}
// CODE ON FRAME 2
gotoAndPlay(1);
In Flash 5 and later, we may alternatively use the
enterFrame movie clip event handler to build a
more portable preloader. In the movie we wish to preload, at the
frame where we want preloading to start, we invoke the
stop( ) function. Then we place a movie clip
with the following code on that movie's timeline:
onClipEvent (enterFrame) {
loaded = _parent._framesloaded;
if (loaded > 0 && loaded == _parent._totalframes && loading != "done") {
_parent.gotoAndPlay("beginMovie");
loading = "done";
}
}
In the preceding example, the clip tracks its parent's load
progress and starts its parent playing when loading is finished. By
using a movie clip as a preloader, we circumvent the need for a loop
on the preloading movie's timeline. A movie clip preloader
could even be turned into a Smart Clip, providing easier workflow for
less experienced developers.
Notice that in our preloader examples, we checked whether
_framesloaded >
0 in addition to whether
_framesloaded ==
_totalframes. This is necessary because when a
movie is unloaded from a clip, that clip has a
_totalframes of 0. Hence, if
_framesloaded is
(as it might be on a very slow connection), the comparison
_framesloaded ==
_totalframes can return true
even when no frames have yet loaded. Our check prevents the movie
from skipping ahead before the appropriate content has loaded. This
precaution is not necessary with main movie preloaders for
.swf files loaded onto levels, because their
_totalframes property is never zero.
Example
Preloaders often include a horizontal loading bar and a text field
indicating the percentage of a movie that has downloaded. Loading
bars are implemented as clips sized with either the
_width property or the _xscale
property. However, note that a clip scales about its registration
point (proportionately on the right and left sides of the
clip's registration point). Therefore, to size a clip from one
side only, we must place all of the clip's content on one side
of the registration point in the clip's symbol. The following
example shows how to add a loading bar and a status text field to our
earlier clip handler code:
// A Portable Preloader with a Status Bar
onClipEvent (enterFrame) {
// Measure how many frames have loaded
loaded = _parent._framesloaded;
// If all the frames have finished loading...
if (loaded > 0 && loaded == _parent._totalframes && loading != "done") {
// ...play the movie and make a note that we're done loading
_parent.gotoAndPlay("beginMovie");
loading = "done";
}
// Determine the percentage of bytes that have loaded
percentDone = Math.floor((_parent.getBytesLoaded( )
/ _parent.getBytesTotal( )) * 100);
// Display the percentage of loaded bytes in the text field loadStatus
loadStatus = percentDone + "% complete";
// Set the size of our loadBar clip
loadBar._xscale = percentDone;
}
Use the Bandwidth Profiler in Test Movie mode to simulate movie
download for preloader testing.
See Also
MovieClip.getBytesLoaded( ),
MovieClip._totalframes;
Section 10.10.4, "data" in Chapter 10, "Events and Event Handlers",
and Section 19.1.4, "The Bandwidth Profiler" in Chapter 19, "Debugging"
MovieClip.getBounds( ) Method | determine the bounding box of a clip or movie
|
Availability
Flash 5
Synopsis
mc.getBounds(targetCoordinateSpace)
Arguments
- targetCoordinateSpace
A string indicating the path to the movie or clip in which space
mc 's dimensions are measured.
Because a movie clip reference is converted to a path when used in a
string context, targetCoordinateSpace may
also be a movie clip object reference, as in
mc.getBounds(_root) versus
mc.getBounds("_root"). Defaults to
mc if not specified.
Returns
An object whose properties -- xMin,
xMax, yMin,
yMax -- describe the bounding box of the space
occupied by mc. These four properties of
the object respectfully specify the leftmost, rightmost, topmost, and
bottommost pixel coordinates of mc.
Description
The getBounds( ) method returns an anonymous
object with properties that define the rectangular area occupied by
mc (i.e., mc
's bounding box). To retrieve the values
stored in the returned object, we must access that object's
properties as shown in the next example.
The dimensions of the bounding box of a clip may be measured relative
to any other clip or movie. Using the
targetCoordinateSpace argument, we may
pose the question, "If mc resided on
targetCoordinateSpace's canvas, what
area would it occupy?" The answer will be different depending
on whether targetCoordinateSpace is a main
movie or a clip instance; the origin point of the main movie's
coordinate space is the top-left corner of the Stage, but the origin
point of an instance's coordinate space is its registration
point as marked in the clip's Library symbol (shown as a
crosshair).
The getBounds( ) method can be used to perform
basic collision detection between a movie or clip and some other
point (though MovieClip.hitTest( ) serves this
purpose better). It might also be used to identify a rectangular
region in which to place a clip added to a movie with
MovieClip.attachMovie( ).
Example
var clipBounds = this.getBounds( );
var leftX = clipBounds.xMin;
var rightX = clipBounds.xMax;
var topY = clipBounds.yMin;
var bottomY = clipBounds.yMax;
See Also
MovieClip.hitTest( )
MovieClip.getBytesLoaded( ) Method | check the number of bytes that have downloaded to the Player
|
Availability
Flash 5
Synopsis
mc.getBytesLoaded()
Returns
An integer representing the number of bytes of
mc that have finished downloading to the
Player. (Divide by 1024 to convert to kilobytes.)
Description
The getBytesLoaded( ) method tells us the number
of bytes of a movie that have downloaded into the Flash Player.
However, getBytesLoaded( ) measures bytes in
whole-frame chunks only. So if a movie's first frame is 200
bytes in size and its second frame is 3000 bytes in size,
getBytesLoaded( ) will return 200 and 3200 but
never any increment in between. Until all of a
given frame has downloaded, the return value of
getBytesLoaded( ) does not change. The
getBytesLoaded( ) method may, therefore, be
thought of as a "bytes version" of the
_framesloaded property.
Note that internal movie clips are always entirely loaded before they
are displayed, so the return value of getBytesLoaded(
) on an internal movie clip will always be the same as
getBytesTotal( ) (unless the movie clip is
currently loading an external .swf file in
response to loadMovie( )). Therefore,
getBytesLoaded( ) is effective only when used
with a main movie or an external .swf file being
loaded into an instance or level.
Like _framesloaded , getBytesLoaded(
) is normally used to build preloaders. It can be used in
concert with getBytesTotal( ) to create a more
accurate progress bar than is possible with
_framesloaded and _totalframes
(because the byte size of each frame may not be equal -- a movie
with 10 frames is not 30% loaded when three frames are loaded if the
frames differ widely in size).
Example
// CODE ON FRAME 1
if (_framesloaded > 0 && _framesloaded == _totalframes) {
gotoAndPlay("beginMovie");
} else {
// Show the load progress in text fields. Divide by 1024 to convert to KB.
loadProgressOutput = this.getBytesLoaded( )/1024;
loadTotalOutput = this.getBytesTotal( )/1024;
}
// CODE ON FRAME 2
gotoAndPlay(1);
See Also
MovieClip._framesloaded,
MovieClip.getBytesTotal( )
MovieClip.getBytesTotal( ) Method | check the size of a clip or movie, in bytes
|
Availability
Flash 5
Synopsis
mc.getBytesTotal()
Returns
An integer representing the size of mc, in
bytes. Divide by 1024 to convert to kilobytes.
Description
The getBytesTotal( ) method tells us the size,
in bytes, of a clip instance or the main movie. When invoked on the
main movie, getBytesTotal( ) reports the size of
the entire .swf. It is normally used in concert
with getBytesLoaded( ) to produce preloaders for
main movies and .swf files loaded into instances
or levels.
See Also
MovieClip.getBytesLoaded( ),
MovieClip._totalframes
MovieClip.getURL( )
Method | load a document into a browser window
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 2,
enhanced in Flash 4 to include the method
argument)
Synopsis
mc.getURL(URL, window, method)
Arguments
- URL
A string specifying the location of the document to load or external
script to run.
- window
An optional string, specifying the name of the browser window or
frame into which to load the document. May be a custom name or one of
the four presets: "_blank", "_
parent", "_self", or
"_top".
- method
An optional string literal specifying the method by which to send the
variables from mc to an external script.
Must be either the literal "GET" or
"POST"; no other expression is allowed.
Description
The MovieClip.getURL( ) method is an alternative
to the global getURL( ) function. Its method
form is useful only when variables are being sent, in which case
getURL( ) sends the variables from
mc, which does not have to be the current
timeline.
See Also
For general usage instructions, see the global getURL(
) function.
MovieClip.globalToLocal( ) Method | convert a point on the main Stage to clip coordinates
|
Availability
Flash 5
Synopsis
mc.globalToLocal(point)
Arguments
- point
A reference to an object with two properties, x
and y, that describe a point on the main Stage of
the Player (i.e., on _root). Both
x and y may be any
floating-point number.
Description
The globalToLocal( ) method converts the
x and y properties of
point from coordinates on the main Stage
to coordinates in the coordinate space of
mc. Note that globalToLocal(
) does not return a new object, it merely modifies the
existing x and y values of
point.
To use globalToLocal( ), we must first create an
object with x and y properties.
For example:
var myPoint = new Object( );
myPoint.x = 10;
myPoint.y = 20;
The x and y properties of our
object are positions on the horizontal and vertical axes of the main
Stage, relative to its top-left corner. For example, an
x of 10 is 10 pixels to the right of the
Stage's left edge, and a y of 20 is 20
pixels below the Stage's top border. With our object created
and our x and y properties set,
we then pass the object to the globalToLocal( )
method, as in:
myClip.globalToLocal(myPoint);
When globalToLocal( ) is executed, the values of
myPoint's x and
y properties are transformed to represent a point
in the space of myClip, measured from
myClip's registration point. By examining
the new values of our myPoint object's
properties, we answer the question, "Where does the point
(x, y) of the main Stage appear in
myClip ?" For example:
xInClip = myPoint.x;
yInClip = myPoint.y;
Example
The following example calculates the offset from the upper-left
corner of the main Stage to the registration point of the current
clip:
pt = new Object( ); // Create generic object to hold our point
pt.x = 0; // Left border of main Stage
pt.y = 0; // Top border of main Stage
this.globalToLocal(pt); // Convert pt to local coordinates
trace("From the current clip, the top-left corner of the main Stage is at ");
trace("x: " + pt.x + "y: " + pt.y);
See Also
MovieClip.localToGlobal( )
MovieClip.gotoAndPlay( )
Method | jump to a given frame, then play
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 2
and later)
Synopsis
mc.gotoAndPlay(frameNumber)
mc.gotoAndPlay(frameLabel)
Arguments
- frameNumber
A positive integer indicating the number of the frame to which the
playhead of mc should jump before playing.
If frameNumber is less than 1 or greater
than the number of frames in mc 's
timeline, the playhead is sent to either the first or last frame,
respectively.
- frameLabel
A string indicating the label of the frame to which the playhead of
mc should jump before playing. If
frameLabel is not found, the playhead is
sent to the first frame of mc 's
timeline.
Description
The MovieClip.gotoAndPlay( ) method is an
alternative to the global gotoAndPlay( )
function. Use the method form to control remote movie clips or
movies, specified by mc.
For general usage instructions, see the global gotoAndPlay(
) function.
Example
// Send the part1 clip to the label intro, then play part1
part1.gotoAndPlay("intro");
MovieClip.gotoAndStop( )
Method | jump to a given frame, and stop the playhead
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 2
and later)
Synopsis
mc.gotoAndStop(frameNumber)
mc.gotoAndStop(frameLabel)
Arguments
- frameNumber
A positive integer indicating the number of the frame to which the
playhead of mc should jump. If
frameNumber is less than 1 or greater than
the number of frames in mc 's
timeline, the playhead is sent to either the first or last frame,
respectively.
- frameLabel
A string indicating the label of the frame to which the playhead of
mc should jump. If
frameLabel is not found, the playhead is
sent to the first frame of mc 's
timeline.
Description
The MovieClip.gotoAndStop( ) method is an
alternative to the global gotoAndStop( )
function. Use the method form to control remote movie clips or main
movies specified by mc.
For general usage instructions, see the global gotoAndStop(
) function.
Example
// Send the mainMenu clip to frame 6 and stop the playhead there
mainMenu.gotoAndStop(6);
MovieClip._height Property | height of a clip or movie, in pixels
|
Availability
Flash 4; enhanced in Flash 5
Synopsis
mc._height
Access
Read-only in Flash 4; read/write in Flash 5
Description
The floating-point _height property is a
non-negative number specifying the height of
mc, in pixels. If
mc has no content,
_height is 0. The _height
property measures the content of a clip as the distance between the
highest occupied pixel and the lowest occupied pixel, even if there
is empty space between those pixels. An occupied
pixel is a pixel that contains a shape, graphic, button,
movie clip, or other content element. Changes made to a clip's
height in the authoring tool or via _ yscale are
reflected by _height.
We may set the value of _height in order to
vertically resize a movie clip. Attempts to set
_height to a negative value are ignored. Setting a
clip's _height to
does not make it invisible; rather, the clip becomes a one-pixel
horizontal line.
The _height of the main movie (either
_root._height or
_leveln._height)
is not the Stage height as specified under Modify Movie
Dimensions in the authoring tool but rather the height of the
contents of the main movie. There is no explicit Stage height
property; if required, we must provide the Stage height manually as a
variable. For example, if a movie's Stage has a height of 400,
we could add the following variable:
_root.stageHeight = 400;
To make that value available on the timeline of any clip, use:
Object.prototype.stageHeight = 400;
Usage
Note that when we set the height of a movie clip, lines are scaled
proportionally, losing their original point size as set in the Stroke
panel. However, the point size of lines set to Hairline in the Stroke
panel is not scaled when a movie clip is resized. That is, use
hairlines to prevent your strokes from appearing fat or distorted
when a clip is scaled.
Example
ball._height = 20; // Set the height of ball to 20 pixels
ball._height /= 2; // Reduce the height of ball by a factor of 2
See Also
MovieClip._width,
MovieClip._yscale
MovieClip.hitTest( ) Method | check whether a point is in a clip or two clips intersect
|
Availability
Flash 5
Synopsis
mc.hitTest(x, y, shapeFlag)
mc.hitTest(target)
Arguments
- x
The horizontal coordinate of the point to test.
- y
The vertical coordinate of the point to test.
- shapeFlag
An optional Boolean value indicating whether the collision test
should detect against the bounding box of
mc (false) or the
actual pixels of mc
(true). Defaults to false if
not supplied. Note that shapeFlag may be
used only with the x and
y arguments, not the
target argument. It is meaningful only
when mc has an irregular contour or a hole
like a donut; it has no effect if mc is a
solid rectangular object.
- target
A string indicating the path to the movie clip to test for collision
with mc. Because movie clip references are
converted to paths when used in a string context,
target may also be a movie clip object
reference, as in
mc.hitTest(ball) versus
mc.hitTest("ball").
Returns
A Boolean indicating the result of the collision-detection test. The
result is true under any of the following
circumstances:
The result is false under any of the following
circumstances:
The shapeFlag property is
true and the point (x, y) on
the main Stage does not intersect with any occupied pixel of
mc. An occupied pixel is one that contains
a visual element, such as a shape or text.
Description
The hitTest( ) method is used to determine
whether a movie clip or specific point intersects with (i.e.,
"hits") mc.
When checking to see if a point intersects
mc, we provide hitTest(
) with the x and
y coordinates of the point to check
(relative to the main Stage). We may also provide the optional
shapeFlag argument, which indicates
whether the collision test should use the actual pixels of
mc, or just mc
's bounding box (the smallest rectangle that can encompass
every occupied pixel of mc). Checking the
actual pixels of mc allows us to determine
whether the point (x, y) is an occupied pixel
inside the contour of mc, not merely
whether it is any point inside mc 's
bounding box.
When we're checking to see if a movie clip intersects
mc, we provide hitTest(
) with the target argument
specifying the clip to check. Collision detection between
target and mc
always uses the bounding boxes of the clips; hitTest(
) does not support pixel-perfect clip-versus-clip
detection. Manual pixel-perfect collision-detection routines can be
difficult to create and processor-intensive to run. In many
situations -- for example, a simple spaceship
game -- it's common practice to detect against a bounding
circle rather than exact pixels.
Usage
Note that collision is always tested relative to the location of
mc on the main Stage of the Player.
Therefore, when hitTest( ) is used with a single
point, the arguments x and y
should always describe a point using Stage coordinates. See
MovieClip.localToGlobal( ) for information on
converting clip coordinates to Stage coordinates. In clip-versus-clip
detection, the coordinates of clips on different timelines are
automatically converted to global (i.e., Stage) coordinates.
Example
This example shows how to manually detect the intersection of two
circles without using hitTest( ):
// Check the distance between two circular clips on both axes
var deltaX = clip1._x - clip2._x; // Horizontal distance
var deltaY = clip1._y - clip2._y; // Vertical distance
// Store the radius of each circle in a convenient property
var radius1 = clip1._width / 2;
var radius2 = clip2._width / 2;
// If the distance between the circles' centers squared is less
// than or equal to the total length of the two radii squared,
// an intersection occurs.
if ((deltaX * deltaX) + (deltaY * deltaY)
<= (radius1 + radius2) * (radius1 + radius2)) {
trace("intersecting");
} else {
trace("not intersecting");
}
Here we check whether paddle intersects
ball using hitTest( ):
if (paddle.hitTest("ball")) {
trace("The paddle hit the ball.");
}
Here we check whether the mouse pointer is over an occupied pixel
within tractor's contour. Notice that the
coordinates of the pointer are given in relation to
_root (the main Stage). Gaps in a movie clip are
detectable when shapeFlag is
true; for example, if the
tractor uses empty space to represent its windows,
then hitTest( ) will return
false when the pointer is over a window:
if (tractor.hitTest(_root._xmouse, _root._ymouse, true)) {
trace("You're pointing to the tractor.");
}
See Also
MovieClip.getBounds(
), MovieClip.localToGlobal( )
MovieClip.loadMovie( )
Method | load an external .swf file into the Player
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 4)
Synopsis
mc.loadMovie(URL)
mc.loadMovie(URL, method)
Arguments
- URL
A string specifying the location of the external
.swf file to load.
- method
An optional string literal indicating the method by which to send
variables to an external script. Must be either the literal
"GET" or "POST"; no other
expression is allowed.
Description
The MovieClip.loadMovie( ) method is an
alternative to the global loadMovie( ) function.
When invoked as a MovieClip( ) method,
loadMovie( ) takes no
target parameter; it loads the
.swf at URL into
mc. The method syntax is less prone to
user error than its global function counterpart.
For usage instructions, see the global loadMovie(
) function.
See Also
loadMovie( ); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
MovieClip.loadVariables( )
Method | retrieve an external set of variables
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 4
and later)
Synopsis
mc.loadVariables(URL)
mc.loadVariables(URL, method)
Arguments
- URL
A string specifying the path to one of two variable sources: a script
that produces variables as output or a text file containing
variables.
- method
An optional string literal indicating the method by which to send the
variables from mc to an external script.
If specified, variables are both sent and loaded. If omitted,
variables are loaded only. Must be either the literal
"GET" or "POST"; no other
expression is allowed.
Description
The MovieClip.loadVariables( ) method is an
alternative to the global loadVariables( )
function. When invoked as a MovieClip method,
loadVariables( ) takes no
target parameter; it loads the variables
at URL into mc.
The method syntax is less prone to user error than its global
function counterpart.
For usage instructions, see the global loadVariables(
) function.
See Also
loadVariables( ); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
MovieClip.localToGlobal( ) Method | convert a point in a clip to main Stage coordinates
|
Availability
Flash 5
Synopsis
mc.localToGlobal(point)
Arguments
- point
A reference to an object with two properties, x
and y, that describe a point in
mc's coordinate space. Both
x and y may be any
floating-point number.
Description
The localToGlobal( ) method converts the
x and y properties of
point from coordinates given in
mc 's coordinate space to
coordinates on the main Stage of the Player. Note that
localToGlobal( ) does not return a new object,
it merely modifies the existing x and
y values of point.
To use localToGlobal( ), we must first create a
so-called point or
coordinates object with x and
y properties. To do so, we'll simply create
a generic object from the Object class, and add
x and y properties to it:
myPoint = new Object( );
myPoint.x = 10;
myPoint.y = 20;
The x and y properties of our
object are positions on the horizontal and vertical axes of
mc, relative to mc
's registration point (shown as a crosshair in
mc 's Library symbol). For example,
an x of 10 is 10 pixels to the right of
mc 's registration point, and a
y of 20 is 20 pixels below mc
's registration point. With our object created
and our x and y properties set,
we then pass the object to the localToGlobal( )
method, as in:
myClip.localToGlobal(myPoint);
When localToGlobal( ) is executed, the values of
myPoint's x and
y properties are transformed to represent the
corresponding point on the main Stage, measured from the
Stage's upper-left corner. By examining the new values of our
myPoint object's properties, we answer the
question "Where does the point (x, y) of
the movie clip appear on the main Stage?" For example:
mainX = myPoint.x;
mainY = myPoint.y;
Example
The following example determines the location of a clip's
registration point relative to the main Stage:
pt = new Object( );
pt.x = 0; // Horizontal registration point of clip
pt.y = 0; // Vertical registration point of clip
this.localToGlobal(pt); // Convert pt to main Stage coordinates
trace("On the main Stage, the registration point of the current clip is at: ");
trace("x: " + pt.x + "y: " + pt.y);
The localToGlobal( ) method can be used to
convert a point to Stage coordinates for use with the
hitTest( ) method, which expects points to be
supplied in the Stage's coordinate space. It can also be used
to compare points in two different movie clips using a common
coordinate space.
See Also
MovieClip.globalToLocal( ),
MovieClip.hitTest( )
MovieClip._name Property | the identifier of a clip instance, as a string
|
Availability
Flash 4 and later
Synopsis
mc._name
Access
Read/write
Description
The _name property specifies the instance name of
a movie clip instance as a string. Because it initially reflects the
instance name set in the Instance panel during authoring, the
_name property doesn't apply to main movies
(the main movie is most easily referred to by the global property
_root).
Example
We can use _name to determine whether or not to
perform some manipulation of a given clip, as we did when generating
a series of star movie clips in Example 10-2.
The _name property may also be used to reassign
the identifier of a clip. For example:
// Change ball to circle
ball._name = "circle";
// Now control the former ball as circle
circle._x = 500;
See Also
MovieClip._target,
targetPath( ); Section 13.3.3, "Instance Names" in
Chapter 13, "Movie Clips"
MovieClip.nextFrame( ) Method | advance a clip or movie's playhead one frame and stop it
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 2
and later)
Synopsis
mc.nextFrame()
Description
The MovieClip.nextFrame( ) method is an
alternative to the global nextFrame( ) function.
Use the method form to control remote movie clips or main movies
specified by mc.
For general usage instructions, see the global nextFrame(
) function.
Example
// Advance slideshow one frame and stop the playhead
slideshow.nextFrame( );
See Also
MovieClip.prevFrame( ), nextFrame(
)
MovieClip._parent
Property | a reference to the host clip or movie containing this clip
|
Availability
Flash 4 and later
Synopsis
mc._parent
Access
Read-only
Description
The _ parent property stores a reference to the
clip object upon whose timeline mc
resides. Main movies don't support the _ parent
property because they are at the top level (conveniently referred to
as _root). References to _root._
parent return undefined. The
_parent property gives us the powerful ability to
manipulate clips in relation to the current clip.
Bugs
Though it is possible in Flash 5 to reassign the _
parent property to another clip, doing so has little
purpose -- only the reference is changed, not the physical
structure of the clips. This unintentional behavior will likely be
changed in the future.
Example
If mc resides on the main timeline of a
movie, we can play the main timeline from
mc using:
_parent.play( );
We may also set the parent timeline's properties, as in:
_parent._alpha = 50;
The _ parent property may also be used in
succession; that is, we may access the _ parent of
a _ parent, as follows:
_parent._parent.play( ); // Play the clip two clips above the current clip
See Also
_root; Section 13.5.3, "Referring to Nested Instances"
in Chapter 13, "Movie Clips"
MovieClip.play( ) Method | begin the sequential display of frames in a clip or movie
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 2
and later)
Synopsis
mc.play()
Description
The MovieClip.play( ) method is an alternative
to the global play( ) function. Use the method
form to control remote movie clips or main movies specified by
mc.
For general usage instructions, see the global play(
) function.
Example
// Begin playing clip intro
intro.play( );
See Also
MovieClip.stop( ), play( )
MovieClip.prevFrame( ) Method | send a clip or movie's playhead back one frame and stop it
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 2
and later)
Synopsis
mc.prevFrame()
Description
The MovieClip.prevFrame( ) method is an
alternative to the global prevFrame( ) function.
Use the method form to control remote movie clips or main movies
specified by mc.
For general usage instructions, see the global prevFrame(
) function.
Example
// Rewind slideshow one frame and stop it
slideshow.prevFrame( );
See Also
MovieClip.nextFrame( ), prevFrame(
)
MovieClip.removeMovieClip( ) Method | delete a movie clip from the Flash Player
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 4
and later)
Synopsis
mc.removeMovieClip()
Description
The MovieClip.removeMovieClip( ) method is an
alternative to the global removeMovieClip( )
function. When invoked as a MovieClip method,
removeMovieClip( ) takes no
target parameter; it removes
mc. The method syntax is less prone to
user error than its global function counterpart.
For usage instructions, see the global removeMovieClip(
) function.
See Also
duplicateMovieClip( ), MovieClip.attachMovie( ),
MovieClip.duplicateMovieClip( ); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
MovieClip._rotation Property | rotation, in degrees, of a clip or movie
|
Availability
Flash 4 and later
Synopsis
mc._rotation
Access
Read/write
Description
The floating-point _rotation property specifies
the number of degrees mc is rotated from
its original orientation (if mc is a clip,
the original orientation is that of its symbol
in the Library). Both authoring tool and programmatic adjustments are
reflected in _rotation. Numbers in the range
to 180.0 rotate the clip clockwise. Numbers in the range
to -180.0 rotate the clip counter-clockwise. The same effect is
achieved when rotating a clip n degrees or
n-360 degrees (where
n is positive). For example, there is no
difference between rotating a clip +299.4 degrees or -60.6 degrees.
Likewise, when n is negative, there is no
difference between n degrees and
n+360 degrees. For example, rotating a
clip -90 degrees is the same as rotating it +270 degrees.
When _rotation is set to anything outside the
range of -180 to 180, the value is brought into the proper range
according to the following calculation:
x = newRotation % 360;
if (x > 180) {
x -= 360;
} else if (x < -180) {
x += 360;
}
_rotation = x;
Bugs
In the Flash 4 Player, setting the _rotation of a
clip reduces the scale of that clip by a fractional amount. Over many
_rotation settings, a clip will actually shrink
noticeably. To account for this bug, set the
_xscale and _ yscale of the
clip to 100 whenever setting the _rotation.
Example
Placing the following code on a clip causes the clip to rotate 5
degrees clockwise each time a frame is rendered:
onClipEvent (enterFrame) {
_rotation += 5;
}
MovieClip.startDrag( )
Method | make a movie or movie clip follow the mouse
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 4
and later)
Synopsis
mc.startDrag()
mc.startDrag(lockCenter)
mc.startDrag(lockCenter, left, top, right, bottom)
Arguments
- lockCenter
A Boolean indicating whether the registration point of
mc should be centered under the mouse
pointer (true) or dragged relative to its original
location (false).
- left
A number specifying the x-coordinate to the left of which
mc 's registration point may not be
dragged.
- top
A number specifying the y-coordinate above which
mc 's registration point may not be
dragged.
- right
A number specifying the x-coordinate to the right of which
mc 's registration point may not be
dragged.
- bottom
A number specifying the y-coordinate below which
mc 's registration point may not be
dragged.
Description
The MovieClip.startDrag( ) method is an
alternative to the global startDrag( ) function.
When invoked as a MovieClip method,
startDrag( ) takes no
target parameter; it drags
mc. The method syntax is less prone to
user error than its global function counterpart.
For usage instructions, see the global startDrag(
) function.
Bugs
Note that the correct order of the constraining rectangular
coordinates is left, top, right, bottom but that the Flash 5
ActionScript Dictionary lists them in the wrong order under
MovieClip.startDrag( ).
Example
// Button code to drag and drop the current clip or movie
on (press) {
this.startDrag(true);
}
on (release) {
stopDrag( );
}
See Also
MovieClip.stopDrag( ), startDrag(
), stopDrag( ); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
MovieClip.stop( ) Method | pause a clip or movie
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 2
and later)
Synopsis
mc.stop()
Description
The MovieClip.stop( ) method is an alternative
to the global stop( ) function. Use the method
form to control remote movie clips or main movies specified by
mc.
For general usage instructions, see the global stop(
) function.
Example
// Halt the playback of spinner
spinner.stop( );
See Also
MovieClip.play( ), stop( )
MovieClip.stopDrag( ) Method | end a drag operation in progress
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 4
and later)
Synopsis
mc.stopDrag()
Description
The MovieClip.stopDrag( ) method is an
alternative to the global stopDrag( ) function.
However, there is no need to use the method form; stopDrag(
) cancels any drag operation in progress, whether invoked
through a movie clip or as a global function.
See Also
MovieClip.startDrag( ), stopDrag(
)
MovieClip.swapDepths( ) Method | change the graphic layering of an instance in the instance stack
|
Availability
Flash 5
Synopsis
mc.swapDepths(target)
mc.swapDepths(depth)
Arguments
- target
A string indicating the path to the movie clip to be swapped with
mc. Because movie clip references are
converted to paths when used in a string context,
target may also be a movie clip object
reference, as in
mc.swapDepths(window2)
versus
mc.swapDepths("window2").
- depth
An integer specifying a level in
mc's parent's clip stack. A
depth of -1 is below 0, 1 is in front of 0, 2 is in front of 1, and
so on. See Section 13.4, "Movie and Instance Stacking Order" in Chapter 13, "Movie Clips" for more details. Negative depths are
functional, but not officially supported by ActionScript; to ensure
future compatibility, use depths of
0 or greater.
Description
All movie clip instances in a .swf document
reside in a stack that governs the visual layering of instances in
the Player. The stack is structured like a deck of cards; clips in
higher positions in the stack appear in front of clips in lower
positions. The position of an instance in the stack is initialized
when the clip is created (either in the Flash authoring tool or via
attachMovie( ) or duplicateMovieClip(
) ). Using swapDepths( ), we can
change the position of an instance in the stack.
The swapDepths( ) method takes two forms. When
used with a target argument,
swapDepths( ) trades the stack position of
mc and target,
provided that mc and
target share the same parent clip (reside
on the same timeline). When used with a
depth argument, swapDepths(
) places mc in a new position
in mc's parent stack. If that
position is occupied, the previous occupant is moved to
mc's old position. Note that
swapDepths( ) cannot be used to move a clip
outside of the stack maintained by its parent. For information on how
movies and movie clips are stacked in the Player, see Section 13.4, "Movie and Instance Stacking Order" in Chapter 13, "Movie Clips".
Bugs
Note that swapping a duplicated or attached instance with a manually
created instance via the depth argument
can cause redraw problems in the Flash 5 Player. Treat the
depth argument with prudence, and always
test depth-swapping code extensively.
See Also
Section 13.4, "Movie and Instance Stacking Order" in Chapter 13, "Movie Clips"
MovieClip._target Property | the target path of a clip or movie, in slash syntax
|
Availability
Flash 4 and later
Synopsis
mc._target
Access
Read-only
Description
The _target property represents the path to
mc in a Flash 4-style slash notation
string. For example, if a clip, ball, resides on
the main movie timeline, ball's
_target property is "/ball". A
clip, stripe, inside ball would
have a _target of
"/ball/stripe".
To retrieve a string giving the path to a clip in dot notation, use
the targetPath( ) function.
See Also
targetPath( )
MovieClip._totalframes Property | the total number of frames in a clip or movie timeline
|
Availability
Flash 4 and later
Synopsis
mc._totalframes
Access
Read-only
Description
The integer _totalframes property represents the
number of frames in mc's timeline,
where mc is a movie clip or main movie. A
new clip or main movie always has a _totalframes
of 1. But if the contents of a clip are unloaded via
unloadMovie( ), _totalframes
becomes 0. It may also be
momentarily while the current clip is unloaded before a new clip is
loaded during a loadMovie( ) operation over a
slow connection. The _totalframes property is most
often used along with _frameloaded to create
preloaders as shown in the entry for
MovieClip._framesloaded.
See Also
MovieClip._framesloaded
MovieClip.unloadMovie( ) Method | remove a movie or movie clip from the Player
|
Availability
Method form introduced in Flash 5 (global form supported by Flash 3
and later)
Synopsis
mc.unloadMovie()
The MovieClip.unloadMovie() method is an
alternative to the global unloadMovie()
function. When invoked as a MovieClip method,
unloadMovie() takes no
target parameter; it unloads
mc. The method syntax is less prone to
user error than its global function counterpart.
For usage instructions, see the global unloadMovie(
) function.
Example
// Removes a loaded document from level 1
_level1.unloadMovie( );
See Also
MovieClip.loadMovie( ), unloadMovie(
); Section 13.8.3.1, "Method versus global function overlap issues" in Chapter 13, "Movie Clips"
MovieClip._url Property | the network address from which a clip or movie was loaded
|
Availability
Flash 4 and later
Synopsis
mc._url
Access
Read-only
Description
The _url property represents the URL (Uniform
Resource Locator) indicating the Internet or local disk location from
which the content of mc was loaded, as a
string. The _url property is always an absolute
URL, never a relative one. For main movies, _url
is simply the location of the current .swf file.
The _url of all movie clips in a
.swf file is the same as the main movie of that
file unless external .swf files have been loaded
into individual clips via MovieClip.loadMovie(
). The _url of a clip that hosts an
externally loaded .swf file is the location of
the externally loaded file.
The _url property is sometimes used to create
simple security systems that prevent a movie from playing when
displayed in a unwanted location.
Example
The value of _url in a movie loaded from a web
site looks like this:
"http://www.moock.org/gwen/meetgwen.swf"
The value of _url in a movie loaded from a local
PC hard drive looks like this:
"file:///C|/data/flashfiles/movie.swf"
Here we check whether a movie is hosted in the desired location (if
not, we display a frame that contains an error):
if (_url != "http://www.moock.org/gwen/meetgwen.swf") {
trace ("This movie is not running from its intended location.";
gotoAndStop("accessDenied");
}
See Also
MovieClip.loadMovie( )
MovieClip.valueOf( ) Method | the path of a clip or movie, as a string
|
Availability
Flash 5
Synopsis
mc.valueOf()
Returns
A string containing the full path to mc,
using dot syntax. For example:
"_level1.ball"
"_level0"
"_level0.shoppingcart.product1"
Description
The valueOf( ) method returns a string
representing the absolute path to mc using
dot syntax notation. The valueOf( ) method is
automatically invoked whenever a MovieClip
object is used where a string is called for. For example,
trace(mc)
will generate the same result as
trace(mc.valueOf(
)). It is, therefore, rarely necessary to invoke
valueOf( ) explicitly.
See Also
Object.valueOf( ), targetPath(
)
MovieClip._visible Property | whether a clip or movie is shown or hidden
|
Availability
Flash 4 and later
Synopsis
mc._visible
Access
Read/write
Description
The Boolean _visible property indicates whether
mc is currently shown
(true) or hidden (false). We
use _visible as a quick means of hiding a movie
clip or movie from view. Note that hidden clips may still be
controlled via ActionScript and still play, stop, receive events, and
otherwise operate as normal. Hidden clips are simply not displayed on
screen.
The initial value of the _visible property for all
movie clips is true, even for movie clips that are
fully transparent or completely off stage. The
_visible property changes only when deliberately
modified by a script; think of it as a way to programmatically show
and hide clips, not a reflection of all factors such as position and
transparency that can affect a clip's visibility.
Hiding a movie clip using the _visible property is
preferred to setting it to fully transparent or moving it off stage
because the Flash Player does not attempt to draw the graphics in
movie clips with _visible set to
false, thus improving rendering performance.
Example
The following button code hides the current clip when the button is
depressed and reveals it when the button is released:
on (press) {
this._visible = false;
}
on (release) {
this._visible = true;
}
See Also
MovieClip._alpha
MovieClip._
width Property | width of a clip or movie, in pixels
|
Availability
Flash 4; enhanced in Flash 5
Synopsis
mc._width
Access
Read-only in Flash 4; read/write in Flash 5
Description
The floating-point _width
property stores a non-negative number specifying the current width of
mc, in pixels. If
mc has no content,
_width is 0. The _width
property measures the content of a clip or movie as the distance
between the leftmost occupied pixel and the rightmost occupied pixel,
even if there is empty space between those pixels. An
occupied pixel is a pixel that contains a shape,
graphic, button, movie clip, or other content element. Changes made
to a clip's width in the authoring tool or via
_xscale are reflected by
_width.
We may set the value of _width in order to
horizontally resize a movie clip. Attempts to set
_width to a negative value are ignored. Setting a
clip's _width to
does not hide the clip, it turns it into a one-pixel vertical line.
The _width of the main movie (either
_root._width or
_leveln._width)
is not the Stage width as specified under Modify Movie
Dimensions in the authoring tool but rather the width of the contents
of the main movie. There is no explicit Stage width property; if
required, we must provide the Stage width manually as a variable. For
example, if a movie's Stage has a width of 550, we could add
the following variable:
_root.stageWidth = 550;
To make that value available on the timeline of any clip, use:
Object.prototype.stageWidth = 550;
Usage
Note that when we set the width of a movie clip, lines are scaled
proportionally, losing their original point size as set in the Stroke
panel. However, the point size of lines set to Hairline in the Stroke
panel is not scaled when a movie clip is resized. That is, use
hairlines to prevent your strokes from appearing fat or distorted
when a clip is scaled.
Example
ball._width = 20; // Set the width of ball to 20 pixels
ball._width *= 2; // Double the width of ball
See Also
MovieClip._height,
MovieClip._xscale
MovieClip._x Property | horizontal location of a clip or movie, in pixels
|
Availability
Flash 4 and later
Synopsis
mc._x
Access
Read/write
Description
The floating-point _x property
always indicates the horizontal position of
mc's registration point,
but
it is measured relative to one of three possible
coordinate spaces:
If mc resides on the main timeline,
_x is measured relative to the
Stage's left edge. For example, an
_x of 20 would indicate that the registration
point of mc is 20 pixels to the right of
the Stage's left edge; -20 would indicate 20 pixels to the
left.
If mc resides on another movie clip
instance's timeline, _x is measured relative
to the registration point of that parent
instance. For example, an _x of 20 would indicate
that the registration point of mc is 20
pixels to the right of its parent instance's registration
point; -20 would indicate 20 pixels to the left.
If mc is the main movie,
_x is the horizontal offset of the entire
.swf document relative to the Stage's left
edge. For example, an _x of 200 would indicate
that the contents of the Stage are offset 200 pixels to the right of
their author-time position; -200 would indicate 200 pixels to the
left.
The _x property (along with all horizontal
coordinates in Flash) increases to the right and decreases to the
left. Fractional _x values are approximated in
Flash with
antialiasing
(blurring).
If mc is contained by an instance that is
scaled and/or rotated, the coordinate space it inhabits is also
scaled and/or rotated. For example, if
mc's parent is scaled by 200% and
rotated 90 degrees clockwise, _x will increase in
the downward direction rather than to the right, and a single unit of
_x will actually be 2 pixels instead of 1.
Because switching between instance and main movie coordinate spaces
can be cumbersome, the MovieClip object provides
the localToGlobal( ) and
globalToLocal( ) methods for performing
coordinate-space transformations.
Example
Placing the following code on a clip causes it to move 5 pixels to
the right with each passing frame (assuming that its coordinate space
hasn't been altered by transformations to its parent):
onClipEvent (enterFrame) {
_x += 5;
}
Positioning clips via _x and _y
is a fundamental task in visual ActionScript programming. The
following example shows clip event handlers that cause a clip to
follow the mouse at a fixed rate of speed (many other motion samples
may be obtained from the online Code Depot):
// Make a clip follow the mouse
onClipEvent(load) {
this.speed = 10;
// Moves clip toward the point (leaderX, leaderY)
function follow (clip, leaderX, leaderY) {
// Move only if we're not at the destination
if (clip._x != leaderX || clip._y != leaderY) {
// Determine the distance between clip and leader
var deltaX = clip._x - leaderX;
var deltaY = clip._y - leaderY;
var dist = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
// Allocate speed between X and Y axes
var moveX = clip.speed * (deltaX / dist);
var moveY = clip.speed * (deltaY / dist);
// If the clip has enough speed to overshoot the destination,
// just go to the destination. Otherwise move according to
// the clip's speed.
if (clip.speed >= dist) {
clip._x = leaderX;
clip._y = leaderY;
} else {
clip._x -= moveX;
clip._y -= moveY;
}
}
}
}
onClipEvent(enterframe) {
follow(this, _root._xmouse, _root._ymouse);
}
See Also
MovieClip.globalToLocal( ),
MovieClip.localToGlobal( ),
MovieClip._y
MovieClip._xmouse Property | horizontal location of the mouse pointer
|
Availability
Flash 5
Synopsis
mc._xmouse
Access
Read-only
Description
The floating-point _xmouse property indicates the
horizontal location of the mouse pointer's hotspot relative to
the coordinate space of mc. If
mc is a main movie,
_xmouse is measured from the Stage's left
edge. If mc is an instance,
_xmouse is measured from the instance's
registration point. To obtain a consistent _xmouse
coordinate that is always measured relative to the Stage, use
_root._xmouse.
Example
Placing the following code on a clip causes it to mirror the mouse
pointer's horizontal position relative to the Stage (it moves
left and right in a straight line):
onClipEvent (enterFrame) {
_x = _root._xmouse;
}
See Also
MovieClip._ ymouse
MovieClip._xscale Property | width of a clip or movie, as a percentage
|
Availability
Flash 4 and later
Synopsis
mc._xscale
Access
Read/write
Description
The floating-point _xscale property specifies the
width of mc relative to its original
width, expressed as a percentage. If mc is
an instance, its "original width" is the width of the
instance's symbol in the Library. If
mc is a main movie, its "original
width" is the width of the movie at authoring time.
When the current width of mc is the same
as its original width, _xscale is 100. An
_xscale of 200 doubles
mc's width relative to its original
width. An _xscale of 50 halves
mc's width relative to its original
width.
The _xscale property scales a clip about its
registration point (proportionately on the right and left sides of
the clip's registration point). To size a clip from one side
only, place all of the clip's content on one side of the
registration point in the clip's symbol (this is a useful
technique for creating horizontal preloader bars). When a
clip's _xscale is set to a negative value,
the clip is flipped horizontally as if across a vertical mirror
running through its registration point (i.e., it becomes a mirror
image of itself), after which the negative value is treated as a
positive. To flip a clip horizontally without resizing it, set the
clip's _xscale to -100.
Example
// Double the width of ball (the height remains unchanged)
ball._xscale *= 2;
// Create a mirror image of ball
ball._xscale = -100;
See Also
MovieClip._ yscale
MovieClip._y Property | vertical location of a clip or movie, in pixels
|
Availability
Flash 4 and later
Synopsis
mc._y
Access
Read/write
Description
The floating-point _ y property
always indicates the vertical position of mc
's registration point,
but
it is measured relative to one of three possible coordinate spaces.
If mc resides on the main timeline,
_ y is measured relative to the
Stage's top edge. For example, a
_ y of 20 would indicate that the registration
point of mc is 20 pixels below the
Stage's top edge; -20 would indicate 20 pixels above.
If mc resides on another movie clip
instance's timeline, _ y is measured
relative to the registration point of that
parent instance. For example, a _ y of 20 would
indicate that the registration point of mc
is 20 pixels below its parent instance's registration point;
-20 would indicate 20 pixels above.
If mc is the main movie, _
y is the vertical offset of the entire
.swf document relative to the Stage's top
edge. For example, a _ y of 200 would indicate
that the contents of the Stage are offset 200 pixels below their
author-time position; -200 would indicate 200 pixels above.
The _ y property (along with all vertical
coordinates in Flash) increases downward and decreases
upward -- the opposite of the Cartesian coordinate system.
Fractional _ y values are approximated in Flash
with antialiasing (blurring).
If mc is contained by an instance that is
scaled and/or rotated, the coordinate space it inhabits is also
scaled and/or rotated. For example, if
mc's parent is scaled by 200% and
rotated 90 degrees clockwise, _ y will increase
toward the left rather than downward, and a single unit of _
y will actually be 2 pixels instead of 1.
Because switching between instance and main movie coordinate spaces
can be cumbersome, the MovieClip object provides
the localToGlobal( ) and
globalToLocal( ) methods for performing
coordinate-space transformations.
Example
Placing the following code on a clip causes the clip to move down 5
pixels with each passing frame (assuming that its coordinate space
hasn't been altered by transformations to its parent):
onClipEvent (enterFrame) {
_y += 5;
}
See Also
MovieClip.globalToLocal( ),
MovieClip.localToGlobal( ),
MovieClip._x
MovieClip._ymouse Property | vertical location of the mouse pointer
|
Availability
Flash 5
Synopsis
mc._ymouse
Access
Read-only
Description
The floating-point _ ymouse property indicates the
vertical location of the mouse pointer's hotspot relative to
the coordinate space of mc. If
mc is a main movie, _
ymouse is measured from the Stage's top edge. If
mc is an instance, _
ymouse is measured from the instance's registration
point. To obtain a consistent _ ymouse coordinate
that is always measured relative to the Stage, use _root._
ymouse.
Example
Placing the following code on a clip causes it to mirror the mouse
pointer's vertical position relative to the Stage (it moves up
and down in a straight line):
onClipEvent (enterFrame) {
_y = _root._ymouse;
}
See Also
MovieClip._xmouse
MovieClip._
yscale Property | height of a clip or movie, as a percentage
|
Availability
Flash 4 and later
Synopsis
mc._yscale
Access
Read/write
Description
The floating-point _ yscale property specifies the
height of mc relative to its original
height, expressed as a percentage. If mc
is an instance, its "original height" is the height of
the instance's symbol in the Library. If
mc is a main movie, the "original
height" is the height of the movie at authoring time.
When the current height of mc is the same
as its original height, _ yscale is 100. A
_ yscale of 200 doubles
mc's height relative to its original
height. A _ yscale of 50 halves
mc's height relative to its original
height.
The _ yscale property scales a clip about its
registration point (proportionately above and below the clip's
registration point). To size a clip from above or below only, place
all of the clip's content above or below the registration point
in the clip's symbol (this is a useful technique for creating
vertical preloader bars). When a clip's _
yscale is set to a negative value, the clip is flipped
vertically as if across a horizontal mirror running through its
registration point (i.e., it becomes a vertical mirror image of
itself), after which the negative value is treated as a positive. To
flip a clip vertically without resizing it, set the clip's
_ yscale to -100.
Example
// Double the height of ball (the width remains unchanged)
ball._yscale *= 2;
// Flip ball vertically
ball._yscale = -100;
See Also
MovieClip._xscale
NaN Global Property | constant representing invalid numeric data (Not-a-Number)
|
Availability
Flash 5
Synopsis
NaN
Access
Read-only
Description
NaN is a special numeric constant used to
represent invalid numeric data (NaN is an acronym
for "Not-a-Number"). Numeric operations that cannot be
resolved to a legitimate number yield the value
NaN. For example:
Math.sqrt(-1); // An imaginary number that cannot be represented
15 - "coffee cup"; // "coffee cup" cannot be converted to a number.
Note that NaN is still numeric data, even though
it is not a calculable number:
typeof NaN; // Yields "number"
Usage
The value NaN is hardly ever used directly in
source code but rather serves as a way for an operation to return an
error condition. Because NaN does not compare
equal to itself, the only way you can detect it is with the global
function isNaN( ). NaN is
shorthand for Number.NaN.
See Also
isNaN( ), Number.NaN; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
newline Constant | insert a line break
|
Availability
Flash 4 and later
Synopsis
newline
Returns
A newline character.
Description
The constant newline represents a standard line
break character (ASCII 10). It is synonymous with the escape sequence
"\n" and is used to force a line break in a block
of text (usually for display in a text field variable).
Usage
Though newline was a function in Flash 4, it
became a constant in Flash 5 and has a syntax that resembles a
property or variable. Note that parentheses are not used following
newline.
Example
myOutput = "hello" + newline + "world";
See Also
See Section 4.5.2.2, "Escape sequences" in Chapter 4, "Primitive Datatypes"
nextFrame( ) Global Function | advance a movie or movie clip's playhead one frame and stop it
|
Availability
Flash 2 and later
Synopsis
nextFrame()
Description
The nextFrame( ) function moves the playhead of
the current timeline ahead one frame and stops it there. The
"current timeline" is the timeline from which the
nextFrame( ) function is invoked. The
nextFrame( ) function is synonymous with
gotoAndStop(_currentFrame + 1);. If invoked on
the last frame of a timeline, nextFrame( )
simply stops the playhead on that frame unless another scene follows
the current scene, in which case nextFrame( )
moves the playhead to frame 1 of the next scene.
See Also
gotoAndStop( ), MovieClip.nextFrame(
), nextScene( ), prevFrame(
)
nextScene( ) Global Function | advance a movie's playhead to frame 1 of the next scene
|
Availability
Flash 2 and later
Synopsis
nextScene()
Description
The nextScene( ) function moves the main
playhead of a movie to frame 1 of the scene following the current
scene and stops the main movie timeline. The "current
scene" is the scene from which the nextScene(
) function is invoked. It must be invoked on a
scene's main timeline in order to have an effect; that is,
nextScene( ) does not work inside a movie clip
or onClipEvent( ) handler. If invoked from the
last scene in a movie, nextScene( ) sends the
playhead to frame 1 of that scene and halts movie playback.
See Also
nextFrame( ), prevScene( )
Number( ) Global Function | convert a value to the Number datatype
|
Availability
Flash 5
Synopsis
Number(value)
Arguments
- value
An expression containing the value to be converted to a number.
Returns
The result of converting value to a
primitive number.
Description
The Number( ) function converts its argument to
a primitive numeric value and returns that converted value. The
results of converting various types of data to a primitive number are
described in Table 3-1. It's often not
necessary to use the Number( ) function;
ActionScript automatically converts values to the
number type when appropriate.
Be sure not to confuse the global Number( )
function with the Number class constructor. The
former is a function that converts a value to the
number type, whereas the latter is the class
used to wrap a primitive numeric datum in an object that can take
properties and methods.
Usage
Note that the Number( ) function frequently
appears in Flash 4 .fla files that have been
converted to the Flash 5 format. For information on how datatypes are
handled when Flash 4 files are converted to Flash 5, see Section 3.4.4, "Flash 4-to-Flash 5 Datatype Conversion" in Chapter 3, "Data and Datatypes".
See Also
The Number class, parseFloat(
), parseInt( ); Section 3.4.2, "Explicit Type Conversion" in Chapter 3, "Data and Datatypes"
Number Class | wrapper class for primitive numeric data
|
Availability
Flash 5
Constructor
new Number(value)
Arguments
- value
An expression to be resolved and, if necessary, converted to a
numeric value, then wrapped in a Number object.
Class Properties
The following properties are accessed
directly as properties of the Number class,
using
Number.propertyName.
To access them you do not need to instantiate a new
Number object (i.e., there is no need for the
constructor function). Some of these properties, such as
NaN don't even require the
Number.propertyName
notation. You can simply use NaN as shorthand for
Number.NaN
(details for each property follow later).
- MAX_VALUE
The largest representable positive number in ActionScript.
- MIN_VALUE
The smallest representable positive number in ActionScript.
- NaN
Special Not-a-Number value indicating invalid numeric data.
- NEGATIVE_INFINITY
Any number more negative than -MAX_VALUE.
- POSITIVE_INFINITY
Any number larger than MAX_VALUE.
Methods
- toString( )
Convert a number to a string.
Description
The Number class has two purposes:
It gives us access to built-in properties that represent special
numeric values -- MIN_VALUE,
MIN_VALUE, NaN,
NEGATIVE_INFINITY, and
POSITIVE_INFINITY -- that can be used to check
whether numeric data is valid.
Usage
There is no need to create a new Number object
if you simply want to access the numeric properties it defines. In
fact, where applicable, it is easier to use global property
equivalents (NaN, Infinity, and
-Infinity). Frankly, it is rare that you'll
need the Number class properties at all.
On the other hand, the Number class's
toString( ) method is used with an instantiated
Number object. However, the interpreter takes
care of creating a Number object for us whenever
we invoke a method on a primitive numeric value. For example:
x = 102;
x.toString(16); // x is automatically converted to a Number object
// for the sake of this operation.
You might do this in order to, say, use toString(
) to convert between various number systems. Again,
frankly, this is a fairly rare task, so you probably won't be
using the Number class much.
See Also
The Math object; Section 4.1, "The Number Type" in Chapter 4, "Primitive Datatypes"
Number.MAX_VALUE Property | the largest representable positive number in ActionScript
|
Availability
Flash 5
Synopsis
Number.MAX_VALUE
Access
Read-only
Description
The MAX_VALUE property stores the largest
representable positive number in ActionScript
(1.7976931348623157e+308). It is convenient when you'd like to
start with a very large value, as shown in the following example. Any
number greater than MAX_VALUE can't be
represented by ActionScript and is therefore considered to be
POSITIVE_INFINITY.
Example
Here we are looking for a minimum value in an array. We initialize
the minVal variable to
MAX_VALUE, knowing that any subsequent value will
be less than it:
var myArray = [-10, 12, 99]
var minVal = Number.MAX_VALUE
for (thisValue in myArray) {
if (myArray[thisValue] < minVal) {
minVal = myArray[thisValue];
}
}
trace ("The minimum value is " + minVal);
See Also
Number.MIN_VALUE;
Number.POSITIVE_INFINITY; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
Number.MIN_VALUE Property | the smallest representable positive number in ActionScript
|
Availability
Flash 5
Synopsis
Number.MIN_VALUE
Access
Read-only
Description
The MIN_VALUE property stores
the smallest representable positive number in ActionScript, 5e-324
(not to be confused with
-Number.MAX_VALUE,
the most-negative number allowed in ActionScript).
See Also
Number.MAX_VALUE; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
Number.NaN Property | constant representing invalid numeric data (Not-a-Number)
|
Availability
Flash 5
Synopsis
Number.NaN
Access
Read-only
Description
The NaN property stores the special "invalid
number" value of the number datatype. It
is used to represent the result of an illogical mathematical
calculation (e.g., 0/0) or an attempted data
conversion that does not yield a legitimate number.
Number.NaN is normally used in its more convenient
global property form, NaN.
Usage
The value NaN is hardly ever used directly in
source code but rather serves as a way for an operation to return an
error condition. The only way you can detect NaN
is with the global function isNaN( ).
See Also
isNaN( ), NaN; Section 4.3.3, "Special Values of the Number Datatype" in Chapter 4, "Primitive Datatypes"
Number.toString( ) Method | convert a Number to a string
|
Availability
Flash 5
Synopsis
numberObject.toString(radix)
Arguments
- radix
An
integer between 2 and 36 specifying the base of the number system
used to represent numberObject in string
format. This argument is optional; if omitted, it defaults to 10.
Returns
The value of numberObject converted to a
string.
Description
The toString( ) method retrieves the value of a
Number object, converts that value to a string,
and returns that string. We may use the
radix argument to convert numeric values
between different bases (e.g., binary, octal, decimal, and
hexadecimal). The letters A-Z are used to represent digits with the
value 10-35, respectively, although ordinarily only A through F are
used (to represent the hex digits equivalent to 10 through 15).
To use Number.toString( ) with a primitive
numeric value, surround the value with parentheses, as in:
(204).toString(16);
Example
x = new Number(255);
trace(x.toString( )); // Displays: "255" (i.e., decimal)
trace(x.toString(16)); // Displays: "ff" (i.e., hexadecimal)
trace(x.toString(2)); // Displays: "11111111" (i.e., binary)
// Convert a hex literal to decimal
trace((0xFFFFFF).toString(10)); // Displays: "16777215"
See Also
Number ( ), Object.toString(
), parseInt( ); See Section 4.3.1, "Integer Literals" in Chapter 4, "Primitive Datatypes"
Object Class | the basis for all other classes and for generic objects
|
Availability
Flash 5
Constructor
new Object()
Properties
- constructor
A reference to the class constructor function used to create the
object.
- __proto__
A reference to the prototype property of the
object's constructor function.
Methods
- toString( )
Convert the value of the object to a string.
- valueOf( )
Retrieve the primitive value of the object, if one exists.
Description
The Object class is the base class of the
ActionScript object model. Object is used for
two general purposes: (a) as a constructor for creating new, generic
objects, and (b) as a superclass upon which to base new classes. All
classes in ActionScript, whether user-defined or built-in are
descendants of the Object class. All objects of
all classes therefore inherit the properties of
Object (though some classes override those
properties).
To create a generic object of the Object class directly in our code
without using a constructor, we can use an object literal just as we
might use a string literal or an array literal. An object literal is
a series of comma-separated property name/value pairs, enclosed in
curly braces. Here's the general syntax:
{ property1: value1, property2: value2, property3: value3 }
The names of properties in an object literal must be legal
identifiers as described in Chapter 14, "Lexical Structure". The values
may be any valid expression. For example:
// An object literal with two numeric properties
myObject = { x: 30, y: 23 };
// Set the x property value using a complex expression
myOtherObject = { x: Math.floor(Math.random( ) * 50 + 1) };
Because object literals always create generic, anonymous objects,
they are used only when we need object-formatted data temporarily,
such as when, say, invoking Sound.setTransform(
), Color.setTransform( ), or
MovieClip.localToGlobal( ).
See Also
Chapter 12, "Objects and Classes"
Object.constructor Property | a reference to the class constructor function used to create the object
|
Availability
Flash 5
Synopsis
someObject.constructor
Access
Read/write (overwriting an object's
constructor property is not recommended as it
alters the natural structure of class inheritance).
Description
The constructor property stores a reference to the
constructor function that was used to create
someObject. For example, the
constructor property of a
Date object is the Date
constructor function:
now = new Date( );
now.constructor == Date; // Yields true
See Also
Section 12.5.3.3, "The constructor property" in Chapter 12, "Objects and Classes"
Object.toString( ) Method | the value of the object, as a string
|
Availability
Flash 5
Synopsis
someObject.toString()
Returns
An internally defined string that describes or otherwise represents
the object.
Description
The toString( ) method returns a string
description for someObject. By default,
someObject.toString( )
returns the expression:
"[object " + class + "]"
where class is the internally defined name
of the class to which someObject belongs.
The ActionScript interpreter automatically invokes the
toString( ) method whenever
someObject is used in a string context.
For example:
x = new Object( );
trace(x); // Displays: "[object Object]"
Most classes overwrite the default toString( )
method of Object in order to provide more
meaningful information about each member of the class. For example,
the Date.toString( ) method returns the date and
time, and the Array.toString( ) method returns a
comma-separated list of array elements. We may do the same when
constructing our own classes.
Example
This example shows how to provide a custom toString(
) method for the Ball class that we
created in Chapter 12, "Objects and Classes":
// Add a Custom toString() method
// Make the Ball constructor
function Ball (radius, color, xPosition, yPosition) {
this.radius = radius;
this.color = color;
this.xPosition = xPosition;
this.yPosition = yPosition;
}
// Assign a function literal to the Ball class prototype's toString() method
Ball.prototype.toString = function ( ) {
return "A ball with the radius " + this.radius;
};
// Create a new ball object
myBall = new Ball(6, 0x00FF00, 145, 200);
// Now check myBall's string value
trace(myBall); // Displays: "A ball with the radius 6"
See Also
Array.toString( ), Date.toString(
), Number.toString( ),
Object.valueOf( )
Object.valueOf( ) Method | the primitive value of the object
|
Availability
Flash 5
Synopsis
someObject.valueOf()
Returns
The internally defined primitive value of
someObject, if a primitive value is
associated with someObject. If no
primitive value is associated with
someObject, then
someObject itself is returned.
Description
The valueOf( ) method returns the primitive
datum associated with an object, if such an association exists. This
method is mostly commonly used with objects of the
Number, String, and
Boolean classes, which all have associated
primitive data. The MovieClip.valueOf( ) method
returns a string representing the path to the clip.
Note that it's rarely necessary to invoke valueOf(
) explicitly; it is automatically invoked by the
interpreter whenever someObject is used
where a primitive is expected.
See Also
Boolean.valueOf( ), MovieClip.valueOf(
), Number.valueOf( ),
Object.toString( ), String.valueOf(
)
parseFloat( ) Global Function | extract a floating-point number from a string
|
Availability
Flash 5
Synopsis
parseFloat(stringExpression)
Arguments
- stringExpression
The string from which a floating-point number is to be extracted.
Returns
The extracted floating-point number. Or, if extraction was
unsuccessful, the special numeric value NaN.
Description
The parseFloat( ) function converts a string to
a floating-point number (a number with a fractional portion). It
works only with strings that contain a valid string representation of
a floating-point number; otherwise, NaN is
returned. The string must be of the following form:
Trailing characters that cannot be parsed as part of the preceding
numeric form are ignored.
Usage
Because user input data entered into text fields always belongs to
the string datatype, we often use
parseFloat( ) to extract numeric data from
user-entered text. Note that parseFloat( ) can
extract numbers from strings that contain both numbers and
non-numeric characters, whereas Number( )
cannot.
Examples
parseFloat("14.5 apples"); // Yields 14.5
parseFloat(".123"); // Yields 0.123
var x = "15, 4, 23, 9";
parseFloat(x); // Yields 15
See Also
isNaN( ), NaN,
Number( ), parseInt( );
Section 3.4.2, "Explicit Type Conversion" in Chapter 3, "Data and Datatypes";
Section 4.2, "Integers and Floating-Point Numbers" in Chapter 4, "Primitive Datatypes"
parseInt( ) Global Function | extract an integer from a string or convert numbers to base-10.
|
Availability
Flash 5
Synopsis
parseInt(stringExpression)
parseInt(stringExpression, radix)
Arguments
- stringExpression
The string from which an integer is to be extracted.
- radix
An
optional integer, between 2 and 36, specifying the base (or
radix) of the integer to be extracted. If not
specified, the default radix depends on the contents of
stringExpression (as described later).
Returns
The extracted integer value, as a base-10 number regardless of the
original radix. Or, if extraction was
unsuccessful, the special numeric value NaN.
Description
The parseInt( ) function converts a string
expression to an integer. It works only with strings that contain a
valid string representation of an integer using the specified radix.
The string must be of the following form:
Trailing characters that cannot be parsed as part of the preceding
numeric form are ignored.
The number derived from the supplied string starts with the first
nonblank character in the string and ends with the character before
the first character that is not a legitimate digit in the supplied
radix. For example, in the base-10 system,
the letter F is not a valid digit, so the
following expression yields the number 2:
parseInt("2F", 10);
But in the
base-16 system (hexadecimal), the
characters A, B, C, D, E, and
F are valid numerals, so
the following expression yields the number 47:
parseInt("2F", 16); // 2F in hexadecimal is 47 in base-10
The radix argument of parseInt(
) specifies the base of the number as it exists in the
string. In other words, using the radix
argument we may say to the interpreter "Treat this string as a
base-16 number" or "Treat this string as a base-2
number."
parseInt( ) also interprets the prefix
0x to indicate a hexadecimal (a.k.a. hex) number
(as if a radix of 16 was specified) and a
leading
to indicate an octal number (as if a radix
of 8 was specified):
parseInt("0xFF"); // Parsed as hex, yields 255
parseInt("FF", 16); // Parsed as hex, yields 255
parseInt("0377"); // Parsed as octal, yields 255 = (3 * 64) + (7 * 8) + (7 * 1)
parseInt("377", 8); // Parsed as octal, yields 255
An explicit radix overrides any implicit radix:
parseInt ("0xFF", 10) // Parsed as decimal, yields 0
parseInt ("0x15", 10) // Parsed as decimal, yields 0 (not 15, and not 21)
parseInt ("0377", 10) // Parsed as decimal, yields 377
Note that the parseInt( ) function extracts
integer values only, unlike parseFloat( ) which
can also extract fractional values but may be used only with base-10
numbers.
Example
We primarily use parseInt( ) to extract integers
from a string that contains both numbers and text or to remove the
decimal place from a number (similar to Math.floor(
)).
parseInt("Wow, 20 people were there"); // Yields NaN
parseInt("20 people were there"); // Yields 20
parseInt("1001", 2); // Yields 9 (1001 evaluated in binary)
parseInt(1.5); // Yields 1 (the number 1.5 is converted to the string
// "1.5" before the parseInt operation proceeds)
See Also
Math.floor( ), NaN,
parseFloat( ); Section 3.4.2, "Explicit Type Conversion" in
Chapter 3, "Data and Datatypes"; Section 4.2, "Integers and Floating-Point Numbers"
in
Chapter 4, "Primitive Datatypes"
play( ) Global Function | begin the sequential display of frames in a movie
|
Availability
Flash 2 and later
Synopsis
play()
Description
Invoking the play( ) function initiates the
sequential display of the frames in the current main movie or movie
clip. The "current" movie or movie clip is the one that
bears the play( ) function invocation statement.
Frames are displayed at a rate dictated by the frames per second (or
FPS) setting of the entire movie, which is set under the Movie
Properties (Modify Movie Frame Rate).
Once started, the playback of a movie or movie clip continues until
another function invocation specifically stops the playback. All
movie clips loop (begin playing again at frame 1) when the playhead
reaches the end of the timeline. In a browser, however, main movies
loop only if the code used to embed the movie in the HTML page
specifies that the movie should loop, as determined by the
LOOP attribute. (If you're using the Publish
command to embed your movie in an HTML page, set the
LOOP attribute by selecting File Publish
Settings HTML Playback Loop.)
See Also
gotoAndPlay( ), MovieClip.play(
), stop( )
prevFrame( ) Global Function | send a movie's playhead back one frame and stop it
|
Availability
Flash 2 and later
Synopsis
prevFrame()
Description
The prevFrame( ) function moves the playhead of
the current timeline back one frame and stops it there. The
"current timeline" is the timeline from which the
prevFrame( ) function is invoked. The
prevFrame( ) function is synonymous with
gotoAndStop(_currentFrame - 1);. If invoked on
the first frame of a timeline, prevFrame( )
simply stops the playhead on that frame unless another scene precedes
the current scene, in which case prevFrame( )
moves the playhead to the last frame of the previous scene.
See Also
gotoAndStop( ), MovieClip.prevFrame(
), nextFrame( ), prevScene(
)
prevScene( ) Global Function | send a movie's playhead to frame 1 of the previous scene
|
Availability
Flash 2 and later
Synopsis
prevScene()
Description
The prevScene( ) function moves the main
playhead of a movie to frame 1 of the scene before the current scene
and stops the main movie timeline. The "current scene" is
the scene from which the prevScene( ) function
is invoked. It must be invoked on a scene's main timeline in
order to have an effect; that is, prevScene( )
does not work inside a movie clip or onClipEvent(
) handler. If invoked from the first scene in a movie,
prevScene( ) sends the playhead to frame 1 of
that scene and halts movie playback.
See Also
nextScene( ), prevFrame( )
print( ) Global Function | print the frames of a movie or movie clip using vectors
|
Availability
Flash 5
Synopsis
print(target, boundingBox)
Arguments
- target
A string or reference indicating the path to the movie clip or
document level to print (references are converted to paths when used
in a string context).
- boundingBox
A string indicating how the printed frames of
target should be cropped when printed.
Cropping is defined by a bounding box that represents the entire
printed page. The region of target
included in the printed page can be set using one of three legal
values for boundingBox (which must be a
literal string):
- "bframe"
-
The bounding box for each printed frame is set individually to match
the size of each frame's contents. Hence, every printed
frame's content is scaled to fill the entire printed page.
- "bmax"
-
The area occupied by the content of all printed frames is combined to
form a general bounding box. Each printed frame's content is
scaled and placed on the printed page relative to the general
bounding box.
- "bmovie"
-
The bounding box for all printed frames is set to the size of a
single, designated frame in the target
clip. Content of printed frames is cropped to the bounding box of
that designated frame. To designate a frame as the bounding box,
assign it the label #b.
Description
Printing a Flash movie using a web browser's built-in print
function behaves inconsistently and often results in poor quality
printouts. Using the print( ) function, we can
print the contents of a movie with accuracy and quality, directly
from Flash. By default, print( ) causes all of
the frames of target's timeline to
be sent to the printer, one frame per page, cropped according to the
boundingBox argument. To designate only
specific frames for printing, we assign the label
#P to the desired frames.
The print( ) function sends vectors directly to
PostScript printers and vectors converted to bitmaps to
non-PostScript printers. Because print( ) uses
vectors, it cannot be used to print movies with alpha transparency or
color transformations. To print movies that have color effects, use
printAsBitmap( ).
Usage
In Flash 4 r20 and above, the features of the various Flash 5
print( ) functions are available as a modified
getURL( ) Action. For more details, see
Macromedia's Flash Printing SDK, available at:
http://www.macromedia.com/software/flash/open/webprinting/authoring.html
Example
// Print every frame in the main movie timeline,
// sizing each individually to fill the page
print("_root", "bframe");
// Print every frame in the main movie timeline,
// sizing each frame relative to the combined size of all frames
print("_root", "bmax");
When a button with the following code is clicked, Flash prints all
frames in the button's timeline, cropped to the bounding box of
the frame with the label #b and sized to fill the
page:
on (release) {
print(this, "bmovie");
}
See Also
getURL( ), printAsBitmap(
), printAsBitmapNum( ),
printNum( )
printAsBitmap( ) Global Function | print the frames of a movie or movie clip as bitmaps
|
Availability
Flash 5
Synopsis
printAsBitmap(target, boundingBox)
Arguments
- target
A string or reference indicating the path to the movie clip or
document level to print (references are converted to paths when used
in a string context).
- boundingBox
A string indicating how the printed frames of
target should be cropped when printed, as
described earlier under print( ).
Description
The printAsBitmap( ) function is functionally
identical to print( ), except that it outputs
rasterized content to the printer, not vectors. It can, therefore,
successfully print movies with color transformations but produces
poorer quality for vector-based artwork.
Usage
See Usage notes under the print( ) function.
See Also
print( ), printAsBitmapNum(
), printNum( )
printAsBitmapNum( ) Global Function | print the frames of a document level as bitmaps
|
Availability
Flash 5
Synopsis
printAsBitmapNum(level, boundingBox)
Arguments
- level
A non-negative integer or an expression that yields a non-negative
integer, indicating the document level to print.
- boundingBox
A string indicating how the printed frames of
target should be cropped when printed, as
described earlier under print( ).
Description
The printAsBitmapNum( ) function is nearly
identical to printAsBitmap( ) except that it
requires the target level of the print
operation to be specified as a number rather than as a string. This
means that printAsBitmapNum( ) can print only
document levels, not movie clips. It is normally used when we wish to
dynamically assign the level of a movie to print, as in:
var x = 3;
printAsBitmapNum(x, "bmax");
which could also be achieved using string concatenation with the
regular printAsBitmap( ) function:
printAsBitmap("_level" + x, "bmax");
Usage
See Usage notes under the print( ) function.
See Also
print( ), printAsBitmap( ),
printNum( )
printNum( ) Global Function | print the frames of a document level using vectors
|
Availability
Flash 5
Synopsis
printNum(level, boundingBox)
Arguments
- level
A non-negative integer or an expression that yields a non-negative
integer indicating the document level to print.
- boundingBox
A string indicating how the printed frames of
target should be cropped when printed, as
described earlier under print( ).
Description
The printNum( ) function is nearly identical to
print( ) except that it requires the target
level of the print operation to be
specified as a number rather than as a string. This means that
printNum( ) can print only document levels, not
movie clips. It is normally used when we wish to dynamically assign
the level of a movie to print, as in:
var x = 3;
printNum(x, "bmax");
which could also be achieved using string concatenation with the
regular print( ) function:
print("_level" + x, "bmax");
Usage
See Usage notes under the print( ) function.
See Also
print( ), printAsBitmap( ),
printAsBitmapNum( )
_quality Global Property | the rendering quality of the Player
|
Availability
Flash 5
Synopsis
_quality
Access
Read/write
Description
The _quality property stores a string that
dictates the rendering quality of the Flash Player as follows:
- "LOW"
Low quality. Neither bitmaps nor vectors are antialiased (smoothed).
- "MEDIUM"
Medium quality. Vectors are moderately antialiased.
- "HIGH"
High quality. Vectors are highly antialiased. Bitmaps are antialiased
when no animation is occurring.
- "BEST"
Best quality. Both bitmaps and vectors are always antialiased.
Lower rendering quality means that fewer calculations are required to
draw a frame of the movie, resulting in faster performance. The
typical setting of _quality for most movies is
"HIGH".
Example
Here we set the rendering quality of a movie to the best it can be
(which also causes the slowest playback):
_quality = "BEST";
See Also
_highQuality, toggleHighQuality( )
random( ) Global Function | generate a random number
|
Availability
Flash 4; deprecated in Flash 5 in favor of Math.random(
)
Synopsis
random(number)
Arguments
- number
A positive integer.
Returns
A random integer greater than or equal to
0 and less than number.
Description
The deprecated random( ) function was used in
Flash 4 to generate random numbers. This function has been retired
from the language and is available only for the sake of backward
compatibility. In Flash 5 and higher, use the preferred
Math.random( ) method. Note that
random( ) generated integers from
to number -1, whereas Math.random(
) generates floats from 0.0 to .999.
See Also
Math.random( )
removeMovieClip( ) Global Function | delete a movie clip from the Flash Player
|
Availability
Flash 4; enhanced in Flash 5 to apply to instances created with
attachMovie( )
Synopsis
removeMovieClip(target)
Arguments
- target
A string or reference indicating the path to the movie clip instance
to be removed from the Player (references to movie clips are
converted to paths when used in a string context).
Description
The removeMovieClip( ) function deletes the
specified movie clip from the Player, leaving no trace of the
clip's contents or shell. Subsequent references to the clip or
any of its variables or properties yield
undefined.
The removeMovieClip( ) function may be used only
on movie clip instances that were originally created via
duplicateMovieClip( ) or attachMovie(
). It has no effect on movie clips created in the
authoring tool.
See Also
attachMovie( ), duplicateMovieClip(
), MovieClip( ).removeMovieClip( );
Section 13.6, "Removing Clip Instances and Main Movies" in Chapter 13, "Movie Clips"
_root Global
Property | a reference to the main timeline of the movie in the current level
|
Availability
Flash 5 (same as "/" in Flash 4 movies)
Synopsis
_root
Access
Read-only
Description
The _root property stores a reference to the main
timeline of the current document level. We use
_root to invoke methods on the main movie or to
retrieve and set the main movie's properties. For example:
_root.play( ); // Play the main timeline
_root._alpha = 40; // Make the whole movie partially transparent
The _root property may also be used to refer to
nested clips. For example:
_root.myClip.play( );
_root.shapes.square._visible = false;
The _root property provides access to a movie clip
in absolute terms. That is, a reference that starts with
_root is valid (and invariant) from anywhere in a
movie.
See Also
_leveln; _ parent;
Section 13.5.4, "Referring to Main Movies with _root and _leveln" in Chapter 13, "Movie Clips" and Section 2.5.6, "Accessing Variables on Different Timelines" in
Chapter 2, "Variables"
scroll Property | the current top line displayed in a text field
|
Availability
Flash 4 and later
Synopsis
textfield.scroll
Returns
A positive integer representing the number of the topmost viewable
line of a text field.
Description
The scroll text field property can be both
retrieved and set. When we retrieve the value of a text field's
scroll property, it indicates the number of the
line currently displayed as the first line in the field's
viewable region. When we set the value of scroll,
it scrolls the text field, making the supplied line number the top
line in the field's viewable region. The
scroll property is normally used with
maxscroll to create text-scrolling interfaces as
described under Section 18.4.3, "Typical Text-Scrolling Code" in Chapter 18, "On-Screen Text Fields".
Usage
Though scroll is listed as a function in Flash, it
is effectively used as a property of a text field variable. Notice
that parentheses are not used when scroll is
invoked.
Bugs
In Build 5.0 r30 of the Flash Player, when a text field's font
is embedded, using scroll may cause some text to
be displayed outside the visual region of the field. Some text may
not be removed as the text in the field scrolls. To work around the
problem, use a mask over the text field layer. This problem was fixed
in Build 5.0 r41.
Example
// Sets x to the index of the top line displayed in myField
var x = myField.scroll;
// Scrolls the text in myField down one
myField.scroll++;
See Also
maxscroll; Section 18.4.1, "The scroll Property" in
Chapter 18, "On-Screen Text Fields"
Selection Object | control over text field selections
|
Availability
Flash 5
Synopsis
Selection.methodName()
Methods
-
getBeginIndex( )
Retrieve the index of the first selected character.
- getCaretIndex( )
Retrieve the index of the insertion point.
- getEndIndex( )
Retrieve the index of the last selected character.
- getFocus( )
Identify the text field in which the insertion point currently
resides.
- setFocus( )
Place the insertion point in a specific text field.
- setSelection( )
Select characters in the currently focused text field.
Description
We use the Selection
object to control user interaction with text fields and to capture
portions of text fields. In actual use, the
Selection object methods are preceded by the
keyword Selection; they always operate on the text
field with focus, of which there can be only one at any given time.
The methods of a Selection object can position
the insertion point and can select or retrieve a text field's
content. These abilities add subtle but important behavior to
user-input systems. For example, in a user-login screen, we can
prompt a user to enter his name by placing the cursor in a name-entry
text field. Or we can highlight an error in a form by selecting the
problematic text. We can also customize the so-called Tab
order of a series of text fields, as
shown under Reference 20.205.
Positions of the characters in a text field are referred to with
zero-relative indexes where the first character is index 0, the
second is index 1, and so on. Character indexing is described in
detail in Section 4.6.4, "Character Indexing" in Chapter 4, "Primitive Datatypes".
In Flash 5 it is not possible to cut, copy, or paste text
programmatically. Further, cut, copy, and paste shortcut keys such as
Ctrl-C and Ctrl-V are not functional in the Flash Player. The
secondary mouse button (right-click on Windows, Ctrl-click on
Macintosh) provides access to the cut, copy, and paste commands.
Usage
Clicking a form's submit button automatically removes focus
from any previously focused text field. To capture a selection before
focus is lost, use the button's rollover event. For example:
on (rollOver) {
focusedField = Selection.getFocus();
}
See Also
_focusrect, Selection.setFocus(
); Chapter 18, "On-Screen Text Fields"
Selection.getBeginIndex( ) Method | retrieve the index of a text field's first selected character
|
Availability
Flash 5
Synopsis
Selection.getBeginIndex()
Returns
The index of the first character in the current selection
(highlighted block of text). If no text field has keyboard focus, it
returns -1. If a text field has focus but no characters are selected,
it returns the value of Selection.getCaretIndex(
).
Description
The getBeginIndex( ) method identifies the
beginning of a selection. To determine the span of characters
currently selected, use both getBeginIndex( )
and getEndIndex( ).
Example
The following example creates a string representing the currently
selected characters and then displays that string in the Output
window:
var firstChar = Selection.getBeginIndex( );
var lastChar = Selection.getEndIndex( );
var currentSelection = eval(Selection.getFocus( )).substring(firstChar, lastChar);
trace(currentSelection);
The following code extends the current selection by one character to
the left:
Selection.setSelection(Selection.getBeginIndex() - 1, Selection.getEndIndex( ));
See Also
Selection.getCaretIndex( ),
Selection.getEndIndex( )
Selection.getCaretIndex( ) Method | retrieve the index of the insertion point
|
Availability
Flash 5
Synopsis
Selection.getCaretIndex()
Returns
The index of the insertion point in the current text field. If no
text field has keyboard focus, it returns -1. If the text field with
focus is empty, it returns 0.
Description
The getCaretIndex( ) method indicates the
insertion point (i.e., the location of the cursor) in a text field.
The cursor appears as an I-beam when a text field has keyboard focus.
Use setSelection( ) to set the location of the
insertion point.
Example
Because getCaretIndex( ) returns -1 when no text
field has focus, we may determine whether any field has focus by
checking whether getCaretIndex( ) is equal to
-1, as follows:
if (Selection.getCaretIndex( ) == -1) {
trace("No field has focus");
}
See Also
Selection.setSelection( )
Selection.getEndIndex( ) Method | retrieve the index of the last selected character
|
Availability
Flash 5
Synopsis
Selection.getEndIndex()
Returns
The index of the character after the last character in the current
selection (highlighted block of text). If no text field has focus, it
returns -1. If a text field has focus but no characters are selected,
it returns the value of Selection.getCaretIndex(
).
Description
The getEndIndex( ) method identifies the end of
a selection. To identify the span of characters currently selected,
use both getEndIndex( ) and
getBeginIndex( ).
Example
The following code extends the current selection by one character to
the right:
Selection.setSelection(Selection.getBeginIndex(), Selection.getEndIndex( )+ 1);
See Also
Selection.getBeginIndex( ),
Selection.getCaretIndex( )
Selection.getFocus( ) Method | identify the text field in which the cursor currently resides
|
Availability
Flash 5
Synopsis
Selection.getFocus()
Returns
A string indicating the full path to the
text field variable that has keyboard focus (i.e., the one in which
the cursor currently resides), for example,
"_level1.myTextField". If no text field has
keyboard focus, it returns null.
Description
The getFocus( ) method identifies which text
field currently has focus (if any) by returning its string path. To
turn that string into a variable reference, we use eval(
). For example, in the following code we identify the
number of characters in the text field with focus. We retrieve the
name of the field by invoking getFocus( ), and
we convert that name into a variable with eval(
) :
var numChars = eval(Selection.getFocus( )).length;
Example
Because getFocus( ) returns
null when no text field is selected, we may
determine whether any field has focus by checking whether
getFocus( ) is equal to null,
as follows:
if (Selection.getFocus( ) == null) {
trace("No field has focus");
}
See Also
Selection.setFocus( ), eval(
), Selection.getCaretIndex( )
Selection.setFocus( ) Method | set keyboard focus for a specific text field
|
Availability
Flash 5
Synopsis
Selection.setFocus(variableName)
Arguments
- variableName
A string representing the path (e.g.,
"_root.myTextField" or
"userName") to the text field variable that is to
receive focus.
Returns
A Boolean indicating whether the focus attempt succeeded
(true) or failed (false). A
focus attempt fails only if the variable specified by
variableName is not found or if it is not
a text field variable.
Description
The setFocus( ) method sets the keyboard focus
for a text field. It places the cursor in that text field, normally
in order to draw attention to the field or to allow the user to enter
data. The setFocus( ) method can also provide a
handy means of identifying erroneous input to a user. In an online
form, for example, a user may mistype an email address. To alert the
user to the error, we could set the focus to the email-address text
field and ask her to fix the problem. We can also use
setFocus( ) to create a custom Tab key order for
the fields in a form, as shown in the example that follows.
Usage
Note that setting the focus of a text field automatically selects any
content in that field. To set a field's focus without selecting
any characters, use the following code:
// First, focus myField
Selection.setFocus("myField");
// Now place the insertion point at the start of myField
Selection.setSelection(0, 0);
// Or at the end of myField
Selection.setSelection(myField.length, myField.length);
TIP
When a movie is viewed in a browser, a focused text field will accept
text entry only if the Flash movie itself has focus (that is, the
user has clicked on the movie at some point during movie playback).
Make sure a movie has focus before asking a user to type into one of
its text fields. One way to do this is by including a button that
says "Click Here to Start" at the beginning of your
movie.
Example
This example
shows how to assign a custom Tab order to the fields in a fill-in
form. The corresponding sample .fla file may be
downloaded from the online Code Depot (for more information on
trapping the Tab key, see Section 10.11.4.1, "Handling special keys" in
Chapter 10, "Events and Event Handlers"):
// Custom Tab Order
// CODE ON THE MOVIE CLIP CONTAINING THE FORM FIELDS
onClipEvent (load) {
// Store the path to this clip in a string. We'll use it
// later when invoking Selection.setFocus( ).
path = targetPath(this);
// Create an array with the names of our text fields, supplied
// in the desired Tab order. The first field listed is the default.
tabOrder = ["field1", "field3", "field2", "field4"];
}
onClipEvent (keyUp) {
// If the Tab key was pressed...
if (Key.getCode( ) == Key.TAB) {
// ...If no field has focus...
if (Selection.getFocus( ) == null) {
// ...then set focus to the first field in the array of fields
Selection.setFocus(path + "." + tabOrder[0]);
} else {
// Otherwise, locate the currently focused field in the array of fields
i = 0;
focused = Selection.getFocus( );
while (i < tabOrder.length) {
// Extract the name of the field variable from the full path
// that's returned by Selection.getFocus( )
fieldName = focused.substring(focused.lastIndexOf(".") + 1);
// Check each element of tabOrder for the focused field.
if (tabOrder[i] == fieldName) {
// Stop when we find a match
currentFocus = i;
break;
}
i++;
}
// Now that we know where the focused field lies in the tabOrder array,
// set the new focus to either the next field or the previous field,
// depending on whether the Shift key is down.
if (Key.isDown(Key.SHIFT)) {
// Shift key is down, so go to the previous field, unless we're already
// at the beginning, in which case go to the last field.
nextFocus = currentFocus-1 == -1 ? tabOrder.length-1 : currentFocus-1;
} else {
// Shift key is not down, so go to the next field,
// unless we're already at the end, in which case go to the first field.
nextFocus = currentFocus+1 == tabOrder.length ? 0 : currentFocus+1;
}
// Finally, assign the new focus
Selection.setFocus(path + "." + tabOrder[nextFocus]);
}
}
}
// CODE ON BUTTON ON MAIN TIMELINE
on (keyPress "<Tab>") {
// This placeholder code just traps the Tab key in Internet Explorer
var tabCatcher = 0;
}
See Also
Selection.getFocus(
), Selection.setSelection( )
Selection.setSelection( ) Method | select characters in the text field with focus, or set the insertion point
|
Availability
Flash 5
Synopsis
Selection.setSelection(beginIndex, endIndex)
Arguments
- beginIndex
A non-negative integer specifying the index of the first character to
be included in the new selection.
- endIndex
A non-negative integer specifying the index of the character
after the last character to be included in the
new selection.
Description
The setSelection( ) method selects (highlights)
the characters from beginIndex to
endIndex-1 in the text
field with focus. If no field has focus, setSelection(
) has no effect. It is commonly used to highlight
problematic user input.
Usage
Though the Selection object does not have a
"setCaretIndex" method, we may use
the setSelection( ) method to set the insertion
point to a specific location within a text field. To do so, we
specify the same beginIndex and
endIndex values, as in:
// Set the insertion point after the third character
Selection.setSelection(3, 3);
Example
// Select the second and third letters
// of the currently focused text field
Selection.setSelection(1, 3);
See Also
Selection.getBeginIndex( ),
Selection.getCaretIndex( ),
Selection.getEndIndex( )
setProperty( ) Global Function | assign a value to a movie clip property
|
Availability
Flash 4 and later
Synopsis
setProperty(movieClip, property, value)
Arguments
- movieClip
An expression that yields a string indicating the path to a movie
clip. In Flash 5, this may also be a movie clip reference because
movie clip references are converted to paths when used in a string
context.
- property
The name of the built-in property to which
value will be assigned. Must be an
identifier, not a string (e.g., _alpha, not
"_alpha").
- value
The new data value to be assigned to the specified
property of
movieClip.
Description
The setProperty( ) function assigns
value to one of
movieClip's built-in properties (the
built-in properties are listed under the
MovieClip class ). It
cannot be used to set the value of custom (i.e., user-defined)
properties. In Flash 4, setProperty( ) was the
only means to assign movie clip property values; as of Flash 5, the
. and [] operators are the
preferred means of setting both built-in and custom movie clip
properties.
Example
// Flash 4 syntax. Rotate the main movie by 45 degrees:
setProperty("_root", _rotation, 45);
// Flash 5 syntax. Also rotates the main movie by 45 degrees:
_root._rotation = 45;
See Also
getProperty( ); Section 13.1, "The "Objectness" of Movie Clips" in
Chapter 13, "Movie Clips"; Appendix C, "Backward Compatibility".
Sound
Class | control over sounds in a movie
|
Availability
Flash 5
Constructor
new Sound()
new Sound(target)
Arguments
- target
A string indicating the path to the movie clip or document level
whose sound is to be controlled. May also be a reference to a movie
clip or document level (references are converted to paths when used
in a string context).
Methods
- attachSound( )
Associate a sound from the Library with the
Sound object.
- getPan( )
Retrieve the current pan setting.
- getTransform( )
Determine the current distribution of the channels of a sound to the
left and right speakers (i.e., balance).
- getVolume( )
Retrieve the current volume.
- setPan( )
Set the pan across a sound's left and right channels.
- setTransform( )
Distribute the left and right channels between the left and right
speakers (i.e., balance).
- setVolume( )
Set the sound volume.
- start( )
Start playing an attached sound.
- stop( )
Silence all sounds or a specified attached sound.
Description
Objects of the Sound class are used to control
the existing sounds in a movie or to control sounds added to a movie
programmatically. Sound objects have several
distinct applications. They can control:
To create a Sound object
that controls all the sounds in the Player (including sounds in
.swf files on document levels), use the
Sound constructor without any parameters. For
example:
myGlobalSound = new Sound( );
To create a Sound object that controls all the
sounds in a particular clip or main movie, supply a
target parameter indicating the clip or
movie to control. Note that this also controls sounds in clips inside
target. For example:
spaceshipSound = new Sound("spaceship"); // Control sounds in spaceship clip
mainSound = new Sound("_root"); // Control sounds on main timeline
To make an individual sound that can be started, stopped, and looped
independently, create any kind of Sound object
and then attach a sound to it using the attachSound(
) method.
See Also
stopAllSounds( );
_soundbuftime
Sound.getPan( )
Method | retrieve the last pan value set
|
Availability
Flash 5
Synopsis
soundObject.getPan()
Returns
A number indicating the last value set by setPan(
). Usually in the range -100 (left channel on, right
channel off) to 100 (right channel on, left channel off). Default
value is
(both left and right channels in equal proportions).
Description
By adjusting the pan of a sound, you can create the illusion of a
moving sound source. The getPan( ) method is
used to determine the current distribution of the left and right
channels of the sounds controlled by
soundObject. Normally, getPan(
) is used in combination with setPan(
) to adjust the current pan of a sound.
Example
Here we alter the pan of a sound by 20:
mySound = new Sound( );
mySound.setPan(mySound.getPan( ) - 20);
See Also
Sound.getTransform( ), Sound.setPan( )
Sound.getTransform( ) Method | determine the current distribution of the channels of a sound to the left and right speakers
|
Availability
Flash 5
Synopsis
soundObject.getTransform()
Returns
An anonymous object whose properties contain the channel percentage
values for the sounds controlled by
soundObject.
Description
The getTransform( ) method returns an object
with properties that tell us how the channels in the sounds
controlled by soundObject are distributed
to the left and right speakers. The properties of the returned object
are ll, lr,
rl, and rr, as described in the
entry for the Sound.setTransform( ) method.
See Also
Sound.getPan( ), Sound.setTransform(
)
Sound.getVolume( ) Method | retrieve the current volume setting
|
Availability
Flash 5
Synopsis
soundObject.getVolume()
Returns
A number indicating the current volume as set by setVolume(
). Usually in the range
(no volume) to 100 (default volume), but it can be higher.
Description
The getVolume( ) method is used to determine the
current volume of the sounds controlled by
soundObject. Normally,
getVolume( ) is used in combination with
setVolume( ) to adjust the current volume of a
sound.
Example
Here we reduce the volume of a sound by 20:
mySound = new Sound( );
mySound.setVolume(mySound.getVolume( ) - 20);
See Also
Sound.setVolume( )
Sound.setPan( ) Method | set the balance of a sound's left and right channels
|
Availability
Flash 5
Synopsis
soundObject.setPan(pan)
Arguments
- pan
A number between -100 (left) and 100 (right) indicating the
distribution between the left and right speakers for sounds
controlled by soundObject. If the
pan supplied is greater than 100, the
actual value assigned is 200 -
pan. If the pan
supplied is less than -100, the actual value assigned is
-200 -
pan.
Description
The setPan( ) method dictates the balance of
the right and left channels of the sounds controlled by
soundObject. By adjusting the pan over
time, we can cause a sound to move from one speaker to the other
(known as panning).
To play the sounds controlled by
soundObject in the left speaker only, use
a pan of -100. To play the sounds
controlled by soundObject in the right
speaker only, use a pan of 100. To balance
the two channels evenly, use a pan of 0.
Note that setPan( ) affects all the sounds
controlled by soundObject. If
soundObject is a global sound,
setPan( ) affects all the sounds in a movie. If
soundObject is tied to a clip or a main
timeline, setPan( ) affects all the sounds in
that clip or timeline and all the clips it contains.
The effects of setPan( ) can be changed only by
another call to setPan( ). A setPan(
) assignment affects all future sounds controlled by
soundObject, even if
soundObject is deleted.
Example
The following clip event handlers cause sounds in a movie clip to
endlessly pan between the left and right speakers:
onClipEvent (load) {
panEffect = new Sound(this);
panDirection = "right";
panIncrement = 50;
}
onClipEvent(enterFrame) {
if (panDirection == "right") {
newPan = panEffect.getPan( ) + panIncrement;
if (newPan > 100) {
panDirection = "left";
panEffect.setPan(panEffect.getPan( ) - panIncrement);
} else {
panEffect.setPan(newPan);
}
} else {
newPan = panEffect.getPan( ) - panIncrement;
if (newPan < -100) {
panDirection = "right";
panEffect.setPan(panEffect.getPan( ) + panIncrement);
} else {
panEffect.setPan(newPan);
}
}
}
The following clip event handlers cause sounds in a clip to react to
the mouse. Assuming a Stage width and height of 550 and 400, the
sounds pan left and right with the mouse's horizontal movement
and increase or decrease in volume with the mouse's vertical
movement:
onClipEvent (load) {
// Create a new Sound object and attach the sound bgMusic to it
mySound = new Sound(this);
mySound.attachSound("bgMusic");
mySound.start(0, 999); // Play and loop the sound
}
onClipEvent (enterFrame) {
// Measure the mouse's horizontal location, then set the pan accordingly
mouseX = (_root._xmouse / 550) * 200;
mySound.setPan(mouseX - 100);
// Measure the mouse's vertical location, then set the volume accordingly
mouseY = (_root._ymouse / 400) * 300;
mySound.setVolume(300 - mouseY);
}
See Also
Sound. getPan( )
Sound.setTransform( ) Method | distribute the left and right channels between the left and right speakers
|
Availability
Flash 5
Synopsis
soundObject.setTransform(transformObject)
Arguments
- transformObject
A user-defined object that specifies new channel settings as a series
of properties.
Description
The setTransform( ) method gives us precise
control over how the channels in a sound are output to the left and
right speakers. In principle, setTransform( ) is
not unlike setPan( ), but it provides more
detailed sound control over stereo sounds.
A stereo sound
is a combination of two distinct sounds -- the left
channel and the right
channel -- which are normally sent separately to the
left and right speakers. However, using setTransform(
), we may dictate how much of each channel is broadcast in
each speaker. We may, for example, say, "Play half of the left
channel in the left speaker, none of the left channel in the right
speaker, and all of the right channel in both speakers." Or we
may say, "Play all of the left and right channels in the left
speaker."
To use setTransform( ), we must first create an
object with a series of predefined properties. The properties express
how to distribute the left and right channels of a stereo sound
between the left and right speakers, as described in Table 20-12.
Table 20-12. Properties of a transformObject
Property Name |
Property Value |
Property Description |
ll |
0 to 100 |
The percentage of the left channel to play in the left speaker |
lr |
0 to 100 |
The percentage of the right channel to play in the left speaker |
rl |
0 to 100 |
The percentage of the left channel to play in the right speaker |
rr |
0 to 100 |
The percentage of the right channel to play in the right speaker |
Once we have created an object with the properties described in Table 20-12, we pass that object to the
setTransform( ) method of our
Sound object. The values of the properties on
our transformObject become the new channel
output percentages for the sounds controlled by
soundObject.
To examine the current percentages of a particular
Sound object, we use the
Sound.getTransform( ) method.
Example
// Create a new Sound object
mySound = new Sound( );
// Create a new generic object to use with setTransform( )
transformer = new Object( );
// Set the properties of the transform object
transformer.ll = 0; // None of left channel in left speaker
transformer.lr = 0; // None of right channel in left speaker
transformer.rl = 0; // None of left channel in right speaker
transformer.rr = 100; // All of right channel in right speaker
// Apply the new channel distribution by passing the transform
// object to the setTransform( ) method
mySound.setTransform(transformer);
See Also
Sound.getTransform( ), Sound.setPan(
)
Sound.setVolume( ) Method | set the volume of sounds controlled by a Sound object
|
Availability
Flash 5
Synopsis
soundObject.setVolume(volume)
Arguments
- volume
A number indicating the loudness of the sound controlled by
soundObject, where
is no volume (mute). The larger
volume's absolute value (regardless
of whether volume is positive or
negative), the louder the sounds controlled by
soundObject will be. For example, -50 is
the same volume as 50. The default value
for volume is 100.
Description
The setVolume( )
method makes the sounds controlled by
soundObject louder or softer. To entirely
mute a sound, use a volume of 0. To make a
sound louder, increase volume. Values in
the range 100-200 are generally quite loud, but there is no
predefined maximum.
Note that setVolume( ) affects all the sounds
controlled by soundObject. If
soundObject is a global sound,
setVolume( ) affects all the sounds in a movie.
If soundObject is tied to a clip or a main
timeline, setVolume( ) affects all the sounds in
that clip or timeline.
The effects of setVolume( ) remain in effect
until overridden by another setVolume( ) call. A
setVolume( ) assignment affects all future
sounds controlled by soundObject, even if
soundObject is deleted.
Example
The first example simply sets the volume of a movie clip:
var mySound = new Sound( );
mySound.setVolume (65);
The following example shows how to make buttons that adjust a
movie's volume level:
// CODE ON THE MAIN MOVIE TIMELINE
var globalSound = new Sound( );
var maxVolume = 200;
var minVolume = 0;
var volumeIncrement = 20;
// CODE ON VOLUME-UP BUTTON ON MAIN TIMELINE
on (release) {
globalSound.setVolume(Math.min(globalSound.getVolume( ) + volumeIncrement,
maxVolume));
}
// CODE ON VOLUME-DOWN BUTTON ON MAIN TIMELINE
on (release) {
globalSound.setVolume(Math.max(globalSound.getVolume( ) - volumeIncrement,
minVolume));
}
See Also
Sound.getVolume( )
Sound.start( ) Method | begin playing an attached sound
|
Availability
Flash 5
Synopsis
soundObject.start(secondOffset, loops)
Arguments
- secondOffset
A floating-point number indicating the time in seconds at which to
start playing the sound attached to
soundObject (often called an
entry point). For example, a
secondOffset of 1 starts playback one
second after the sound's actual beginning as defined in the
Library. The default is 0. There is no provision for an exit point
(the time at which to stop playing the sound). The sound plays until
its end unless stopped manually.
- loops
A positive integer indicating how many times to play the sound
attached to soundObject. To play the sound
once, use 1 (which is the default); to play the sound twice in
succession, use 2, and so on. The portion of the sound from
secondOffset is repeated to its end the
number of times specified by loops.
Description
The start( ) method is used to play
programmatically-defined sounds that were added to
soundObject via attachSound(
). The start( ) method does not play
all the sounds in a clip or movie; it plays only the sound most
recently attached to soundObject via
attachSound( ).
To play only a portion of the sound attached to
soundObject, use the
secondOffset argument. To play the sound
attached to soundObject repeatedly, use
the loops argument.
Example
// Create a new Sound object
boink = new Sound( );
// Attach a sound exported as boink to the Sound object
boink.attachSound("boink");
// Play all of boink; soundOffset defaults to 0
boink.start( );
// Play only a portion of boink, starting 0.5 seconds into it; loops defaults to 1
boink.start(.5);
// Play boink three times from beginning to end
boink.start(0, 3);
See Also
Sound.stop( )
Sound.stop( ) Method | silences all sounds or a specified attached sound
|
Availability
Flash 5
Synopsis
soundObject.stop()
soundObject.stop(linkageIdentifier)
Arguments
- linkageIdentifier
The name
of any sound attached to any Sound object with
the same target as
soundObject. Linkage identifiers are
specified in the Library under Options Linkage.
Description
When invoked without a linkageIdentifier,
stop( ) silences all sounds controlled by
soundObject; if
soundObject is a global sound,
stop( ) silences all sounds in a movie; if
soundObject was created with a
target parameter, stop(
) silences all sounds in
target.
When invoked with a linkageIdentifier,
stop( ) silences only the specific sound named
by linkageIdentifier. In that case,
linkageIdentifier must be a sound that was
attached to a Sound object via
attachSound( ). However, the sound to stop need
not be attached to soundObject itself. It
may be attached to any
Sound object that shares the same
target as
soundObject. Or, if
soundObject was created with no
target (i.e., is a global
Sound object), the sound to stop may be attached
to any other global Sound object.
Example
// Create a global Sound object
mySound = new Sound( );
// Attach the sound doorbell to the object
mySound.attachSound("doorbell");
// Stop all sounds in the movie
mySound.stop( );
// Play doorbell
mySound.start( );
// Stop just doorbell
mySound.stop("doorbell");
// Create another global Sound object
myOtherSound = new Sound( );
// Attach a doorknock sound to the object
myOtherSound.attachSound("doorknock");
// Play doorknock
myOtherSound.start( );
// Now stop the doorknock through mySound, not myOtherSound.
// This works because the two Sound objects have the same target.
mySound.stop("doorknock");
See Also
Sound.start( )
_soundbuftime Global Property | length of a streaming sound, in seconds, to preload
|
Availability
Flash 4 and later
Synopsis
_soundbuftime
Access
Read/write
Description
The _soundbuftime property is an integer
specifying the number of seconds of a streamed sound to preload
before playing it. The default is 5 seconds.
Flash synchronizes movie playback with streaming sounds to ensure
that, say, a cartoon character's lips match an accompanying
sound track. Animations will pause until
_soundbuftime seconds of streaming sound are
downloaded; therefore, a long setting can cause excessive startup
times on slower connections. Because network streaming may be slow or
briefly interrupted, a short _soundbuftime setting
can cause sound to skip (i.e., if enough sound data wasn't
buffered). The ideal setting will vary from movie to movie based on
the complexity of the graphics, the quality settings of the sound,
and the bandwidth of the end user's Internet connection. The
default setting (5 seconds) usually works well, but experimentation
may be required to find the best setting for individual cases. The
streaming buffer time can be changed during playback, but it is a
global property and cannot be set separately for individual sounds.
Example
_soundbuftime = 10; // Buffer 10 seconds of audio
startDrag( ) Global Function | make a movie or movie clip follow the mouse pointer
|
Availability
Flash 4 and later
Synopsis
startDrag(target)
startDrag(target, lockCenter)
startDrag(target, lockCenter, left, top, right, bottom)
Arguments
- target
A string or reference indicating the path to the movie or movie clip
instance that should follow the mouse pointer (references to movie
clips are converted to paths when used in a string context).
- lockCenter
A Boolean indicating whether the
target's registration point should
be centered under the mouse pointer (true) or
dragged relative to its original location (false).
- left
A number specifying the minimum x-coordinate to the left of which
target's registration point may not
be dragged.
- top
A number specifying the minimum y-coordinate above which
target's registration point may not
be dragged.
- right
A number specifying the maximum x-coordinate to the right of which
target's registration point may not
be dragged.
- bottom
A number specifying the maximum y-coordinate below which
target's registration point may not
be dragged.
Description
The startDrag( ) function causes
target to visually follow the mouse
pointer around in the Player (known as dragging
the clip). The movement of a dragging clip can be constrained to a
bounding box whose coordinates are provided as arguments to the
startDrag( ) function. Bounding box coordinates
are given relative to the canvas on which
target resides. If that canvas is the main
movie Stage, then (0, 0) is the top-left corner of the Stage. If that
canvas is a movie clip, then (0, 0) is the registration point of the
clip's canvas. Note that Flash's coordinate system
reverses the Cartesian Y-axis; y values increase
toward the bottom of the screen and decrease
toward the top of the screen. Negative y values are
above the origin (i.e., above the X-axis).
Dragging can be stopped at any time via the stopDrag(
) function. Only one movie clip or movie may be dragged at
a time, so issuing a startDrag( ) function on a
new target automatically cancels any drag
operation already in progress. That said, when a movie or move clip
is dragged, all the movie clips it contains are dragged along with
it.
Example
// Drag ball, limiting its movement to the upper-left corner of the Stage
startDrag("ball", true, 0, 0, 225, 200);
See Also
Movieclip.startDrag( ), stopDrag(
)
stop( ) Global Function | pause the movie's playback at the current frame
|
Availability
Flash 2 and later
Synopsis
stop()
Description
The stop( ) function is a simple but fundamental
function that halts the playback of a movie or movie clip. It is the
global counterpart of the MovieClip.stop( )
method. It is commonly used to wait for the user to, say, choose from
a graphical menu.
See Also
MovieClip.stop( ), play( )
stopAllSounds( )
Global Function | silence a movie
|
Availability
Flash 3 and later
Synopsis
stopAllSounds()
Description
The stopAllSounds( ) function mutes all the
sounds currently playing in a movie, no matter how deeply nested in
movie clips. This applies to every sound in a movie, including
programmatically generated Sound objects. For
more precise control over stopping, starting, and setting the volume
of sounds, see the Sound class.
Note that stopAllSounds( ) has only a temporary
effect. Any sound that starts after a stopAllSounds(
) invocation will play normally. There is no way to
permanently mute a movie.
See Also
Sound.setVolume( ), Sound.stop(
)
String( ) Global Function | convert a value to the String datatype
|
Availability
Flash 5
Synopsis
String(value)
Arguments
- value
An expression containing the value to be converted to a string.
Returns
The result of converting value to a
primitive string.
Description
The String( ) function converts its argument to
a primitive string value and returns that converted value. The
results of converting various types of data to a primitive string are
described in Table 3-2. It's normally not
necessary to use the String( ) function;
ActionScript automatically converts values to the
string type when appropriate.
Be sure not to confuse the global String( )
function with the String class constructor. The
former converts an expression to a string, whereas the later is a
class that wraps primitive string data in an object so that
properties and methods may be applied to it.
Usage
Note that the String( ) function sometimes
appears in Flash 4 .fla files that have been
converted to the Flash 5 format. For information on how datatypes are
handled when Flash 4 files are converted to Flash 5, see Section 3.4.4, "Flash 4-to-Flash 5 Datatype Conversion" in Chapter 3, "Data and Datatypes".
See Also
The String class; Section 3.4.2, "Explicit Type Conversion" in Chapter 3, "Data and Datatypes"
String Class | wrapper class for string primitive type
|
Availability
Flash 5
Constructor
new String(value)
Arguments
- value
An expression to be resolved and, if necessary, converted to a
string, then wrapped in a String object.
Properties
- length
The number of characters in a string.
Class Methods
The following method is invoked through the
String class itself, not through an object of
the String class:
- fromCharCode( )
Generate a string from one or more Latin 1/Shift-JIS code points.
Methods
The following object methods are invoked through an instance of the
String class:
- charAt( )
Retrieve a character at a specific position in the string.
- charCodeAt( )
Retrieve the code point of a character at a specific position in the
string.
- concat( )
Combine one or more items into a single string.
- indexOf( )
Find the first occurrence of a specified substring in a string.
- lastIndexOf( )
Find the last occurrence of a specified substring in a string.
- slice( )
Extract a substring from a string based on positive or negative
character positions.
- split( )
Convert a string to an array.
- substr( )
Extract a substring from a string based on a starting position and
length.
- substring( )
Extract a substring from a string based on positive character
positions only.
- toLowerCase( )
Return a lowercase version of a string.
- toUpperCase( )
Return an uppercase version of a string.
Description
The String class has several purposes:
It can be used to create a String object, which
contains a primitive string value in an unnamed, internal property;
however, there is little reason to do so.
Usage
In practice, the String class constructor is
used primarily to convert other datatypes to strings. See the global
String( ) function for more details.
See Also
Section 4.5, "The String Type" in Chapter 4, "Primitive Datatypes"
String.charAt( ) Method | retrieve the character from a specific position in a string
|
Availability
Flash 5
Synopsis
string.charAt(index)
Arguments
- index
The integer position of the character to retrieve, which should be in the range 0 (the first character) to string.length-1 (the last character).
Returns
The character in the position index within
string.
Description
The charAt( ) method determines the character
that resides at a certain position (index)
in a string.
Example
trace("It is 10:34 pm".charAt(1)); // Displays: "t" (the second letter)
var country = "Canada";
trace(country.charAt(0)); // Displays: "C" (the first letter)
// This function removes all the spaces from a string and returns the result
function stripSpaces (inString) {
var outString = "";
for (i = 0; i < inString.length; i++) {
if (inString.charAt(i) != " ") {
outString += inString.charAt(i);
}
}
return outString;
}
See Also
String.charCodeAt( ), String.indexOf(
), String.slice( ); Section 4.6.5.2, "The charAt( ) function" in Chapter 4, "Primitive Datatypes"
String.charCodeAt( )
Method | retrieve the code point of the character at a specific position in a string
|
Availability
Flash 5
Synopsis
string.charCodeAt(index)
Arguments
- index
The integer position of a character in
string, which should be in the range 0
(the first character) to
string.length-1 (the
last character).
Returns
An integer representing the Latin 1 or Shift-JIS code point, as shown
in Appendix B, "Latin 1 Character Repertoire and Keycodes", of the character in the position
index within
string.
Example
var msg = "A is the first letter of the Latin alphabet.";
trace(msg.charCodeAt(0)); // Displays: 65 (the code for the "A" character)
trace(msg.charCodeAt(1)); // Displays: 32 (the code for the space character)
See Also
String.charAt( ), String.fromCharCode(
); Appendix B, "Latin 1 Character Repertoire and Keycodes", Section 4.6.9.2, "The charCodeAt( ) function" in Chapter 4, "Primitive Datatypes"
String.concat( ) Method | combine one or more values into a single string
|
Availability
Flash 5
Synopsis
string.concat(value1, value2,...valuen)
Arguments
- value1,...valuen
Values to be converted to strings (if necessary) and concatenated
with string .
Returns
The result of concatenating string with
value1, value2,
...valuen .
Description
The concat( ) method creates a string from a
series of values. It is equivalent to using the concatenation
operator (+) with strings but is sometimes
preferred for clarity, as the + operator can also
be used to add numbers. For details on concat(
), see Chapter 4, "Primitive Datatypes".
Usage
Note that concat( ) does not modify
string ; it returns a completely new
string.
Example
var greeting = "Hello";
excitedGreeting = greeting.concat("!");
trace(greeting); // Displays: "Hello"
trace(excitedGreeting); // Displays: "Hello!"
var x = 4; // Initialize x as an integer
trace(x + 5); // Displays: 9
trace(x.concat(5)); // Fails because x is not a string.
trace(String(x).concat(5)); // Displays: "45"
var x = "4"; // Initialize x as a string
trace(x.concat(5)); // Displays: "45"
trace(concat("foo", "fee")); // Fails because concat( ) must be invoked
// as a method of a string.
See Also
The + operator, in Chapter 5, "Operators",
Section 4.6.1.1, "The concat( ) function" in Chapter 4, "Primitive Datatypes"
String.fromCharCode( ) Class Method | generate a string from one or more code points
|
Availability
Flash 5
Synopsis
String.fromCharCode(code_ point1, code_ point2,...code_ pointn)
Arguments
- code_ point1,...code_ pointn
A series of one or more decimal integers corresponding to Latin 1 or
Shift-JIS character code points, as shown in Appendix B, "Latin 1 Character Repertoire and Keycodes".
Returns
A string formed by concatenating the characters represented by the
specified code points.
Description
The fromCharCode( ) class method produces a
character or series of characters from character code points as
described in Chapter 4, "Primitive Datatypes".
Example
// Makes a copyright symbol, followed by the year (2001)
copyNotice = String.fromCharCode(169) + " 2001";
See Also
String.charCodeAt( ); Appendix B, "Latin 1 Character Repertoire and Keycodes", Section 4.6.9.1, "The fromCharCode( ) function" in
Chapter 4, "Primitive Datatypes"
String.indexOf( ) Method | find the first occurrence of a substring in a string
|
Availability
Flash 5
Synopsis
string.indexOf(substring)
string.indexOf(substring, startIndex)
Arguments
- substring
A string containing the character or characters to search for.
- startIndex
An optional integer position in string at
which to start searching for substring.
Should be in the range
(the first character) to
string.length-1 (the
last character). Defaults to 0.
Returns
The position of the first occurrence of
substring in
string (starting at
startIndex). Returns -1 if
substring is not found at or after
startIndex in
string.
Description
The indexOf( ) method is used to search for
characters in strings or to check whether a string contains a certain
substring.
Example
// Check if an email address contains an @ sign
var email = "derekaol.com";
if (email.indexOf("@") == -1) {
trace ("This isn't a valid email address");
}
// Check if an email address has an @ sign and is from the domain aol.com
var email = "derek@aol.com";
var atPos = email.indexOf("@");
if (atPos != -1 && email.indexOf("aol.com") == atPos + 1) {
gotoAndStop("AOLuserOffer");
}
The following code shows a generic function that checks for a keyword
in a string, as you might need when grading a fill-in-the-blank quiz:
// Generic function to search origStr for any occurrence
// of searchStr using a case-insensitive comparison
function search (origStr, searchStr) {
var origStr = origStr.toLowerCase( );
var searchStr = searchStr.toLowerCase( );
return origStr.indexOf(searchStr) != -1;
}
var answer = "einstein";
var guess = "Dr. Albert Einstein";
// Increment score if guess contains "einstein"
if (search(guess, answer)) {
score++;
}
See Also
String.charAt( ), String.lastIndexOf(
); Section 4.6.5.3, "The indexOf( ) function" in Chapter 4, "Primitive Datatypes"
String.lastIndexOf( ) Method | find the last occurrence of a substring in a string
|
Availability
Flash 5
Synopsis
string.lastIndexOf(substring)
string.lastIndexOf(substring, startIndex)
Arguments
- substring
A string containing the character or characters to search for.
- startIndex
An optional integer position in string at
which to start the search for substring.
The string is searched backward from
startIndex, which should be in the range 0
(the first character) to
string.length-1 (the
last character). Defaults to
string.length-1.
Returns
The position of the last occurrence of
substring in
string prior to
startIndex. Returns -1 if
substring is not found prior to
startIndex in
string.
Description
The lastIndexOf( ) method is used to search for
the last occurrence of a substring in a string or to check whether a
string contains a certain substring.
Example
URL = "http://www.moock.org/webdesign/flash/fillthewindow.html";
// Finds the last slash character
lastSlash = URL.lastIndexOf("/");
// Extracts the filename from the URL
file = URL.substring(lastSlash + 1);
trace(file); // Displays: fillthewindow.html
See Also
String.charAt( ), String.indexOf(
); Section 4.6.5.4, "The lastIndexOf( ) Function" in Chapter 4, "Primitive Datatypes"
String.length Property | the number of characters in a string
|
Availability
Flash 5
Synopsis
string.length
Access
Read-only
Description
The length property returns the number of
characters in string. Note that a null
character (ASCII 0) does not signal the end of a string, as it would
in some languages, but neither is it counted in the string's
length. For example:
// Create the string "A" + null + "B"
var myString = String.fromCharCode(65,0,66);
trace(myString.length); // Displays: 2 (The null character is ignored)
Example
var myString = "hello";
trace (myString.length); // Displays: 5
trace ("hello".length); // Displays: 5
// Here we convert the number 1000 to a
// string in order to test its length
var age = 1000;
// Display an error message if the number has the wrong number of digits.
if (String(age).length != 2) {
trace ("Please enter a two-digit number");
}
See Also
Array.length( ); Section 4.6.5.1, "The length property" in Chapter 4, "Primitive Datatypes"
String.slice( ) Method | extract a substring from a string based on positive or negative character positions
|
Availability
Flash 5
Synopsis
string.slice(startIndex, endIndex)
Arguments
- startIndex
The integer position of the first character to extract from
string. If
startIndex is negative, the position is
measured from the end of the string, where -1 is the last character,
-2 is the second-to-last character, and so on. (i.e., a negative
startIndex specifies the character at
string.length+startIndex).
- endIndex
The integer position of the character after the
last character to extract from string. If
endIndex is negative, the position is
measured from the end of the string, where -1 is the last character,
-2 is the second-to-last character, and so on. (i.e., a negative
endIndex specifies the character at
string.length+endIndex).
Defaults to
string.length if
omitted.
Returns
A substring of string, starting at
startIndex and ending at
endIndex-1, where both
startIndex and
endIndex are zero-relative.
Description
The slice( ) method is one of three methods that
can be used to extract a substring from a string (the others being
substring( ) and substr( )
). The slice( ) method offers the
option of negative start and end index values, which allows us to
extract a substring by measuring back from the end of a string.
Usage
Note that slice( ) does not modify
string ; it returns a completely new
string.
Example
var fullName = "Steven Sid Mumby";
middleName = fullName.slice(7, 10); // Assigns "Sid" to middleName
middleName = fullName.slice(-9, -6); // Also assigns "Sid" to middleName
See Also
String.substr( ), String.substring(
); Section 4.6.6.3, "The slice( ) function" and Section 4.6.7, "Combining String Examination with Substring Extraction" in Chapter 4, "Primitive Datatypes"
String.split( ) Method | convert a string into a series of array elements
|
Availability
Flash 5
Synopsis
string.split(delimiter)
Arguments
- delimiter
The character or series of characters at which to break
string when forming elements of the new
array.
Returns
An array whose elements contain the substrings formed by breaking
string into segments demarcated by
delimiter.
Description
The split( ) method breaks a string into
substrings, assigns those substrings to the elements of an array, and
returns that array. Contiguous occurrences of
delimiter without intervening characters
result in empty elements. For example, the following code:
owners = "terry,doug,,,jon";
ownersArray = owners.split(",");
assigns the following elements to ownersArray
(elements 2 and 3 contain undefined):
0: terry
1: doug
2:
3:
4: jon
The split( ) method is typically used to convert
a string received from a CGI script or text file into an array for
further manipulation. It is also useful when parsing the parameters
of an asfunction call from an HMTL text field
<A> tag, which can pass only one string argument to a function.
See Section 18.5.14, "Calling ActionScript Functions from HTML Links" in Chapter 18, "On-Screen Text Fields", for example code. Common delimiters include
the comma and the Tab character.
Example
Suppose we store a list of names in a text file named
names.txt. Each name is separated from the
others by a Tab character, as implied by the whitespace shown:
owners=terry doug jon
On frame 1 of our movie, we load the names.txt
file into our movie:
this.loadVariables("names.txt");
After ensuring that names.txt has fully loaded
(see Section 10.10.4, "data" in Chapter 10, "Events and Event Handlers"), we split the loaded
owners variable into an array:
splitString = String.fromCharCode(9); // Assign the Tab character to splitString
ownersArray = owners.split(splitString);
trace(ownersArray[1]); // Displays: "doug"
Note that split( ) can take a long time to
execute with large bodies of text. If performance is a problem, break
your data into manageable portions or consider using XML instead. See
the XML class.
Bugs
In Flash 5, using the empty string as a delimiter adds all of
string to the first element of the array
being generated. According to ECMA-262, an empty string delimiter
should cause string to be broken at each
character. Similarly, multicharacter delimiters are not recognized by
Flash 5 and cause all of string to be
assigned to the first element of the returned array.
See Also
Array.join( ); Section 4.6.6.4, "The split( ) function" in Chapter 4, "Primitive Datatypes"
String.substr( ) Method | extract a substring from a string based on a starting position and length
|
Availability
Flash 5
Synopsis
string.substr(startIndex, length)
Arguments
- startIndex
The integer position of the first character to extract from
string. If
startIndex is negative, the position is
measured from the end of the string, where -1 is the last character,
-2 is the second-to-last character, and so on. (i.e., a negative
startIndex specifies the character at
string.length+startIndex).
- length
The number of characters to extract from
string, starting at (and including) the
startIndex. If not specified, all the
characters from startIndex to the end of
string are extracted.
Returns
A substring of string, starting at
startIndex and including
length characters. If
length is omitted, the result contains
characters from startIndex to the end of
string.
Description
The substr( ) method is one of three methods
that can be used to extract a substring from a string (the others
being slice( ) and substring( )
). The substr( ) method extracts a
string based on the number of characters specified by
length, not based on two character
indexes.
Usage
Note that substr( ) does not modify
string ; it returns a completely new
string.
Example
var fullName = "Steven Sid Mumby";
middleName = fullName.substr(7, 3); // Assigns "Sid" to middleName
firstName = fullName.substr(0, 6); // Assigns "Steven" to firstName
lastName = fullName.substr(11); // Assigns "Mumby" to lastName
// Notice the negative starting indexes...
middleName = fullName.substr(-9, 3); // Assigns "Sid" to middleName
firstName = fullName.substr(-16, 6); // Assigns "Steven" to firstName
lastName = fullName.substr(-5); // Assigns "Mumby" to lastName
See Also
String.slice( ), String.substring(
); Section 4.6.7, "Combining String Examination with Substring Extraction" and Section 4.6.6.2, "The substr( ) function" in Chapter 4, "Primitive Datatypes"
String.substring( )
Method | extract a substring from a string based on positive character positions
|
Availability
Flash 5
Synopsis
string.substring(startIndex, endIndex)
Arguments
- startIndex
The positive integer position of the first character to extract from
string. If negative, 0
is used.
- endIndex
The positive integer position of the character
after the last character to extract from
string. Defaults to
string.length if
omitted. If negative, 0
is used.
Returns
A substring of string, starting at
startIndex and ending at
endIndex-1, where both
startIndex and
endIndex are zero-relative.
Description
The substring( ) method is one of three methods
that can be used to extract a substring from a string (the others
being slice( ) and substr(
) ). The substring( ) function is
identical to slice( ) except that it does not
allow for negative startIndex and
endIndex values, and it automatically
reorders the two indexes if endIndex is
less than startIndex.
Usage
Note that substring( ) does not modify
string ; it returns a completely new
string.
Example
// Extract names from a string
var fullName = "Steven Sid Mumby";
middleName = fullName.substring(7, 10); // Assigns "Sid" to middleName
middleName = fullName.substring(10, 7); // Assigns "Sid" to middleName
// (indexes are swapped automatically)
firstName = fullName.substring(0, 6); // Assigns "Steven" to firstName
lastName = fullName.substring(11); // Assigns "Mumby" to lastName
The following example is a reusable function to search for and
replace all occurrences of a substring within a string:
// A Search-and-Replace Function
function replace (origStr, searchStr, replaceStr) {
var tempStr = "";
var startIndex = 0;
if (searchStr == "") {
return origStr;
}
if (origStr.indexOf(searchStr) != -1) {
while ((searchIndex = origStr.indexOf(searchStr, startIndex)) != -1) {
tempStr += origStr.substring(startIndex, searchIndex);
tempStr += replaceStr;
startIndex = searchIndex + searchStr.length;
}
return tempStr + origStr.substring(startIndex);
} else {
return origStr;
}
}
msg = "three times three is four";
trace(replace(msg, "three", "two")); // Displays: "two times two is four"
See Also
String.slice( ), String.substr(
); Section 4.6.7, "Combining String Examination with Substring Extraction" and Section 4.6.6.2, "The substr( ) function" in Chapter 4, "Primitive Datatypes"
String.toLowerCase( ) Method | generate a lowercase version of a string
|
Availability
Flash 5
Synopsis
string.toLowerCase()
Returns
The lowercase equivalent of string as a
new string. Characters without a lowercase equivalent are left
unchanged.
Description
The toLowerCase( ) method creates a new,
lowercase version of string ; it can be
used for formatting or to facilitate case-insensitive character
comparisons. The toLowerCase( ) method converts
only characters in the range A-Z (it does not convert characters with
diacritical marks such as accents and umlauts).
Usage
Note that toLowerCase( ) does not modify
string ; it returns a completely new
string.
Example
// Set msg to "this sentence has mixed caps!"
msg = "ThiS SenTencE Has MixED CaPs!".toLowerCase( );
// Perform a case-insensitive comparison of two strings
function caseInsensitiveCompare (stringA, stringB) {
return (stringA.toLowerCase() == stringB.toLowerCase( ));
}
trace(caseInsensitiveCompare("Colin", "colin")); // Displays: true
See Also
String.toUpperCase( );
Section 4.6.8.2, "The toLowerCase( ) function" in Chapter 4, "Primitive Datatypes"
String.toUpperCase( ) Method | generate an uppercase version of a string
|
Availability
Flash 5
Synopsis
string.toUpperCase()
Returns
The uppercase (a.k.a. ALL CAPS) equivalent of
string as a new string. Characters without
an uppercase equivalent are left unchanged.
Description
The toUpperCase( ) method creates a new,
uppercase version of string ; it can be
used for formatting or to facilitate case-insensitive character
comparisons. The toUpperCase( ) method converts
only characters in the range a-z (it does not convert characters with
diacritical marks such as accents and umlauts).
Usage
Note that toUpperCase( ) does not modify
string ; it returns a completely new
string.
Example
"listen to me".toUpperCase( ); // Yields the string "LISTEN TO ME"
var msg1 = "Your Final Score: 234";
var msg2 = msg1.toUpperCase( ); // Set msg2 to "YOUR FINAL SCORE: 234"
See Also
String.toLowerCase( ) ;
Section 4.6.8.1, "The toUpperCase( ) function" in Chapter 4, "Primitive Datatypes"
targetPath( ) Global
Function | the absolute path to a movie or movie clip
|
Availability
Flash 5
Synopsis
targetPath (movieClip)
Arguments
- movieClip
A reference to a movie clip object.
Returns
A string representing the path to
movieClip in absolute terms, using dot
notation (e.g., "_level0.myMovie").
Description
The targetPath( ) function returns a movie
clip's reference as a string that describes the absolute path
to the clip (identical to the return value of
MovieClip.valueOf( ) ). The
targetPath( ) function is sometimes used to
compose placement-sensitive code that operates on a movie clip
relative to the timeline upon which the clip resides.
Bugs
Note that the example code given for targetPath(
) in the Flash 5 ActionScript Dictionary does not
represent the proper usage of targetPath( );
contrary to what the example implies, it is not a synonym for
tellTarget( ).
Example
If square is a movie clip contained by
shapes, which resides on the main timeline of
level 0, then inside the shapes clip, the
statement:
targetPath(square);
would return:
"_level0.shapes.square"
See Also
MovieClip._target,
MovieClip.valueOf( ); Section 13.5.6.6, "The targetPath( ) function" in Chapter 13, "Movie Clips"
tellTarget( ) Global Function | execute statements in the scope of a remote movie clip
|
Availability
Flash 3 and Flash 4; deprecated in Flash 5 in favor of
object-oriented syntax or the with statement
Synopsis
tellTarget (target) {
statements
}
Arguments
- target
A string or reference indicating the path to a movie or movie clip
instance (references are converted to paths when used in a string
context).
- statements
The statements to be executed in the scope of
target.
Description
In Flash 3 and Flash 4, tellTarget( ) was the
primary means of communicating between two movie clips (i.e.,
controlling one from the other). It was used to invoke functions such
as play( ), stop( ), and
gotoAndStop( ) on remote movie clips. In Flash
4, when variables were added to ActionScript, we could also use
tellTarget( ) to get and set remote clip
variable values. In Flash 5, these endeavors are better accomplished
with the dot operator, ., and the array access operator,
[]. Another alternative to the
tellTarget( ) function is the
with statement, described in Chapter 6, "Statements".
Usage
The tellTarget( ) function may be better
described as a statement because it requires a substatement block.
The point, however, is academic, as tellTarget(
) has been deprecated.
Example
tellTarget ("ball") {
gotoAndStop("redStripes");
_x += 300;
}
See Also
Section 6.3.9, "The with Statement"" in Chapter 6, "Statements"; Section 13.5.7, "Whither Tell Target?" and Section 13.1, "The "Objectness" of Movie Clips" in Chapter 13, "Movie Clips"
toggleHighQuality( )
Global Function | change the rendering quality of the Player
|
Availability
Flash 2 and later; deprecated in Flash 5 in favor of
_quality
Synopsis
toggleHighQuality()
Description
Switches between High quality and Low quality rendering. When set to
High, the Flash Player renders lines with antialiased (smooth) edges.
When set to Low, the Flash Player renders lines with aliased (jagged)
edges. The toggleHighQuality( ) function does
not take any arguments; it simply switches between the two possible
settings -- "High" and "Low". This is
problematic because it doesn't explicitly set the quality to a
known setting, nor does it allow for more than two different possible
quality settings.
As of Flash 5, toggleHighQuality( ) has been
deprecated in favor of the global _quality
property, which supports Low, Medium, High, and Best rendering
settings.
See Also
_highquality, _quality
trace( ) Global Function | display a value in the Output window
|
Availability
Flash 4 and later
Synopsis
trace(value)
Arguments
- value
The expression to be resolved and then displayed in the Output
window. If the resolved value of value is
not a string, it is converted to a string before being sent to the
Output window, according to the rules described in Table 3-2.
Description
The trace( ) function is a debugging tool used
only within the Test Movie mode of the Flash authoring environment.
Though unassuming in nature, trace( ) is
actually one of the fundamental components of ActionScript
programming; it allows us to check the value of a variable or
expression at any point during the playback of a movie.
Usage
Unfortunately trace( ) can be quite slow. Turn
off tracing under File Publish Settings Flash using the
Omit Trace Actions option.
Example
trace(firstName); // Output the value of firstName
trace(myClip); // Output the path to myClip
trace(myClip._x) // Output the x coordinate of myClip
trace("hello" + " there"); // Resolve then output the expression
See Also
Chapter 19, "Debugging"
unescape( ) Global Function | decode an escaped string
|
Availability
Flash 5
Synopsis
unescape(stringExpression)
Arguments
- stringExpression
A string (or expression that resolves to a string) that was
previously encoded via escape( ).
Returns
A new string that is a decoded version of
string.
Description
The unescape( ) function returns a new string
based on string. The new string contains
equivalent Latin 1 characters for every occurrence of a two-digit
hexadecimal escape sequence prefixed with % in
string. The escape( )
and unescape( ) functions are used to encode and
decode strings for safe transfer over a network. However, manual use
of unescape( ) is rarely necessary as Flash
automatically converts URL-encoded text when it is imported via
loadVariables( ).
Example
var msg = "hello!";
// Set msgCoded to "hello%21"
msgCoded = escape(msg);
// Set msgDecoded to "hello!"
var msgDecoded = unescape(msgCoded);
See Also
escape( ); Appendix B, "Latin 1 Character Repertoire and Keycodes"
unloadMovie( )
Global Function | remove a movie or movie clip from the Player
|
Availability
Flash 4 and later (Flash 5's unloadMovie(
) function corresponds to Flash 4's Unload
Movie with a target path)
Synopsis
unloadMovie(target)
Arguments
- target
A string or reference indicating the path to the movie clip or
document level to remove from the Player (references are converted to
paths when used in a string context).
Description
The unloadMovie( ) function is most often used
to delete movies from document levels in the Player. For example, if
a movie is loaded onto level 1 in the Player, we may remove that
movie from the Player as follows:
unloadMovie("_level1");
The unloadMovie( ) function can also be used on
movie clip instances, in which case it removes the content of the
instance but not the instance itself. The instance is left on stage
as an empty shell; we may load subsequent movies into that shell.
Hence, a single clip can act as a container for dynamic content that
is managed through successive loadMovie( ) and
unloadMovie( ) executions.
See Also
loadMovie( ), MovieClip.unloadMovie(
), unloadMovieNum( ); Section 13.6, "Removing Clip Instances and Main Movies" and Section 13.8.3.1, "Method versus global function overlap issues"
in Chapter 13, "Movie Clips"
unloadMovieNum( ) Global Function | remove a movie from a document level
|
Availability
Flash 3 and later (Flash 5's unloadMovieNum(
) function corresponds to Flash 3's unload
Movie, which worked only with numbered levels)
Synopsis
unloadMovieNum(level)
Arguments
- level
A non-negative integer or an expression that yields a non-negative
integer, indicating the document level to unload.
Description
The unloadMovieNum( ) function is nearly
identical to unloadMovie( ) except that it
requires the target level of the load
operation to be specified as a number rather than as a string. This
means that unloadMovieNum( ) can only remove
movies on document levels, not movie clips. It is normally used when
we wish to dynamically assign the level of a movie to unload, as in:
var x = 3;
unloadMovieNum(x);
This can also be achieved using string concatenation with the regular
unloadMovie( ) function:
unloadMovie("_level" + x);
See Also
loadMovieNum( ),
Movieclip.unloadMovie( ), unloadMovie(
); Section 13.6, "Removing Clip Instances and Main Movies" in Chapter 13, "Movie Clips"
updateAfterEvent( )
Global Function | render the contents of the Stage between frames
|
Availability
Flash 5
Synopsis
updateAfterEvent()
Description
The user-input clip event handlers (mouseMove,
mouseDown, mouseUp,
keyDown, and keyUp) often
occur between frame renderings in the Flash Player. To force the
screen to reflect visual changes that occur during a user-input clip
event handler, we invoke updateAfterEvent( )
within any of those handlers. Note, however, that
updateAfterEvent( ) is not an arbitrary
screen-refreshing tool; it works only within the user-input clip
events. Outside of onClipEvent( ) handlers, it
has no effect.
Example
The following script attached to a movie clip causes the clip to
follow the mouse pointer and refreshes the screen every time the
pointer moves. Because we refresh the screen every time the pointer
moves, the clip following the pointer animates very smoothly:
onClipEvent (mouseMove) {
_x = _root._xmouse;
_y = _root._ymouse;
updateAfterEvent( );
}
Bugs
Note that the Flash 5 ActionScript Dictionary incorrectly describes
the updateAfterEvent( ) function as accepting a
clip event as an argument. It does not accept any arguments.
See Also
See Section 10.14, "Refreshing the Screen with updateAfterEvent" in Chapter 10, "Events and Event Handlers"
$version "Global" Property | the version of the Flash Player
|
Availability
Flash 4 Build 11 and later; deprecated in Flash 5 in favor of
get Version
Synopsis
_root.$version
Access
Read-only
Description
The $version property contains the same string as
the return value of the global getVersion( )
function (operating system, followed by Player version information).
The $version property was introduced midway
through the life cycle of the Flash 4 Player and has been replaced by
the getVersion( ) function. It is technically
not a global property, but a property of the main movie timeline;
from any other movie clip timeline, it must be accessed as
_root.$version.
See Also
getVersion( )
XML Class | DOM-based support for XML-structured data
|
Availability
Flash 5
Constructor
new XML()
new XML(source)
Arguments
- source
An optional string containing well-formed XML (or HTML) data to be
parsed into an XML object hierarchy.
Properties
- attributes
An object whose properties store element attributes.
- childNodes
An array of references to a node's children.
- contentType
The MIME content type to be transmitted to servers.
- docTypeDecl
The document's DOCTYPE tag.
- firstChild
A reference to the first descendant of a node.
- ignoreWhite
Determines whether to ignore whitespace nodes during XML parsing.
- lastChild
A reference to the last descendant of a node.
- loaded
Status of a load( ) or sendAndLoad(
) operation.
- nextSibling
A reference to the node after this node in the current level of the
object hierarchy.
- nodeName
The name of the current node.
- nodeType
The type of the current node.
- nodeValue
The value of the current node.
- parentNode
A reference to the immediate ancestor of a node.
- previousSibling
A reference to the node before this node in the current level of the
object hierarchy.
- status
Error code describing the result of parsing XML source into an object
hierarchy.
- xmlDecl
The document's XML declaration tag.
Methods
- appendChild( )
Add a new child node to a node.
- cloneNode( )
Create a copy of a node.
- createElement( )
Create a new element node.
- createTextNode( )
Create a new text node.
- hasChildNodes( )
Check if a node has any descendants.
- insertBefore( )
Add a sibling node before a node.
- load( )
Import XML source code from an external document.
- parseXML( )
Parse a string of XML source code.
- removeNode( )
Delete a node from an object hierarchy.
- send( )
Send XML source code to a script.
- sendAndLoad( )
Send XML source code to a script and receive XML source in return.
- toString( )
Convert an XML object to a string.
Event Handlers
- onData( )
Handler executed when external XML source finishes loading.
- onLoad( )
Handler executed when external XML data has been parsed into an
object hierarchy.
Description
We use
objects of the XML
class to manipulate the content of an XML (or HTML) document in an
object-oriented manner and to send XML-formatted data to and from
Flash. Using the methods and properties of an
XML object, we may build an XML-structured
document (or read an existing one) and efficiently access, change, or
remove the information in that document.
The source code of an XML document consists primarily of a series of
elements and attributes. For example, in the following XML fragment,
the elements BOOK, TITLE,
AUTHOR, and PUBLISHER take the
same form as well-known HTML tags, and we see that the
AUTHOR element supports one attribute,
SALUTATION:
<BOOK>
<TITLE>ActionScript: The Definitive Guide</TITLE>
<AUTHOR SALUTATION="Mr.">Colin Moock</AUTHOR>
<PUBLISHER>O'Reilly</PUBLISHER>
</BOOK>
From an object-oriented perspective, the content of an XML document
can be treated as a hierarchy of objects in which each element and
text block becomes an object
node in a flowchart-like structure. Figure 20-1 shows our simple XML
<BOOK> fragment represented conceptually as
an XML object hierarchy.
Figure 20-1. A sample XML node hierarchy
Let's consider the structure and semantics of this sample XML
object hierarchy from left to right. We start with the main
XML object, shown in Figure 20-1 as DOCUMENT, which is
created automatically by the XML constructor and
serves as the container for our XML object hierarchy.
Moving one tier to the right in the hierarchy, we come to
BOOK, which is the first element in our XML source
code fragment and, in this case, also the first object
node under DOCUMENT. The
BOOK node is the root of our
XML data structure -- every well-formed XML document must have an
all-encompassing root element such as BOOK that
contains every other element. Branches of an XML object hierarchy are
added to the tree either by parsing XML source code or invoking
node-addition methods on the objects in the hierarchy.
When a node is contained by another node, the contained
node is said to be a child of the
containing node, which is known as the parent.
In our example, BOOK is the first child of
DOCUMENT, and DOCUMENT is
BOOK's parent.
As we move to the right in Figure 20-1, we see that
BOOK has seven children, including four
#text nodes that do not seem to be present in our
original XML document. Each occurrence of
whitespace between elements in XML
source code is rendered as an object in an XML object hierarchy. If
we look closely, we'll find whitespace -- a carriage return
and a Tab character -- between BOOK and
TITLE in the preceding XML fragment. This
whitespace is represented by a #text node in Figure 20-1, which also shows similar whitespace nodes
after the TITLE, AUTHOR, and
PUBLISHER nodes.
BOOK's children are
siblings of one another (i.e., they reside on
the same level in the hierarchy). For example, we say that
AUTHOR's next sibling
is #text, and AUTHOR's
previous sibling is #text.
You can see how the #text nodes
get in our way when we're moving from sibling to sibling in a
hierarchy. We can deal with these empty whitespace nodes in one of
the following ways:
Finally, we move to the last tier in the hierarchy where we find that
the TITLE, AUTHOR, and
PUBLISHER nodes each has a single child. Each
child is a text node, corresponding to the text contained by the
elements TITLE, AUTHOR, and
PUBLISHER. Notice that the text contained by an
element in XML source code resides in a child node of that element in
the corresponding object hierarchy. To access
text contained by an element, we must always refer to that
element's child using either
firstChild.nodeValue or
childNodes[0].nodeValue, which we'll
consider shortly.
But what of the element attributes? Where do they appear in our XML
object hierarchy? You might expect AUTHOR's
SALUTATION attribute to be depicted as a child
node called SALUTATION. But in practice, an
attribute is not considered a child of the
element that defines it, but rather a property
of that element. To learn how attribute properties are accessed, see
the XML.attributes
entry.
Let's see how to build an XML
document as a hierarchy of node objects. To create a new, blank
XML object, we use the XML(
) constructor:
myDocument = new XML( );
We can then add nodes to our empty XML object by
invoking methods such as appendChild( ),
parseXML( ), and load( ) on
the object. Alternatively, we may create an XML
object from existing XML source in our script by invoking the XML
constructor with the source argument:
myDocument = new XML(source);
For example:
myDocument = new XML('<P>hello world!</P>');
When a source argument is supplied to the
XML( ) constructor,
source is parsed and converted into a new
object hierarchy, which is then stored in the object returned by the
constructor. (In this case, the node P is assigned
as myDocument's first child and the text
node with the nodeValue "hello world!"
is assigned as P's first child.)
Once an XML hierarchy is created and stored in an object, we may
access the information in that hierarchy using the methods and
properties of the XML class. For example,
suppose we want to retrieve the text "hello world!" in
myDocument. Thinking in object-oriented terms, we
might assume that we could access the text of P as
a property of myDocument, as follows:
myDocument.P. In fact, that won't work;
instead of referring to nodes by name, we use the
XML class's built-in properties, such as
firstChild and childNodes, to
access nodes. For example, to access the P node,
we could use:
myDocument.firstChild // Accesses P
myDocument.childNodes[0] // Also accesses P
Because firstChild returns a reference to the
first child node of the specified node in the hierarchy,
myDocument.firstChild returns a reference to node
P. However, we want the text "hello
world!" contained by P, not node
P itself. As we learned earlier, the text of an
element node is stored as a child of that node. Therefore, we can
reference the text node (i.e., the first descendant of
P), like this:
myDocument.firstChild.firstChild // Accesses the text node under P
To obtain the value of a node, we use the
nodeValue property. For example, we can display
the value "hello world!" in the Output window using:
trace(myDocument.firstChild.firstChild.nodeValue);
Or, we can reassign the value of the text node under
P using:
myDocument.firstChild.firstChild.nodeValue = "goodbye cruel world";
To remove the P node altogether, add a new node,
or move the text "hello world!" to another node, we
invoke appropriate methods of the XML class. For
example:
// Delete P
myDocument.firstChild.removeNode( );
// Make a new element named P
newElement = myDocument.createElement("P");
// Add the new element to our document
myDocument.appendChild(newElement);
// Make a new text node to attach to P
newText = myDocument.createTextNode("XML is fun");
// Attach the new text node to P
myDocument.firstChild.appendChild(newText);
As you can see, working with XML-structured data in an object
hierarchy is a mediated endeavor. We build, destroy, and manipulate
the data by invoking methods on, and accessing properties of,
objects. To learn the various tools available for working with XML
data, explore the properties and methods of the
XML class, which are listed next.
ActionScript manipulates XML data using the Document Object Model
(DOM) standard published by the World Wide Web Consortium (W3C). For
thorough coverage of how the DOM represents XML-structured data as an
object hierarchy, consult:
http://www.w3.org/DOM
For details on the language-independent specifications of the core
DOM, see:
http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html
(pay particular attention to "Interface Node" under 1.2,
Fundamental Interfaces). For details on
how the DOM is implemented in ECMA-262, see:
http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
Example
We've learned that the whitespace
between any two elements in XML source code
is represented by a text node in the corresponding
XML object hierarchy. Prior to Build 41 of the
Flash 5 Player, undesired whitespace nodes had to be manually
stripped out of an XML object hierarchy. Stripping a particular kind
of node is a common task in XML handling and serves as a good example
of tree traversal (moving through every node in
a hierarchy). Let's consider two different techniques for
stripping whitespace nodes from a document.
In the first example, we'll use a classic FIFO (First In First
Out) stack to add all the nodes in a tree to an array for processing.
The stripWhitespaceTraverse( ) function seeds an
array of node elements with theNode, which
it receives as an argument. Then it enters a loop in which it removes
the first node in the array, processes that node, and adds its
children (if any) to the array. When the array has no more elements,
all the descendants of theNode have been
processed. During processing, any node that has no children is
considered potential whitespace (because text nodes never have
children). Each of these nodes is checked to see if:
Any text nodes containing only characters below ASCII 32 (i.e., only
whitespace) are removed:
// Strip Whitespace Using a FIFO Stack
// Strips any whitespace nodes descending from theNode by traversing the tree
function stripWhitespaceTraverse (theNode) {
// Create a list of nodes to process
var nodeList = new Array( );
// Seed the list with the node passed to the function
nodeList[0] = theNode;
// Process descendants until there are none left to process
while (nodeList.length > 0) {
// Remove the first node from the list and assign it to currentNode
currentNode = nodeList.shift( );
// If this node has children...
if (currentNode.childNodes.length > 0) {
// ...add this node's children to the list of nodes to process
nodeList = nodeList.concat(currentNode.childNodes);
} else {
// ...otherwise, this node is the end of a branch, so check if it's a
// text node. If so, check if it contains only empty whitespace.
// nodeType 3 indicates a text node
if (currentNode.nodeType == 3) {
var i = 0;
var emptyNode = true;
for (i = 0; i < currentNode.nodeValue.length; i++) {
// A useful character is anything over 32 (space, tab,
// new line, etc. are all below).
if (currentNode.nodeValue.charCodeAt(i) > 32) {
emptyNode = false;
break;
}
}
}
// If no useful charaters were found, delete the node
if (emptyNode) {
currentNode.removeNode( );
}
}
}
}
The technique shown in the preceding example is traditionally very
efficient. However, in the Flash 5 Player, the
Array.concat( ) method executes quite slowly.
Hence, it's quicker to strip
whitespace using the
technique shown in the following example. Study the comments
carefully:
// Strip Whitespace Using Function Recursion
// Strips whitespace nodes from an XML document
// by passing twice through each level in the tree
function stripWhitespaceDoublePass(theNode) {
// Loop through all the children of theNode
for (var i = 0; i < theNode.childNodes.length; i++) {
// If the current node is a text node...
if (theNode.childNodes[i].nodeType == 3) {
// ...check for any useful characters in the node
var j = 0;
var emptyNode = true;
for (j = 0;j < theNode.childNodes[i].nodeValue.length; j++) {
// A useful character is anything over 32 (space, tab,
// new line, etc. are all below)
if (theNode.childNodes[i].nodeValue.charCodeAt(j) > 32) {
emptyNode = false;
break;
}
}
// If no useful charaters were found, delete the node
if (emptyNode) {
theNode.childNodes[i].removeNode( );
}
}
}
// Now that all the whitespace nodes have been removed from theNode,
// call stripWhitespaceDoublePass() recursively on its remaining children.
for (var k = 0; k < theNode.childNodes.length; k++) {
stripWhitespaceDoublePass(theNode.childNodes[k]);
}
}
See Also
The XMLnode
class, The XMLSocket
class; Section 18.5, "HTML Support" in Chapter 18, "On-Screen Text Fields"
XML.appendChild( ) Method | add a new child node to a node, or move an existing node
|
Availability
Flash 5
Synopsis
theNode.appendChild(childNode)
Arguments
- childNode
An existing XML node object.
Description
The appendChild( ) method adds the specified
childNode to
theNode as
theNode's last child. We can use
appendChild( ) to add a new node to an existing
node, to move a node within a document, or to move a node between
documents. In each of these cases,
childNode must be a reference to a node
object that already exists.
To add a new child node to an existing
node, we must first create the new child node using
createElement( ), createTextNode(
), or cloneNode( ) or by parsing XML
source code into an XML object. For example, in
the following code, we create a new P node and a
new text node. We append the text node to the P
node and then append the P node and its text node
child to the top node of a document:
// Create a document
myDoc = new XML('<P>paragraph 1</P>');
// Create a P node and a text node
newP = myDoc.createElement("P");
newText = myDoc.createTextNode("paragraph 2");
// Append the text node to the P node
newP.appendChild(newText);
// Append the P node (including its text child) to myDoc
myDoc.appendChild(newP);
trace(myDoc); // Displays: "<P>paragraph 1</P><P>paragraph 2</P>"
To move a node within a document, specify a
childNode that is a reference to an
existing node in the document. In this situation,
childNode indicates the old location of
the node, and theNode indicates the new
parent of the node. In the process of being appended to
theNode,
childNode is removed from its previous
parent node. For example, here we move the B node
from its parent P node to the root of the
document:
// Create a new document
myDoc = new XML('<P>paragraph 1<B>bold text</B></P>');
// Store a reference to the B node
boldText = myDoc.firstChild.childNodes[1];
// Append the B node to the root of the document, while removing it from P
myDoc.appendChild(boldText);
trace(myDoc); // Displays: "<P>paragraph 1</P><B>bold text</B>"
We also could have skipped the reference-storing step and just moved
the node directly:
myDoc.appendChild(myDoc.firstChild.childNodes[1]);
To move a node between
documents, childNode should be a reference
to a node in the first (source) document and
theNode should be a reference to a node in
the second (target) document. For example, here we move the
B node from myDoc to
myOtherDoc:
myDoc = new XML('<P>paragraph 1<B>bold text</B></P>');
myOtherDoc = new XML( );
myOtherDoc.appendChild(myDoc.firstChild.childNodes[1]);
trace(myDoc); // Displays: "<P>paragraph 1</P>"
trace(myOtherDoc); // Displays: "<B>bold text</B>"
See Also
XML.createElement( ),
XML.createTextNode( ), XML.cloneNodee(
), XML.insertBefore( )
XML.attributes Property | an object whose properties store element attributes
|
Availability
Flash 5
Synopsis
theNode.attributes.attributeIdentifier
theNode.attributes[attributeNameInQuotes]
Access
Read/write
Description
The attributes property stores the names and
values of attributes defined by theNode.
For example, the ALIGN attribute of this
P tag:
<P ALIGN="CENTER">this is a paragraph</P>
is accessed using
theNode.attributes.ALIGN
or
theNode.attributes["ALIGN"].
If the P tag were the only tag in our XML source,
we could access the ALIGN attribute as follows:
// Create an XML object hierarchy
myDoc = new XML('<P ALIGN="CENTER">this is a paragraph</P>');
// Access the ALIGN attribute. Displays: "CENTER"
trace(myDoc.firstChild.attributes.ALIGN);
// Set the ALIGN attribute
myDoc.firstChild.attributes.ALIGN = "LEFT";
The attributes property is itself an object. We
can add new properties to the attributes object,
thereby adding new attributes to theNode,
as follows:
// Add a CLASS attribute to the P tag
myDoc.firstChild.attributes.CLASS = "INTRO";
// firstChild now represents the XML source:
// <P ALIGN="CENTER" CLASS="INTRO">this is a paragraph</P>
Because attributes is not an array, it
doesn't contain a length property. Instead,
we can access all the attributes defined on an element using a
for-in loop:
var count = 0;
for(var prop in theNode.attributes) {
trace("attribute " + prop + " has the value " + theNode.attributes[prop]);
count++;
}
trace ("The node has " + count + " attributes.");
If the XML element represented by theNode
has no attributes, attributes is an empty object
with no properties and the preceding example would indicate zero
attributes.
See Also
XML.nodeType
XML.childNodes Property | an array of references to a node's children
|
Availability
Flash 5
Synopsis
theNode.childNodes[n]
Access
Read-only
Description
The childNodes property is an array whose elements
contain references to the immediate descendants of
theNode. It is used to access nodes in an
XML hierarchy. For example, if we create an object hierarchy as
follows:
myDoc = new XML('<STUDENT><NAME>Tim</NAME><MAJOR>BIOLOGY</MAJOR></STUDENT>');
We can then access the STUDENT node using:
myDoc.childNodes[0];
We can access the NAME and
MAJOR nodes (which are descendants of
STUDENT) using:
myDoc.childNodes[0].childNodes[0]; // NAME
myDoc.childNodes[0].childNodes[1]; // MAJOR
If the hierarchy below theNode changes,
childNodes is automatically updated to reflect the
new structure. For example, if we deleted the
MAJOR node,
myDoc.childNodes[0].childNodes[1] would return
undefined.
We often refer to nodes to manipulate information or rearrange a
document's structure. For example, we might change a
student's name or add a new student using:
// Check the name of the student
trace("The student's name is: "
+ myDoc.childNodes[0].childNodes[0].childNodes[0].nodeValue);
// Change the name of the student
myDoc.childNodes[0].childNodes[0].childNodes[0].nodeValue = "James";
// Copy the STUDENT node
newStudent = myDoc.childNodes[0].cloneNode(true);
// Add a new STUDENT node to the document
myDoc.appendChild(newStudent);
Note that as a convenience, we may also use the
firstChild property to refer to
childNodes[0]. The following references are
identical:
myDoc.childNodes[0];
myDoc.firstChild;
To iterate through all the children of a node, we can use a
for statement, as follows:
for (var i = 0; i < theNode.childNodes.length; i++) {
trace("child " + i + " is " + theNode.childNodes[i].nodeName);
}
However, our example traverses only the first level of
theNode's hierarchy. The examples
under the
XML.nextSibling entry
shows how to access all the nodes below
theNode. If
theNode has no children,
theNode.childNodes.length
is 0.
Usage
Remember that empty text nodes, representing the whitespace used to
format XML source code, also show up in a
childNode list. For example, in the following XML
source, empty text nodes will be created by the whitespace after the
BOOK start tag and the TITLE,
AUTHOR, and PUBLISHER end tags:
<BOOK>
<TITLE>ActionScript: The Definitive Guide</TITLE>
<AUTHOR SALUTATION="Mr">Colin Moock</AUTHOR>
<PUBLISHER>O'reilly</PUBLISHER>
</BOOK>
Hence, the first child node of BOOK is an empty
text node; the second child is TITLE.
See Also
XML.firstChild,
XML.hasChildNodes( ),
XML.lastChild,
XML.nextSibling,
XML.previousSibling
XML.cloneNode( ) Method | create a copy of a node
|
Availability
Flash 5
Synopsis
theNode.cloneNode(deep)
Arguments
- deep
A Boolean indicating whether to recursively include
theNode's children in the clone
operation. If true, clone the entire hierarchy
starting at theNode. If
false, clone only
theNode itself (and its attributes, if it
is an element node).
Returns
A duplicate of the theNode object,
optionally including its subtree.
Description
The cloneNode( ) method creates and returns a
copy of theNode, including all of
theNode's attributes and values if
theNode is an element node. If
deep is true, the
returned copy includes the entire node hierarchy descending from
theNode.
We often use cloneNode( ) to create a new node
based on an existing template (which saves us from generating the new
node structure manually). Once we've cloned a node, we normally
customize it and insert it into an existing XML document using either
appendChild( ) or insertBefore(
). The following example clones the first paragraph of a
document to make a sibling paragraph with the same structure:
// Create a new document
myDoc = new XML('<P>paragraph 1</P>');
// Make a clone of the first paragraph
newP = myDoc.firstChild.cloneNode(true);
// Customize the clone
newP.firstChild.nodeValue = "paragraph 2";
// Add the clone into the document
myDoc.appendChild(newP);
trace(myDoc); // Displays: "<P>paragraph 1</P><P>paragraph 2</P>"
Note that the text in an element is stored in a separate child node
of that element, so we must set deep to
true to preserve an element's text content
in a clone operation. Remember that cloneNode( )
does not insert the element it returns into the node's
document -- we must do that ourselves using appendChild(
) or insertBefore( ).
See Also
XML.appendChild( ), XML.createElement(
), XML.createTextNode( ),
XML.insertBefore( )
XML.contentType Property | MIME content type for XML data sent via XML.send( ) and XML.sendAndLoad( )
|
Availability
Flash 5 Build 41 or later
Synopsis
XMLdoc.contentType
Access
Read/write
Description
The contentType property is the MIME type that is
sent to a server when XML.send( ) or
XML.sendAndLoad( ) is invoked. It defaults to
application/x-www-urlform-encoded. The
contentType property may be
modified for specific XML objects, or
XML.prototype.contentType may
be modified to affect all XML objects.
The contentType property first appeared in Build
41 of the Flash 5 Player, before which it was not possible to set
MIME type. Check contentType's validity by
comparing it to undefined or using the
getVersion( ) function to determine the Player
version and build.
Usage
See important notes on setting MIME type under the
XML.send( ) entry.
See Also
XML.send( ), XML.sendAndLoad(
)
XML.firstChild Property | a reference to the first descendant of a node
|
Availability
Flash 5
Synopsis
theNode.firstChild
Access
Read-only
Description
The firstChild property is synonymous with
childNodes[0]. It returns a reference to the first
node object that descends from theNode. If
theNode has no children,
firstChild returns null.
In this XML source fragment, the firstChild of the
MESSAGE node is the text node with the
nodeValue "hey":
<!-- Fragment 1 -->
<MESSAGE>hey</MESSAGE>
Here, the firstChild of the
HOTEL node is the ROOM node:
<!-- Fragment 2 -->
<HOTEL><ROOM><SIZE>Double</SIZE></ROOM></HOTEL>
When theNode is the top of the object
hierarchy (i.e., refers to the XML document
object), firstChild may not always be a reference
to the first useful element in the document. If a document includes
an XML delcaration (<?xml
version="1.0"?>) and perhaps a
DOCTYPE tag, there are normally whitespace nodes
before the actual root element of the XML hierarchy. However, if an
XML fragment has no XML declaration and no
DOCTYPE, we can start processing it with the
document's firstChild node, as in:
// Create a new XML fragment
myDoc = new XML('<MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE>');
// Store the XML fragment's first node in the variable msg
msg = myDoc.firstChild;
// Assign the text contained by the USER tag
// to a text field called userNameOutput
userNameOutput = msg.firstChild.firstChild.nodeValue;
It's good form, but not actually necessary, to use
nodeValue to access the text contained by the
USER tag. When we use a text-node object in a
string context, the toString( ) method is
automatically invoked on that node, and the text in the node is
returned.
See Also
XML.childNodes,
XML.lastChild,
XML.nextSibling,
XML.previousSibling
XML.hasChildNodes( ) Method | check if a node has any descendants
|
Availability
Flash 5
Synopsis
theNode.hasChildNodes()
Returns
A Boolean: true if
theNode has any children;
false if it does not.
Description
The hasChildNodes( ) method indicates whether
any node hierarchy extends from a given node. It is synonymous with
the comparison expression:
theNode.childNodes.length > 0
If theNode contains no subnodes,
hasChildNodes( ) returns
false.
Example
We can use hasChildNodes( ) to determine whether
to operate on a node during node processing. For example, here we
remove the nodes below the first child of a document until the first
child has no more children:
while (myDoc.firstChild.hasChildNodes( )) {
myDoc.firstChild.firstChild.removeNode( );
}
See Also
XML.childNodes
XML.insertBefore( ) Method | give a node a new previous sibling
|
Availability
Flash 5
Synopsis
theNode.insertBefore(newChild, beforeChild)
Arguments
- newChild
An existing XML node object.
- beforeChild
The child of theNode before which
newChild should be inserted.
Description
The insertBefore( ) method adds
newChild to
theNode's child list, before
beforeChild . The insertBefore(
) method is similar to appendChild( )
but lets us precisely position a new node in an existing XML object
hierarchy.
Example
// Create a document
myDoc = new XML('<P>paragraph 2</P>');
// Create a P node and a text node
newP = myDoc.createElement("P");
newText = myDoc.createTextNode("paragraph 1");
// Append the text node to the P node
newP.appendChild(newText);
// Insert the new P node (including its text child) before the existing P
myDoc.insertBefore(newP, myDoc.firstChild);
trace(myDoc); // Displays: "<P>paragraph 1</P><P>paragraph 2</P>"
See Also
XML.appendChild( )
XML.lastChild Property | a reference to the last descendant of a node
|
Availability
Flash 5
Synopsis
theNode.lastChild
Access
Read-only
Description
The lastChild property is synonymous with
childNodes[childNodes.length-1]. It returns a
reference to the last node object that descends from
theNode. If
theNode has no children,
lastChild returns null.
In the following XML source fragment, the
lastChild of the MESSAGE node
is the CONTENT node:
<MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE>
Example
// Create a new XML document
myDoc = new XML('<MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE>');
// Sets msg to "hi" because myDoc's firstChild
// is MESSAGE, MESSAGE's lastChild is CONTENT, and CONTENT's firstChild
// is the text node with the value "hi"
msg = myDoc.firstChild.lastChild.firstChild.nodeValue
See Also
XML.childNodes,
XML.firstChild,
XML.nextSibling,
XML.previousSibling
XML.load( ) Method | import XML source code from an external document
|
Availability
Flash 5
Synopsis
XMLdoc.load(URL)
Arguments
- URL
A string specifying the location of the XML document to load.
Description
The load( )
method imports an external XML document, parses it, converts it into
an XML object hierarchy, and places that hierarchy into
XMLdoc. Any previous contents of
XMLdoc are replaced by the newly loaded
XML content.
XMLdoc must be an instance of the
XML class, not the XMLnode
class.
Usage
Before accessing content imported with load( ),
we must be sure the load and parsing operations are complete. To do
so, either check the value of the XML document's
loaded property, or assign the document an
onLoad( ) callback handler to respond to the
load completion. See the
XML.loaded and
XML.onLoad( ) entries for details. To determine
whether the loaded data was successfully parsed, check the
document's status property.
XML.load( ) is subject to the domain-based
security restrictions described in Table 20-8 under
the global loadVariables( ) function.
Example
myDoc = new XML( );
myDoc.load("myData.xml");
See Also
XML.loaded,
XML.onLoad( ), XML.sendAndLoad(
),
XML.status
XML.loaded
Property | status of a load( ) or sendAndLoad( ) operation
|
Availability
Flash 5
Synopsis
XMLdoc.loaded
Access
Read-only
Description
The loaded property returns a Boolean value
indicating whether a previously invoked load( )
or sendAndLoad( ) operation on
XMLdoc has completed. It is immediately
set to false when an XML load(
) or sendAndLoad( ) operation is
initiated. If the load is successful, loaded is
later set to true. If no such operation has ever
been executed on XMLdoc,
loaded is undefined.
When loaded is false, the
download and parsing of XML data is still in progress, and attempts
to access the object hierarchy in XMLdoc
will fail. When loaded is true,
XML data has finished being downloaded, parsed, and stored in
XMLdoc as an object hierarchy. Note,
however, that the loaded XML data may not have been parsed
successfully (use
XMLdoc.status to
determine whether it was).
XMLdoc must be an instance of the
XML class, not the XMLnode
class.
Example
The following example shows a basic XML
preloader that waits for the XML
data to be loaded before displaying it (XML preloaders may also be
built using an XML.onLoad( ) handler):
// CODE ON FRAME 1
// Create a new XML document
myDoc = new XML( );
// Load an external XML file into the document
myDoc.load("userProfile.xml");
// CODE ON FRAME 5
// Check if the data has loaded. If so, go to the display frame.
// If not, loop back to frame 4 and then play.
// Loop until the data is done loading...
if (myDoc.loaded) {
if (myDoc.status == 0) {
gotoAndStop("displayData");
} else {
gotoAndStop("loadingError");
}
} else {
gotoAndPlay(4);
}
See Also
XML.load( ), XML.onLoad( ),
XML.sendAndLoad( )
XML.nextSibling Property | a reference to the node after this node
|
Availability
Flash 5
Synopsis
theNode.nextSibling
Access
Read-only
Description
The nextSibling property returns the node object
after theNode in the current level of the
XML object hierarchy. If there is no node after
theNode, nextSibling
returns null. In the following XML source
fragment, the CONTENT node is the
nextSibling of the USER node:
<MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE>
Example
The nextSibling property is typically used to
traverse (move through) an XML object hierarchy.
For example, to view all the children of
theNode in the order they appear, we may
use:
for (var child = theNode.firstChild; child != null; child = child.nextSibling) {
trace("found node: " + child.nodeName);
}
By extending our loop into a function, we can recursively traverse
every node in an XML object hierarchy, as follows:
function showNodes (node) {
trace(node.nodeName + ": " + node.nodeValue);
for (var child = node.firstChild; child != null; child = child.nextSibling) {
showNodes(child);
}
}
// Invoke the function on our node or document
showNodes(myDoc);
Note that in both traversal examples shown, text nodes show up
without a name as described under the nodeName
entry.
See Also
XML.childNodes,
XML.firstChild,
XML.lastChild,
XML.nodeName,
XML.nodeValue,
XML.previousSibling
XML.nodeName Property | the name of the current node
|
Availability
Flash 5
Synopsis
theNode.nodeName
Access
Read/write
Description
The nodeName string property reflects the name of
theNode. Since only two node types are
supported by ActionScript (element nodes and
text nodes), nodeName has
only two possible values:
If theNode is an element node,
nodeName is a string matching the tag name of that
element. For example, if theNode
represents the element <BOOK>, then
theNode.nodeName is
"BOOK".
If theNode is a text node,
nodeName is null. Note that
this diverges from the DOM specification, which stipulates that
nodeName for a text node should be the string
"#text". If you prefer, you can use the
DOM-compliant nodeType property instead.
Example
We can use nodeName to check whether the current
node is the type of element we're seeking. For example, here we
extract all the content of H1 tags on the first
level of an XML document (this example checks only for tags named
H1, not for tags named h1
with a lowercase h):
myDoc = new XML('<H1>first heading</H1><P>content</P>' +
'<H1>second heading</H1><P>content</P>');
for (i = 0; i < myDoc.childNodes.length; i++) {
if (myDoc.childNodes[i].nodeName == "H1") {
trace(myDoc.childNodes[i].firstChild.nodeValue);
}
}
See Also
XML.nodeType,
XML.nodeValue
XML.nodeType Property | the type of the current node
|
Availability
Flash 5
Synopsis
theNode.nodeType
Access
Read-only
Description
The nodeType is an integer
property that returns theNode's
type. Since only two node types are supported by
ActionScript -- element nodes and text
nodes -- nodeName has only two possible values:
1, if the node is an element node; and 3, if the node is a text node.
These values may seem arbitrary, but they are actually the
appropriate values as stipulated by the DOM. For reference, the other
node types in the DOM are listed in Table 20-13.
Table 20-13. DOM Node Types
*Supported by Flash. Technically, ActionScript implements so-called
attribute, document, and
document_type nodes in addition to
element and text nodes, but
we don't have direct access to them as objects. For example, we
may manipulate the attributes of a node through the
attributes property, but we do not have direct
access to attribute nodes themselves. Similarly,
we have access to the DOCTYPE tag of a document
through the docTypeDecl property, but we do not
have direct access to document_type itself.
Element nodes correspond to XML or HTML tags.
For example, in the XML fragment <P>what is your
favorite color?</P>, the P tag
would be represented in an XML object hierarchy
as an element node (nodeType 1). The text
contained by a tag in XML source code -- for example, the text
"what is your favorite color?" -- would be represented
as a text node (nodeType 3).
Example
We can conditionally operate on a node based on its
nodeType. For example, here we remove all the
empty text nodes that are children of theNode
:
// Loop through all children of theNode
for (i = 0; i < theNode.childNodes.length; i++) {
// If the current node is a text node...
if (theNode.childNodes[i].nodeType == 3) {
// Check for any useful characters in the node
var j = 0;
var emptyNode = true;
for (j = 0; j < theNode.childNodes[i].nodeValue.length; j++) {
// Useful character codes start above ASCII 32
if (theNode.childNodes[i].nodeValue.charCodeAt(j) > 32) {
emptyNode = false;
break;
}
}
// No useful charaters were found, so delete the node
theNode.childNodes[i].removeNode( );
}
}
See Also
The XML Class,
XML.nodeName,
XML.nodeValue
XML.nodeValue
Property | the value of the current node
|
Availability
Flash 5
Synopsis
theNode.nodeValue
Access
Read/write
Description
The nodeValue property reflects the string value
of theNode. Since only two node types
(element nodes and text
nodes) are supported by ActionScript, nodeValue
has only two possible values:
In practice, nodeValue is normally used only with
text nodes. To assign new text to an existing text node, we use
nodeValue as follows:
// Create a new XML document
myDoc = new XML('<H1>first heading</H1><P>content</P>');
// Change the text contained by the H1 tag
myDoc.firstChild.firstChild.nodeValue = "My Life Story";
Although we may explicitly retrieve the value of a text node using
nodeValue, the toString( )
method implicitly returns a node's value when it is used in a
string context. Therefore, this code displays the text node's
text in the Output window:
trace(myDoc.firstChild.firstChild);
See Also
XML.nodeName,
XML.nodeType
XML.onData( ) Event Handler | executed when external XML source code finishes loading, but has not yet been parsed
|
Availability
Flash 5 (undocumented)
Synopsis
XMLdoc.onData(src);
Arguments
- src
A string containing the loaded XML source code.
Description
The onData( ) handler executes automatically
whenever raw XML source has finished loading into
XMLdoc due to an earlier load(
) or sendAndLoad( ) invocation. By
default, onData( ) has the following behavior:
Otherwise, it parses the source into
XMLdoc, sets
XMLdoc.loaded to true, and
calls XMLdoc.onLoad( ) with the
success parameter set to true.
The onData( ) handler may be assigned a custom
callback function to intercept raw XML source code before
ActionScript has a chance to parse it. Under certain circumstances,
manipulating raw XML source manually may offer improved performance
over ActionScript's built-in parsing.
Example
The following example shows how to display raw loaded XML source
while preventing it from being parsed by ActionScript:
myDoc = new XML();
myDoc.onData = function (src) {
trace("Here's the source: \n" + src);
};
myDoc.load("book.xml");
See Also
XML.onLoad( )
XML.onLoad( ) Event Handler | executed when external XML data has been loaded and parsed
|
Availability
Flash 5
Synopsis
XMLdoc.onLoad(success)
Arguments
- success
A Boolean value indicating whether loading was successful
(true) or failed (false).
Description
The onLoad( ) handler of
XMLdoc is automatically executed whenever
an external XML file is loaded into XMLdoc
via the load( ) or sendAndLoad(
) methods. By default, the onLoad( )
handler of an XML document object is an empty function. To use
onLoad( ), we assign it a
callback handler
(i.e., a custom-made function). For example:
myDoc = new XML( );
myDoc.onLoad = handleLoad;
function handleLoad (success) {
// Process XML as desired here...
}
We rely on onLoad( ) events to tell us when
it's safe to process XMLdoc. If
onLoad( ) is triggered, we know that the loading
and parsing of external XML data have completed, so we may safely
access that loaded content. The onLoad( )
handler, hence, alleviates the need to write preloading code to wait
for data to arrive after the invocation of an XML load(
) function. For example, in the following code we load an
XML document, and then we wait for our custom handleLoad(
) function to be automatically executed when loading
completes. If loading was successful, we process our XML content with
the display( ) function. Otherwise, we show an
error message by executing the display( )
function. (The displayProduct( ) and
displayError( ) functions are custom functions
that you've presumably written to display information to the
user, but they are not shown.)Here is the code:
myDoc = new XML( );
myDoc.onLoad = handleLoad;
myDoc.load("productInfo.xml");
function handleLoad(success) {
if (success) {
output = "Product information received";
displayProduct( ); // Call custom display function
} else {
output = "Attempt to load XML data failed";
displayError( ); // Call custom display function
}
}
Notice that the value of the success argument of
handleLoad( ) is automatically set by the
interpreter to either true or
false, indicating whether or not loading completed
properly. However, the success argument may appear
more useful in theory than it turns out to be in practice. Most web
server error messages (e.g., "404 File Not Found") come
in the form of HTML documents. Since HTML can quite happily be parsed
as XML data, the reception of a server error page results in the
parsing of that page into the target XML document object. Because the
page parses properly, the load attempt is considered
"successful," and success is
true, even though the actual XML file may not have
been found or some other server error may have been encountered. To
be positive that you have the real data you requested, test its
structure or content explicitly for some identifying characteristic,
such as the nodeName of a particular child. See
also the XML.onData( ) event handler, which can
be used to perform custom parsing.
See Also
XML.load( ), XML.onData( ),
XML.sendAndLoad( )
XML.parentNode Property | a reference to the immediate ancestor of a node
|
Availability
Flash 5
Synopsis
theNode.parentNode
Access
Read-only
Description
The parentNode property returns a reference to the
node object from which theNode descends in
the XML object hierarchy. If theNode is
the top of the current hierarchy, parentNode
returns null.
In this XML source fragment, the MESSAGE node is
the parentNode of text node
"hey":
<MESSAGE>hey</MESSAGE>
Here the parentNode of the ROOM
node is the HOTEL node:
<HOTEL><ROOM><SIZE>Double</SIZE></ROOM></HOTEL>
See Also
XML.childNodes,
XML.firstChild,
XML.lastChild,
XML.previousSibling
XML.parseXML( ) Method | parse a string of XML source code
|
Availability
Flash 5
Synopsis
XMLdoc.parseXML(string)
Arguments
- string
A string of XML source code.
Description
The parseXML( ) method is akin to an internal
load( ) function; it reads and parses the XML
source contained by string, converts that
XML into an object hierarchy, and then places the resulting hierarchy
into XMLdoc. Any previous contents of
XMLdoc are replaced by the new hierarchy.
XMLdoc must be an instance of the
XML class, not the XMLnode
class.
To include raw HTML or XML source code in a text node without parsing
it, use a CDATA section as follows:
<![CDATA[ source ]]>
For example, the following code creates a MESSAGE
element with a single child text node containing the text
"<B>Welcome</B> to my site" (the
<B> tag is not
interpreted as an XML tag and does not become part of the XML object
hierarchy):
myDoc = new XML( );
myDoc.parseXML("<MESSAGE><![CDATA[<B>Welcome</B> to my site]]></MESSAGE>");
trace(myDoc); // Displays: "<MESSAGE><B>Welcome</B> to my site</MESSAGE>"
Example
We can use parseXML( ) as a means of replacing
the current object hierarchy in an XML object
with a new hierarchy based on internally composed XML source code
(for example, some user input). In the following example, we create a
simple XML message by combining markup with input from text fields
named username and content:
myDoc = new XML( );
myXMLsource = "<MESSAGE><USER>" + username + "</USER><CONTENT>"
+ content + "</CONTENT></MESSAGE>";
myDoc.parseXML(myXMLsource);
See Also
XML.load( ),
XML.status
XML.previousSibling Property | a reference to the node before this node
|
Availability
Flash 5
Synopsis
theNode.previousSibling
Access
Read-only
Description
The previousSibling property returns a reference
to the node object preceding theNode in
the current level of the XML object hierarchy. If there is no node
before theNode in the current level of the
hierarchy, it returns null.
In the following XML source fragment, the
previousSibling of the CONTENT
node is the USER node:
<MESSAGE><USER>gray</USER><CONTENT>hi</CONTENT></MESSAGE>
Example
The previousSibling property can be used to
traverse an XML object hierarchy, although
nextSibling is more commonly used for this
purpose. To view all the children of
theNode in reverse order, we may use:
for (var i = theNode.lastChild; i != null; i = i.previousSibling) {
trace("found node: " + i.nodeName);
}
See Also
XML.childNodes,
XML.firstChild,
XML.lastChild,
XML.nextSibling,
XML.nodeName,
XML.nodeValue,
XML.parentNode
XML.send( ) Method | send XML source code to a script
|
Availability
Flash 5
Synopsis
XMLdoc.send(URL, window)
Arguments
- URL
A string specifying the location of a script or application to which
XMLdoc should be sent.
- window
A required string, specifying the name of the browser window or frame
into which to load the script's response. May be a custom name
or one of the four presets: "_blank", "_
parent", "_self", or
"_top". For details, see the description of the
window settings under the global getURL( )
function.
Description
The send( ) method converts
XMLdoc into a string of XML source code
and sends that code in an HTTP request to the script or application
residing at URL. The script or application
is expected to process the XML in some way and optionally return a
response -- normally a web page -- to the browser, which
displays it in window. Note that the
response is not caught by Flash but by the browser; use
sendAndLoad( ) to catch the response within
Flash.
When XML.send( ) is invoked from the Flash
Player running in a browser,
XMLdoc is sent via the POST method. When
XML.send( ) is invoked from the Flash Player
running as a standalone application,
XMLdoc is sent via the GET method. The
server application receiving the posted XML string must be able to
access the raw POST data of the HTTP request directly and should not
attempt to parse it as normal name/value pairs. In Perl, the data in
a POST request is available from STDIN, and may be extracted and
stored in, say, $buffer as follows:
read(STDIN,$buffer,$ENV{'CONTENT_LENGTH'});
In ASP, raw POST data may be accessed via the
Request.BinaryRead method. Some applications
(e.g., Cold Fusion) may not have a direct means of accessing the data
in a POST request. For these situations, it may be necessary to first
convert the XML object to a string using XML.toString(
) and then pass that string to the server as a variable
using loadVariables( ).
The default MIME
content type of the XML text sent to the server is
application/x-www-urlform-encoded. This type,
however, is only cosmetic -- the text itself is
not URL-encoded. In Build 41 and later of the
Flash 5 Player, the MIME content type can be modified using the
XML.contentType property. For example, to set the
MIME type to application/xml, we use:
myXML = new XML( );
myXML.contentType = "application/xml";
Nevertheless, setting the contentType property
explicitly to application/x-www-urlform-encoded
still does not cause the text sent to be URL-encoded.
Note that as of Build 41 of the Flash 5 Player, when XML source is
parsed and the characters &,
', ", <,
and > appear in a text node, they are converted
to the following entities: &,
', ",
>, <. This
conversion is transparent in Flash because the entities are converted
back to their original characters when an XML object is converted to
a string; however, the entities will show up in
XML source sent to the server.
Example
myDoc = new XML("<SEARCH_TERM>tutorials</SEARCH_TERM>");
myDoc.send("http://www.domain.com/cgi-bin/lookup.cgi", "remoteWin");
See Also
XML.sendAndLoad( ),
XML.load( ),
XML.loaded,
XML.onLoad( ),
XML.status
XML.sendAndLoad( ) Method | send XML source code to a script, and receive XML source in return
|
Availability
Flash 5
Synopsis
XMLdoc.sendAndLoad(URL, resultXML)
Arguments
- URL
A string specifying the location of a script or application to which
XMLdoc should be sent.
- resultXML
A reference to an XML document object that will
receive the returned XML source code.
Description
The sendAndLoad( ) method serializes
XMLdoc into a string of XML source code
and sends that code to a script or application that resides at
URL. The script or application is expected
to process the XML in some way and send an XML document back as a
response. The response document is caught by Flash, parsed, converted
into an XML object hierarchy, and placed in
resultXML. Any previous contents of
resultXML are replaced by the newly loaded
XML content. See XML.send( ) for important
information about sending XML to a server.
Usage
Before accessing content imported with sendAndLoad(
), we must be sure that the load and parsing operations
are complete. To do so, we either check the value of the
resultXML's
loaded property or we assign
resultXML an onLoad(
) event handler to respond to the load completion. See the
XML.loaded and
XML.onLoad( ) entries for details. To determine
the result of parsing the loaded data, we check the document's
status property.
XML.sendAndLoad( ) is subject to the
domain-based security restrictions described in Table 20-8 under the global loadVariables(
) function.
Example
// Create an XML document
myDoc = new XML("<P>hello server!</P>");
// Create an empty XML document to receive the server's response
serverResponse = new XML( );
// Send myDoc to the server, and place the response in serverResponse
myDoc.sendAndLoad("http://www.domain.com/cgi-bin/readData.cgi", serverResponse);
// Add an onLoad handler to serverResponse that displays the response
// from the server in the text field output.
serverResponse.onLoad = function ( ) {
output = serverResponse.toString( );
}
For a good primer on sending XML to and from a server, see
Macromedia's article "Integrating XML and Flash in a Web
Application," at:
http://www.macromedia.com/support/flash/interactivity/xml
See Also
XML.load( ),
XML.loaded,
XML.onLoad( ), XML.send(
),
XML.status
XML.status Property | indicates whether parsing XML source into an object hierarchy was successful
|
Availability
Flash 5
Synopsis
XMLdoc.status
Access
Read-only
Description
The status property returns a numeric status code
indicating whether any errors were encountered when parsing XML
source code. Parsing occurs when source XML is:
The status codes are
shown in Table 20-14. If no errors were encountered
in parsing, success is indicated by a status of 0.
Errors are indicated by negative numbers. Parsing terminates once the
first error is encountered, so other errors may surface even after
you address previously reported errors.
Table 20-14. XML Parsing Status Codes
Status |
Description |
0 |
The document parsed without errors (i.e., success). |
-2 |
A CDATA section was not properly terminated. |
-3 |
The XML declaration was not properly terminated. |
-4 |
The DOCTYPE declaration was not properly
terminated. |
-5 |
A comment was not properly terminated. |
-6 |
An XML element was malformed. |
-7 |
Not enough memory to parse the XML source. |
-8 |
An attribute value was not properly terminated. |
-9 |
A start tag had no corresponding end tag. |
-10 |
An end tag had no corresponding start tag. |
We normally use status to determine whether
it's safe to proceed with processing an externally loaded XML
file. Check the loaded property to
ensure that a load( ) or sendAndLoad(
) command has completed before checking the
status. Note that ActionScript's XML parser
does not validate documents against DTDs, it only verifies
well-formedness.
Example
myDoc = new XML("<BOOK>Colin Moock</AUTHOR></BOOK>");
trace(myDoc.status); // Displays: "-10" (missing start tag)
See Also
XML.load( ),
XML.loaded,
XML.onLoad( ), XML.parseXML(
), XML.sendAndLoad( )
XMLnode Class | Internal superclass of the XML class
|
Availability
Flash 5
Description
The XMLnode class
defines the core properties and methods of nodes in an
XML object hierarchy. Though
XMLnode is an internal device, it may be used by
programmers to extend the default functionality of XML objects.
Every XML object hierarchy technically includes two kinds of object
nodes:
The main container node is an instance of the
XML class. For example, if we create
myDoc as follows:
myDoc = new XML();
then myDoc is an instance of the
XML class. The XML class
inherits from the XMLnode class, so main
container nodes have all the properties and methods defined by
XMLnode plus those defined by
XML. By contrast, the children of
myDoc would actually be instances of the
XMLnode class, not the XML
class.
So, if we create myParagraph as follows:
myParagraph = myDoc.createElement("P");
then myParagraph is an instance of the
XMLnode class. Most of the time the internal
distinction between node classes does not affect our use of XML
objects. However, if we wish to add an inherited property or method
to all XML objects, then we must use the XMLnode
class's prototype, not the
XML class's prototype
(see the example that follows). Any methods or properties attached to
XMLnode.prototype are inherited by all XML nodes
in a movie.
For reference, the properties, methods, and event handlers defined by
XMLnode and XML are listed
in Table 20-15. Note that while all listed items are
accessible through instances of the XML class,
items defined by XML are not available through
instances of XMLnode. For example, the
load( ) method may be invoked on an instance of
the XML class, but not on an instance of the
XMLnode class. For a full discussion of each
item, see the appropriate XML class entry.
Table 20-15. XMLnode and XML Properties, Methods, and Event Handlers
XMLnode and XML |
XML only |
appendChild( ) |
contentType |
attributes |
createElement( ) |
childNodes |
createTextNode( ) |
cloneNode( ) |
docTypeDecl |
firstChild |
ignoreWhite |
hasChildNodes( ) |
load( ) |
insertBefore( ) |
loaded |
lastChild |
onData( ) |
nextSibling |
onLoad( ) |
nodeName |
parseXML( ) |
nodeType |
send( ) |
nodeValue |
sendAndLoad( ) |
parentNode |
status |
previousSibling |
xmlDecl |
removeNode( ) |
|
toString( ) |
|
Example
The following code adds a custom secondChild( )
method to XMLnode.prototype (the
secondChild( ) method is subsequently available
from any XML node in our movie):
XMLnode.prototype.secondChild = function () {
return this.childNodes[1];
};
myDoc = new XML("<PRODUCT>Cell Phone</PRODUCT><PRODUCT>Game Console </PRODUCT>");
trace(myDoc.secondChild()); // Displays: "<PRODUCT>Game Console</PRODUCT>"
It's also perfectly legitimate to extend the
XML class via XML.prototype,
but such extensions apply only to main container nodes (direct
instances of the XML class).
See Also
The XML Class; Section 12.5.4, "Superclasses and Subclasses" in Chapter 12, "Objects and Classes".
XMLSocket Class | support for a continuous server/client TCP/IP connection
|
Availability
Flash 5
Constructor
new XMLSocket()
Methods
- close( )
Terminate an open connection to a server application.
- connect( )
Attempt to establish a new connection to a server application.
- send( )
Send an XML object hierarchy to a server application as a string.
Event handlers
- onClose( )
Executes when the server terminates the connection.
- onConnect( )
Executes when a connection attempt completes.
- onData( )
Executes when data is received but has not yet been parsed as XML.
- onXML( )
Executes when data has been received and parsed into an XML object
hierarchy.
Description
The majority of connections between Flash and a server have a very
short life span. When Flash requests external data via the
loadMovie( ), loadVariables(
), or XML.load( ) functions, a
temporary communication channel is established. Data is sent over
that channel and then the channel is terminated. This kind of
short-term communication has many useful applications, but it is also
limited in two important ways:
As of Flash 5, we can overcome these limitations with the
XMLSocket class, which allows us to open a
persistent communication link between a server application and Flash.
We use XMLSocket to develop systems that require
frequent server updates, such as a chat room or a networked
multiplayer game.
In order to connect to a remote application using
XMLSocket, we must first create and store an
XMLSocket object, like this:
mySocket = new XMLSocket( );
Then, we invoke the connect( ) method, which
asks Flash to establish a communication link with the remote
application. For example:
mySocket.connect("http://www.myserver.com", 8000);
Once a connection is established, the XMLsocket
object acts as a transmitter/receiver. We send XML-formatted data to
the remote application by invoking the socket's send(
) method, and we know that we've received
XML-formatted data when the socket's onXML(
) event is triggered.
A server application used with an XMLSocket
object must:
Server applications are typically created by server-side programmers,
not Flash programmers. For an example of a simple server application
that broadcasts all messages it receives to all connected clients,
see the Java XMLSocket server available at the online Code Depot.
An XMLSocket connection stays open until one of
the following occurs:
Thankfully, the XMLSocket class also provides a
way for us to monitor the status of our connection. It includes three
properties -- onClose,
onConnect, and
onXML -- that
allow us to define event handlers that will be triggered when the
corresponding event occurs. Such handlers are typically known as
callback
handlers because they are triggered automatically by Flash
in response to some event beyond the programmer's direct
control. (In this sense they are very similar to ActionScript's
built-in clip and button event handlers, except that the handler
functions are programmer-defined.) For example, when a connection is
closed by the server, the handler defined by the
onClose property will be triggered.
TIP
If you fail to define callback handlers for the
onClose and
onConnect properties, you won't be
able to perform any error checking or provide any feedback. If you
fail to define a callback handler for your
onXML property, you won't be
notified when the socket receives data from a server-side
application, nor will you be able to retrieve such data.
Example
The following example shows the bare-bones code needed to implement a
simple chat client. The client may be seen in action running at:
http://www.moock.org/chat
Both the server and the client are available at the online Code Depot:
// A Simple Chat Client
// *** General init
var incomingUpdated = false; // Track whether or not we need to scroll
// to the end of incoming (the main
// chat text field)
var incoming = ""; // Assign the main chat text field a starting value
// Attach the scroll manager movie. It forces the chat text field to
// show the next (most recent) line each time a message is added.
// Note that we only need the scroll manager because of a
// text field scroll bug in Build r30 of the Flash 5 Player.
attachMovie("processScroll", "processScroll", 0);
// Attach sound to play when we receive a message
var click = new Sound( );
click.attachSound("click");
// Attach sound to play when user joins or leaves
var welcomeSound = new Sound( );
welcomeSound.attachSound("welcome");
// Turn off ugly yellow highlight on buttons
_focusrect = 0;
// *** Creates a new socket and attempts to connect to the server
function connect ( ) {
// Create a new XMLSocket object
mySocket = new XMLSocket( );
// Assign callback functions to mySocket's handlers.
mySocket.onConnect = handleConnect;
mySocket.onClose = handleClose;
mySocket.onXML = handleIncoming;
// Attempt to connect, and assign the return of mySocket.connect()
// to connectSuccess (connect() returns true if the initial stage
// of connection succeeds)
var connectSuccess = mySocket.connect("www.myserver.com", 1025);
if (connectSuccess) {
trace("initial connection succeeded");
} else {
// connectSuccess was false, so we didn't establish a connection.
gotoAndStop("connectionFailed");
trace("initial connection failed");
}
}
// *** Event handler to respond to the completion of a connection attempt
function handleConnect (succeeded) {
// If handleConnect()'s succeeded argument is true, the connection has been
// established and we can proceed with the chat.
// Otherwise, show a failure message.
if (succeeded) {
// Set a property noting that we have an open connection available.
mySocket.connected = true;
gotoAndStop("chat");
// Put the cursor in the "send message" text field
Selection.setFocus("_level0.outgoing");
} else {
// Connection didn't succeed so show an error message
gotoAndStop("connectionFailed");
trace("connection failed");
}
}
// *** Event handler called when server kills the connection
function handleClose ( ) {
// Tell the user that the connection was lost
incoming += ("The server has terminated the connection.\n");
// We updated the chat text field, so let the scroll manager know
incomingUpdated = true;
// Set a property noting that the connection was lost
mySocket.connected = false;
numClients = 0;
}
// *** Event handler to receive and display incoming messages
function handleIncoming (messageObj) {
// Display the received XML data in the Output window
trace("--------new data received-----------");
trace(">>" + messageObj.toString( ) + "<<");
trace("-------- end of new data -----------");
// We're updating the chat text field, so let the scroll manager know
incomingUpdated = true;
lastScrollPos = incoming.scroll;
// Check the time
var now = new Date( );
var hours = now.getHours( );
var minutes = now.getMinutes( );
var seconds = now.getSeconds( );
// Format time for output
hours = (hours < 10 ? "0" : "") + hours;
minutes = (minutes < 10 ? "0" : "") + minutes;
seconds = (seconds < 10 ? "0" : "") + seconds;
// The server sends NUMCLIENTS any time a client connects or disconnects
// If we find NUMCLIENTS in the XML object...
if (messageObj.firstChild.nodeName == "NUMCLIENTS") {
// ...then check if the incoming messages window is empty. If it is...
if (incoming == "") {
// ...then the user has just joined, so add a welcome message to the chat.
incoming += ("welcome to moock comm 1.0.0, "
+ userID + "\n"
+ " connection time: " + hours + ":" + minutes + ":" + seconds + "\n"
+ " server: clayton\'s javaComm generic flash xmlsocket server\n\n");
} else {
// Otherwise, someone has arrived or departed, so tell the user
if (parseInt(messageObj.firstChild.firstChild.nodeValue) > numClients) {
// Report the client arrival in the chat window
incoming += (hours + ":" + minutes + ":"
+ seconds + " a new user has connected.\n");
} else {
// Report the client departure in the chat window
incoming += (hours + ":" + minutes + ":"
+ seconds + " a user disconnected.\n");
}
}
// Finally, keep track of the new number of clients
// and play a welcome/departure sound
numClients = parseInt(messageObj.firstChild.firstChild.nodeValue;)
welcomeSound.setVolume(100);
welcomeSound.start( );
} else {
// No NUMCLIENTS node was found, so this is just a regular message.
// Grab the user name and message from our XML object.
var user = messageObj.firstChild.firstChild.nodeValue;
var message = messageObj.childNodes[1].firstChild.nodeValue;
// Add the message to the chat window, with a time stamp
incoming += (hours + ":" + minutes
+ ":" + seconds + user + ">> " + message + "\n");
// Now do the new message click.
// If it's been more than 30 secs since the last message,
// sound a loud click. Otherwise sound a quiet click.
trace("time since last message: " + (now - lastIncomingMessageTime));
if (lastIncomingMessageTime && (now - lastIncomingMessageTime) > 30000) {
click.setVolume(200);
} else {
click.setVolume(30);
}
click.start( );
}
// Truncate the contents of the main chat text
// field if it's longer than 5000 characters
if (incoming.length > 5000) {
var nearestNewline = incoming.indexOf("\n", incoming.length - 5000);
incoming = incoming.substring(nearestNewline, incoming.length);
}
// Remember when this message arrived for next time
lastIncomingMessageTime = now;
}
// *** Sends a new XML object to the server
function sendMessage( ) {
// Create the message to send as an XML source fragment.
// Note that the spaces before the <USER> and </MESSSAGE> tags
// are required so MESSAGE and USER always have a text child node.
var message = '<USER> ' + userID + '</USER><MESSAGE>'
+ outgoing + ' </MESSAGE>';
// Convert the message into an XML object hierarchy
messageObj = new XML( );
messageObj.parseXML(message);
// Check what we're sending
trace("Sending: " + messageObj);
// If a socket object has been created and is connected, send the XML message.
// Otherwise warn the user that he needs to connect first.
if (mySocket && mySocket.connected) {
mySocket.send(messageObj);
// Clear the "send message" text field
outgoing = "";
} else {
// The server must have kicked us off...
incoming += "You are no longer connected. Please reconnect.\n"
incomingUpdated = true;
}
}
// *** Closes the connection to the server
function quit( ) {
if (mySocket.connected) {
mySocket.close( );
mySocket.connected = false;
numClients = 0;
incoming = "";
gotoAndStop("login");
}
}
See Also
oadVariables(
), The XML Class
XMLSocket.close( )
Method | terminate an open connection to a server application
|
Availability
Flash 5
Synopsis
socket.close()
Description
The close( ) method severs the communication
link between socket and a server
application. Once close( ) has been executed on
socket, subsequent attempts to invoke
send( ) on socket
fail. Likewise, the server application will no longer be able to send
data to Flash through socket.
Note that close( ) has no effect if the
socket is already closed or was never
connected. Furthermore, close( ) does not
trigger the onClose( ) handler of the socket
object -- onClose( ) is triggered only by a
server-side connection closure.
See Also
XMLSocket.connect( ),
XMLSocket.onClose( )
XMLSocket.connect( )
Method | open a connection to a server application
|
Availability
Flash 5
Synopsis
socket.connect(host, port)
Arguments
- host
A string specifying a hostname such as
"www.myserver.com" or a standard IP address (four,
dot-separated, 8-bit, decimal integers such as 111.222.3.123). If
null or an empty string is specified, it defaults
to the server address from which the movie was served.
- port
An integer specifying a TCP port number greater than or equal to 1024.
Returns
A Boolean indicating the initial success (true) or
failure (false) of the connection attempt.
Description
The connect( ) method attempts to establish a
connection from Flash to a server application running on
host at port.
If connect( ) returns true,
the initial phase of the connection completed successfully and the
socket's onConnect(
) handler will be invoked at a later time. From the
onConnect( ) handler, we can evaluate whether
the connection was fully established. Note that connection attempts
can take varying amounts of time, particularly when a connection
attempt fails. You should indicate to the user that a connection
attempt is in progress when invoking connect( ).
If connect( ) returns false,
the initial connection phase did not complete successfully. In such a
case, socket's onConnect(
) handler will not be invoked.
It is important to check both the return value of the
connect( ) method and, if connect(
) returns true, the value of the
success parameter of the
onConnect( ) handler.
Usage
For security reasons, connect(
) is not permitted to connect to arbitrary Internet hosts.
It may connect only to hosts in the domain that the movie was
downloaded from. The rules for connect( ) are
the same ones applied to the loadVariables( )
function. See Table 20-8 under the
global loadVariables( ) function for a list of
the domain matching requirements imposed by the connect( )
method. The connect( ) method returns
false for connection attempts that violate
security restrictions. Note that security restrictions do not apply
to the standalone Player.
Example
// Create a new socket object
mySocket = new XMLSocket( );
// Assign a callback handler function to onConnect
mySocket.onConnect = handleConnect;
// Attempt to connect to an application running on myserver.com at port 10000
if (mySocket.connect("myserver.com", 10000) == false) {
// Jump to a frame showing some sort of error message
gotoAndStop("failureDialog");
} else {
// Jump to a frame where we'll wait until onConnect is triggered
gotoAndPlay("connecting");
}
See Also
XMLSocket.close( ),
XMLSocket.onConnect( )
XMLSocket.onClose( ) Event Handler | specifies the callback handler invoked when the server closes the connection
|
Availability
Flash 5
Synopsis
socket.onClose = closeHandler
socket.closeHandler()
Description
The onClose property allows you to specify a
callback handler to be executed automatically whenever an open
connection to socket is closed by the
server. Server-instigated closures usually result from a server
application shutting down or deliberately "kicking off"
the client.
Example
To respond to an onClose event, we must assign
our own function (i.e., our callback handler) to the
onClose property of an
XMLSocket object. In practice, we use this
callback handler to detect an external socket disconnection. The
following code assigns the function handleClose(
) to mySocket's
onClose property. The
handleClose( ) function simply alerts the user
that a closure has occurred by updating the value of the text field
status:
mySocket = new XMLSocket( );
mySocket.onClose = handleClose;
function handleClose ( ) {
status += ("\nThe server has terminated the connection.\n");
}
See Also
XMLSocket.close( ); Section 10.6.2, "Attaching Event Handlers to Other Objects" in Chapter 10, "Events and Event Handlers"
XMLSocket.onConnect( ) Event Handler | defines the event handler invoked when a connection attempt is completed, successfully or otherwise
|
Availability
Flash 5
Synopsis
socket.onConnect = connectHandler
socket.connectHandler(success )
Arguments
- success
A Boolean indicating whether the connection attempt succeeded
(true) or failed (false).
Description
The onConnect property allows you to
specify a callback handler to be executed automatically when a
previously invoked connect( ) operation
finishes. The execution of the callback handler specified by
onConnect does not necessarily mean a
connection has been successfully established -- the callback
handler is executed whenever the connection
attempt is finished, whether or not the attempt
was successful. The callback handler specified by
onConnect is passed a
success argument that indicates if the
attempt succeeded (i.e., a connection has been established). If so,
success is set to true.
If the attempt failed (i.e., a connection timed out, was refused, or
otherwise could not be established), the
success argument is set to
false. Note that ActionScript does not distinguish
among network timeout, unknown host, refusal, or other common
connection errors. The callback handler, therefore, may not be
executed for up to a minute after the connect( )
command is issued depending on the settings of the server involved in
a connection attempt, the connection speed, network traffic, and so
on.
Example
We use the callback handler specified by
onConnect to detect the success or failure
of a connection attempt. In practice, we might use the callback
handler to set a flag indicating that transmissions should begin if
the connection was successful. We may also use the
callback handler to execute fallback code when the
connection fails, such as alerting the user to the problem's
nature.
To respond to an onConnect event, we must assign
our own function (i.e., our callback handler) to the
onConnect property of an
XMLSocket object. The following code assigns the
function handleConnect( ) to
mySocket's
onConnect property. By updating the value
of the text field status, handleConnect(
) alerts the user that a connection has either succeeded
or failed:
mySocket = new XMLSocket( );
mySocket.onConnect = handleConnect;
function handleConnect (succeeded) {
if (succeeded) {
status += ("Successfully connected.\n");
} else {
status += ("Connection attempt failed.\n");
}
}
For code showing the onConnect( ) handler used
in a more complete system, see the example under the
XMLSocket class.
See Also
XMLSocket.connect( ); Section 10.6.2, "Attaching Event Handlers to Other Objects" in Chapter 10, "Events and Event Handlers"
XMLSocket.onXML( ) Event Handler | defines the callback handler invoked when data is received by an XMLSocket object and has been parsed as XML
|
Availability
Flash 5
Synopsis
socket.onXML = xmlHandler
socket.xmlHandler(XMLobject )
Arguments
- XMLobject
The XML object that will house the incoming XML-formatted data.
Description
The onXML property allows you to specify a
callback handler to be executed when Flash receives an incoming
transmission. Whenever socket receives a
complete block of data (i.e., a string followed by an ASCII
null character) from the server, the callback
handler specified by
socket.onXML
is automatically invoked.
A server may send data as often as it
pleases, but the callback handler is executed only when the trailing
null character (i.e., a zero byte) is received by
socket. In Java, a zero byte is specified
as '\0'. When the zero byte is received, it causes
ActionScript to parse any data that has been received by
socket since the last zero byte was sent
(or since the initial connection if this is the first zero byte). The
parsed data is converted to an XML object hierarchy which is passed
as the XMLobject argument to the callback
handler.
If you are a Flash programmer who is responsible for the client side
of a client/server application only, simply note that the callback
handler specified by onXML receives any new XML
data when it arrives. The new XML data is accessible through
XMLobject.
To access the raw data sent over a socket, override the default
behavior of the socket's onData( )
handler. See XMLSocket.onData( ).
Example
To respond to an onXML event, we must assign our
own function (i.e., our callback handler) to the
onXML property of an
XMLSocket object. The following code assigns the
function handleIncoming( ) to
mySocket's onXML
property. The handleIncoming( ) function
accesses one of the nodes of the XML object hierarchy stored in
messageObj and adds its value to the text field
messages:
mySocket = new XMLSocket( );
mySocket.onXML = handleIncoming;
function handleIncoming (messageObj) {
trace("Got some new data!");
// messageObj will contain the fragment: <MESSAGE>text</MESSAGE>
var message = messageObj.firstChild.firstChild;
messages += (message.nodeValue + "\n");
}
For code showing the onXML handler used in a
more complete system, see the example under the XMLSocket
class.
See Also
XMLSocket.send, XMLSocket.onData(
); Section 10.6.2, "Attaching Event Handlers to Other Objects" in Chapter 10, "Events and Event Handlers"
XMLSocket.send( )
Method | transmit XML-formatted data to a server application
|
Availability
Flash 5
Synopsis
socket.send(XMLobject)
Arguments
- XMLobject
An XML object to be converted into a string and
sent to the server application or any string containing XML-formatted
text.
Description
The send( ) method transmits a message from
Flash to a server application via socket.
The message to send should be an object of the
XML class but may also be a string. When
send( ) is invoked,
XMLobject is converted to a string and
sent to the remote application, followed by a zero byte (the first
ASCII character, null). The remote application is not obliged to
respond; however, any response sent will trigger
socket's onXML(
) event handler.
Example
The following code sends a very simple XML-formatted message to a
remote application over the socket
mySocket, which is a valid
XMLSocket object for which a connection has
already been established (note that
message is an XML
object, not an XMLSocket object; see the example
under the XMLSocket class entry for a
full-fledged XMLSocket sample application):
var message = new XML('<MESSAGE>testing...testing...</MESSAGE>');
mySocket.send(message);
It is also legal to send a string containing XML-formatted text
without wrapping it in an XML object. For simple
XML messages, this is often sufficient:
mySocket.send('<MESSAGE>testing...testing...</MESSAGE>');
See Also
XMLSocket.onXML;
the XMLSocket Class, XML.send(
)
| | | 20.4. Entry Headings | | IV. Appendixes |
Copyright © 2002 O'Reilly & Associates. All rights reserved.
|