ActionScript Dictionary overview

This dictionary describes the syntax and use of ActionScript elements in Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004. To use examples in a script, copy the example code from this dictionary and paste it in the Script pane or into an external script file. The dictionary lists all ActionScript elements—operators, keywords, statements, actions, properties, functions, classes, and methods. For an overview of all dictionary entries, see Contents of the dictionary; the tables in this section are a good starting point for looking up symbolic operators or methods whose class you don't know. For information on components, see Using Components.

There are two types of entries in this dictionary:

  • Individual entries for operators, keywords, functions, variables, properties, methods, and statements
  • Class entries, which provide general information about built-in classes

Use the information in the sample entries to interpret the structure and conventions used in these types of entries.


Sample entry for most ActionScript elements

The following sample dictionary entry explains the conventions used for all ActionScript elements that are not classes.

Entry title

All entries are listed alphabetically. The alphabetization ignores capitalization, leading underscores, and so on.

Availability

Unless otherwise noted, the Availability section tells which versions of Flash Player support the element. This is not the same as the version of Flash used to author the content. For example, if you use Macromedia Flash MX 2004 or Macromedia Flash MX Professional 2004 to create content for Flash Player 6, you can use only ActionScript elements that are available to Flash Player 6.

In a few cases, this section also indicates which version of the authoring tool supports an element. For an example, see System.setClipboard().

Finally, if an element is supported only in ActionScript 2.0, that information is also noted in this section.

Usage

This section provides correct syntax for using the ActionScript element in your code. The required portion of the syntax is in code font, and the code that you provide is in italicized code font. Brackets ([]) indicate optional parameters.

Parameters

This section describes any parameters listed in the syntax.

Returns

This section identifies what, if any, values the element returns.

Description

This section identifies the type of element (for example, operator, method, function, and so on) and then describes how to use the element.

Example

This section provides a code sample demonstrating how to use the element.

See also

This section lists related ActionScript dictionary entries.


Sample entry for classes

The following sample dictionary entry explains the conventions used for built-in ActionScript classes. Classes are listed alphabetically with all other elements in the dictionary.

Entry title

The entry title provides the name of the class. The class name is followed by general descriptive information.

Method and property summary tables

Each class entry contains a table listing all of the associated methods. If the class has properties (often constants), event handlers, or event listeners, these elements are summarized in additional tables. All of the elements listed in these tables also have their own dictionary entries, which follow the class entry.

Constructor

If a class requires that you use a constructor to access its methods and properties, the constructor is described in each class entry. This description has all of the standard elements (syntax, description, and so on) of other dictionary entries.

Method and property listings

The methods and properties of a class are listed alphabetically after the class entry.


Contents of the dictionary

All dictionary entries are listed alphabetically. However, some operators are symbols and are presented in ASCII order. In addition, methods that are associated with a class are listed along with the class name—for example, the abs() method of the Math class is listed as Math.abs().

The following two tables help you locate these elements. The first table lists the symbolic operators in the order in which they occur in the dictionary. The second table lists all other ActionScript elements.

Symbolic operators | See entry
-- | -- (decrement)
++ | ++ (increment)
! | ! (logical NOT)
!= | != (inequality)
!== | !== (strict inequality)
% | % (modulo)
%= | %= (modulo assignment)
& | & (bitwise AND operator)
&& | && (logical AND)
&= | &= (bitwise AND assignment)
() | () (parentheses)
- | - (minus)
* | * (multiplication)
*= | *= (multiplication assignment)
, | , (comma)
. | . (dot)
: | : (type)
?: | ?: (conditional)
/ | / (division)
// | // (comment delimiter)
/* | /* (comment delimiter)
/= | /= (division assignment)
[] | [] (array access)
^ | ^ (bitwise XOR)
^= | ^= (bitwise XOR assignment)
{} | {} (object initializer)
| | | (bitwise OR)
|| | || (logical OR)
|= | |= (bitwise OR assignment)
~ | ~ (bitwise NOT)
+ | + (addition)
+= | += (addition assignment)
< | < (less than)
<< | << (bitwise left shift)
<<= | <<= (bitwise left shift and assignment)
<= | <= (less than or equal to)
<> | <> (inequality)
= | = (assignment)
-= | -= (subtraction assignment)
== | == (equality)
=== | === (strict equality)
> | > (greater than)
>= | >= (greater than or equal to)
>> | >> (bitwise right shift)
>>= | >>= (bitwise right shift and assignment)
>>> | >>> (bitwise unsigned right shift)
>>>= | >>>= (bitwise unsigned right shift and assignment)

The following table lists all ActionScript elements that are not symbolic operators.

ActionScript element | See entry
#endinitclip | #endinitclip
#include | #include
#initclip | #initclip
__proto__ | Object.__proto__
_accProps | _accProps
_alpha | MovieClip._alpha, Button._alpha, TextField._alpha
_currentframe | MovieClip._currentframe
_droptarget | MovieClip._droptarget
_focusrect | _focusrect, Button._focusrect, MovieClip._focusrect
_framesloaded | MovieClip._framesloaded
_global | _global object
_height | Button._height, MovieClip._height, TextField._height
_highquality | _highquality, Button._highquality, MovieClip._highquality, TextField._highquality
_lockroot | MovieClip._lockroot
_name | Button._name, MovieClip._name, TextField._name
_parent | _parent, Button._parent, MovieClip._parent, TextField._parent
_quality | _quality, Button._quality, TextField._quality
_root | _root
_rotation | Button._rotation, MovieClip._rotation, TextField._rotation
_soundbuftime | _soundbuftime, Button._soundbuftime, MovieClip._soundbuftime, TextField._soundbuftime
_target | Button._target, MovieClip._target, TextField._target
_totalframes | MovieClip._totalframes
_url | Button._url, MovieClip._url, TextField._url
_visible | Button._visible, MovieClip._visible, TextField._visible
_width | Button._width, MovieClip._width, TextField._width
_x | Button._x, MovieClip._x, TextField._x
_xmouse | Button._xmouse, MovieClip._xmouse, TextField._xmouse
_xscale | Button._xscale, MovieClip._xscale, TextField._xscale
_y | Button._y, MovieClip._y, TextField._y
_ymouse | Button._ymouse, MovieClip._ymouse, TextField._ymouse
_yscale | Button._yscale, MovieClip._yscale, TextField._yscale
abs | Math.abs()
Accessibility | Accessibility class
acos | Math.acos()
activityLevel | Camera.activityLevel, Microphone.activityLevel
add | add
addListener | Key.addListener(), Mouse.addListener(), MovieClipLoader.addListener(), Selection.addListener(), Stage.addListener(), TextField.addListener()
addPage | PrintJob.addPage()
addProperty | Object.addProperty()
addRequestHeader | LoadVars.addRequestHeader(), XML.addRequestHeader()
align | Stage.align, TextFormat.align
allowDomain | LocalConnection.allowDomain, System.security.allowDomain()
allowInsecureDomain | LocalConnection.allowInsecureDomain, System.security.allowInsecureDomain()
and | and
appendChild | XML.appendChild()
apply | Function.apply()
Arguments | Arguments class
Array | Array class, Array()
asfunction | asfunction
asin | Math.asin()
atan | Math.atan()
atan2 | Math.atan2()
attachAudio | MovieClip.attachAudio()
attachMovie | MovieClip.attachMovie()
attachSound | Sound.attachSound()
attachVideo | Video.attachVideo()
attributes | XML.attributes
autosize | TextField.autoSize
avHardwareDisable | System.capabilities.avHardwareDisable
background | TextField.background
backgroundColor | TextField.backgroundColor
BACKSPACE | Key.BACKSPACE
bandwidth | Camera.bandwidth
beginFill | MovieClip.beginFill()
beginGradientFill | MovieClip.beginGradientFill()
blockIndent | TextFormat.blockIndent
bold | TextFormat.bold
Boolean | Boolean(), Boolean class
border | TextField.border
borderColor | TextField.borderColor
bottomScroll | TextField.bottomScroll
break | break
bufferLength | NetStream.bufferLength
bufferTime | NetStream.bufferTime
builtInItems | ContextMenu.builtInItems
bullet | TextFormat.bullet
Button | Button class
bytesLoaded | NetStream.bytesLoaded
bytesTotal | NetStream.bytesTotal
call | call(), Function.call()
callee | arguments.callee
caller | arguments.caller
Camera | Camera class
capabilities | System.capabilities object
CAPSLOCK | Key.CAPSLOCK
caption | ContextMenuItem.caption
case | case
catch | try..catch..finally
ceil | Math.ceil()
charAt | String.charAt()
charCodeAt | String.charCodeAt()
childNodes | XML.childNodes
chr | chr
class | class
clear | MovieClip.clear(), SharedObject.clear(), Video.clear()
clearInterval | clearInterval()
cloneNode | XML.cloneNode()
close | LocalConnection.close(), NetStream.close(), XMLSocket.close()
Color | Color class, TextFormat.color
concat | Array.concat(), String.concat()
connect | LocalConnection.connect(), NetConnection.connect(), XMLSocket.connect()
condenseWhite | TextField.condenseWhite
constructor | Array class, Boolean class, Camera class, Color class, ContextMenu class, ContextMenuItem class, Date class, Error class, LoadVars class, LocalConnection class, Microphone class, NetConnection class, NetStream class, Number class, Object class, PrintJob class, SharedObject class, Sound class, String class, TextField class, TextField.StyleSheet class, TextFormat class, XML class, XMLSocket class
contentType | LoadVars.contentType, XML.contentType
ContextMenu | ContextMenu class
ContextMenuItem | ContextMenuItem class
continue | continue
CONTROL | Key.CONTROL
copy | ContextMenu.copy(), ContextMenuItem.copy()
cos | Math.cos()
createElement | XML.createElement()
createEmptyMovieClip | MovieClip.createEmptyMovieClip()
createTextField | MovieClip.createTextField()
createTextNode | XML.createTextNode()
currentFps | Camera.currentFps, NetStream.currentFps
curveTo | MovieClip.curveTo()
CustomActions | CustomActions class
customItems | ContextMenu.customItems
data | SharedObject.data
Date | Date class
deblocking | Video.deblocking
default | default
delete | delete
DELETEKEY | Key.DELETEKEY
do while | do while
docTypeDecl | XML.docTypeDecl
domain | LocalConnection.domain()
DOWN | Key.DOWN
duplicateMovieClip | duplicateMovieClip(), MovieClip.duplicateMovieClip()
duration | Sound.duration
dynamic | dynamic
E | Math.E
else | else
else if | else if
embedFonts | TextField.embedFonts
enabled | Button.enabled, ContextMenuItem.enabled, MovieClip.enabled
END | Key.END
endFill | MovieClip.endFill()
ENTER | Key.ENTER
eq | eq (equal — string specific)
Error | Error class
ESCAPE (constant) | Key.ESCAPE
escape (function) | escape
eval | eval()
exactSettings | System.exactSettings
exp | Math.exp()
extends | extends
false | false
finally | try..catch..finally
findText | TextSnapshot.findText()
firstChild | XML.firstChild
floor | Math.floor()
flush | SharedObject.flush()
focusEnabled | MovieClip.focusEnabled
font | TextFormat.font
for | for
for..in | for..in
fps | Camera.fps
fromCharCode | String.fromCharCode()
fscommand | fscommand()
function | function, Function class
gain | Microphone.gain
ge | ge (greater than or equal to — string specific)
get | Camera.get(), CustomActions.get(), get, Microphone.get()
getAscii | Key.getAscii()
getBeginIndex | Selection.getBeginIndex()
getBounds | MovieClip.getBounds()
getBytesLoaded | LoadVars.getBytesLoaded(), MovieClip.getBytesLoaded(), Sound.getBytesLoaded(), XML.getBytesLoaded()
getBytesTotal | LoadVars.getBytesTotal(), MovieClip.getBytesTotal(), Sound.getBytesTotal(), XML.getBytesTotal()
getCaretIndex | Selection.getCaretIndex()
getCode | Key.getCode()
getCount | TextSnapshot.getCount()
getDate | Date.getDate()
getDay | Date.getDay()
getDepth | Button.getDepth(), MovieClip.getDepth(), TextField.getDepth()
getEndIndex | Selection.getEndIndex()
getFocus | Selection.getFocus()
getFontList | TextField.getFontList()
getFullYear | Date.getFullYear()
getHours | Date.getHours()
getInstanceAtDepth | MovieClip.getInstanceAtDepth()
getLocal | SharedObject.getLocal()
getMilliseconds | Date.getMilliseconds()
getMinutes | Date.getMinutes()
getMonth | Date.getMonth()
getNewTextFormat | TextField.getNewTextFormat()
getNextHighestDepth | MovieClip.getNextHighestDepth()
getPan | Sound.getPan()
getProgress | MovieClipLoader.getProgress()
getProperty | getProperty
getRGB | Color.getRGB()
getSeconds | Date.getSeconds()
getSelected | TextSnapshot.getSelected()
getSelectedText | TextSnapshot.getSelectedText()
getSize | SharedObject.getSize()
getStyle | TextField.StyleSheet.getStyle()
getStyleNames | TextField.StyleSheet.getStyleNames()
getSWFVersion | MovieClip.getSWFVersion()
getText | TextSnapshot.getText()
getTextExtent | TextFormat.getTextExtent()
getTextFormat | TextField.getTextFormat()
getTextSnapshot | MovieClip.getTextSnapshot()
getTime | Date.getTime()
getTimer | getTimer
getTimezoneOffset | Date.getTimezoneOffset()
getTransform | Color.getTransform(), Sound.getTransform()
getURL | getURL(), MovieClip.getURL()
getUTCDate | Date.getUTCDate()
getUTCDay | Date.getUTCDay()
getUTCFullYear | Date.getUTCFullYear()
getUTCHours | Date.getUTCHours()
getUTCMilliseconds | Date.getUTCMilliseconds()
getUTCMinutes | Date.getUTCMinutes()
getUTCMonth | Date.getUTCMonth()
getUTCSeconds | Date.getUTCSeconds()
getVersion | getVersion
getVolume | Sound.getVolume()
getYear | Date.getYear()
globalToLocal | MovieClip.globalToLocal()
goto | gotoAndPlay(), gotoAndStop()
gotoAndPlay | gotoAndPlay(), MovieClip.gotoAndPlay()
gotoAndStop | gotoAndStop(), MovieClip.gotoAndStop()
gt | gt (greater than — string specific)
hasAccessibility | System.capabilities.hasAccessibility
hasAudio | System.capabilities.hasAudio
hasAudioEncoder | System.capabilities.hasAudioEncoder
hasChildNodes | XML.hasChildNodes()
hasEmbeddedVideo | System.capabilities.hasEmbeddedVideo
hasMP3 | System.capabilities.hasMP3
hasPrinting | System.capabilities.hasPrinting
hasScreenBroadcast | System.capabilities.hasScreenBroadcast
hasScreenPlayback | System.capabilities.hasScreenPlayback
hasStreamingAudio | System.capabilities.hasStreamingAudio
hasStreamingVideo | System.capabilities.hasStreamingVideo
hasVideoEncoder | System.capabilities.hasVideoEncoder
height | Camera.height, Stage.height, Video.height
hide | Mouse.hide()
hideBuiltInItems | ContextMenu.hideBuiltInItems()
hitArea | MovieClip.hitArea
hitTest | MovieClip.hitTest()
hitTestTextNearPos | TextSnapshot.hitTestTextNearPos()
HOME | Key.HOME
hscroll | TextField.hscroll
html | TextField.html
htmlText | TextField.htmlText
id3 | Sound.id3
if | if
ifFrameLoaded | ifFrameLoaded
ignoreWhite | XML.ignoreWhite
implements | implements
import | import
indent | TextFormat.indent
index | Camera.index, Microphone.index
indexOf | String.indexOf()
Infinity | Infinity
-Infinity | -Infinity
INSERT | Key.INSERT
insertBefore | XML.insertBefore()
install | CustomActions.install()
instanceof | instanceof
int | int
interface | interface
isActive | Accessibility.isActive()
isDebugger | System.capabilities.isDebugger
isDown | Key.isDown()
isFinite | isFinite
isNaN | isNaN()
isToggled | Key.isToggled()
italic | TextFormat.italic
join | Array.join()
Key | Key class
language | System.capabilities.language
lastChild | XML.lastChild
lastIndexOf | String.lastIndexOf()
le | le (less than or equal to — string specific)
leading | TextFormat.leading
LEFT | Key.LEFT
leftMargin | TextFormat.leftMargin
length | length, arguments.length, Array.length, String.length, TextField.length
level | _level
lineStyle | MovieClip.lineStyle()
lineTo | MovieClip.lineTo()
list | CustomActions.list()
LN10 | Math.LN10
LN2 | Math.LN2
load | LoadVars.load(), TextField.StyleSheet.load(), XML.load(),
loadClip | MovieClipLoader.loadClip()
loaded | LoadVars.loaded, XML.loaded
loadMovie | loadMovie(), MovieClip.loadMovie()
loadMovieNum | loadMovieNum()
loadSound | Sound.loadSound()
loadVariables | loadVariables(), MovieClip.loadVariables()
loadVariablesNum | loadVariablesNum()
LoadVars | LoadVars class
LocalConnection | LocalConnection class
localFileReadDisable | System.capabilities.localFileReadDisable
localToGlobal | MovieClip.localToGlobal()
log | Math.log()
LOG10E | Math.LOG10E
LOG2E | Math.LOG2E
lt | lt (less than — string specific)
manufacturer | System.capabilities.manufacturer
Math | Math class
max | Math.max()
MAX_VALUE | Number.MAX_VALUE
maxChars | TextField.maxChars
maxhscroll | TextField.maxhscroll
maxscroll | maxscroll, TextField.maxscroll
mbchr | mbchr
mblength | mblength
mbord | mbord
mbsubstring | mbsubstring
menu | Button.menu, MovieClip.menu, TextField.menu
message | Error.message
Microphone | Microphone class
min | Math.min()
MIN_VALUE | Number.MIN_VALUE
MMExecute | MMExecute()
motionLevel | Camera.motionLevel
motionTimeOut | Camera.motionTimeOut
Mouse | Mouse class
mouseWheelEnabled | TextField.mouseWheelEnabled
moveTo | MovieClip.moveTo()
MovieClip | MovieClip class
MovieClipLoader | MovieClipLoader class
multiline | TextField.multiline
muted | Camera.muted, Microphone.muted
name | Error.name, Microphone.name
names | Camera.names, Microphone.names
NaN | NaN, Number.NaN
ne | ne (not equal — string specific)
NEGATIVE_INFINITY | Number.NEGATIVE_INFINITY
NetConnection | NetConnection class
NetStream | NetStream class
new (operator) | new
newline | newline
nextFrame | nextFrame(), MovieClip.nextFrame()
nextScene | nextScene()
nextSibling | XML.nextSibling
nodeName | XML.nodeName
nodeType | XML.nodeType
nodeValue | XML.nodeValue
not | not
null | null
Number | Number(), Number class
Object | Object class, Object()
on | on()
onActivity | Camera.onActivity, Microphone.onActivity
onChanged | TextField.onChanged
onClipEvent | onClipEvent()
onClose | XMLSocket.onClose()
onConnect | XMLSocket.onConnect()
onData | LoadVars.onData, MovieClip.onData, XML.onData, XMLSocket.onData()
onDragOut | Button.onDragOut, MovieClip.onDragOut
onDragOver | Button.onDragOver, MovieClip.onDragOver
onEnterFrame | MovieClip.onEnterFrame
onID3 | Sound.onID3
onKeyDown | Button.onKeyDown, Key.onKeyDown, MovieClip.onKeyDown
onKeyUp | Button.onKeyUp, Key.onKeyUp, MovieClip.onKeyUp
onKillFocus | Button.onKillFocus, MovieClip.onKillFocus, TextField.onKillFocus
onLoad | LoadVars.onLoad, MovieClip.onLoad, Sound.onLoad, TextField.StyleSheet.onLoad, XML.onLoad()
onLoadComplete | MovieClipLoader.onLoadComplete()
onLoadError | MovieClipLoader.onLoadError()
onLoadInit | MovieClipLoader.onLoadInit()
onLoadProgress | MovieClipLoader.onLoadProgress()
onLoadStart | MovieClipLoader.onLoadStart()
onMouseDown | Mouse.onMouseDown, MovieClip.onMouseDown
onMouseMove | Mouse.onMouseMove, MovieClip.onMouseMove
onMouseUp | Mouse.onMouseUp, MovieClip.onMouseUp
onMouseWheel | Mouse.onMouseWheel
onPress | Button.onPress, MovieClip.onPress
onRelease | Button.onRelease, MovieClip.onRelease
onReleaseOutisde | Button.onReleaseOutside, MovieClip.onReleaseOutside
onResize | Stage.onResize
onRollOut | Button.onRollOut, MovieClip.onRollOut
onRollOver | Button.onRollOver, MovieClip.onRollOver
onScroller | TextField.onScroller
onSelect | ContextMenu.onSelect, ContextMenuItem.onSelect
onSetFocus | Button.onSetFocus, MovieClip.onSetFocus, Selection.onSetFocus, TextField.onSetFocus
onSoundComplete | Sound.onSoundComplete
onStatus | Camera.onStatus, LocalConnection.onStatus, Microphone.onStatus, NetStream.onStatus, SharedObject.onStatus, System.onStatus
onUnload | MovieClip.onUnload
onUpdate | onUpdate
onXML | XMLSocket.onXML()
or (logical OR) | or
ord | ord
os | System.capabilities.os
parentNode | XML.parentNode
parseCSS | TextField.StyleSheet.parseCSS()
parseFloat | parseFloat()
parseInt | parseInt
parseXML | XML.parseXML()
password | TextField.password
pause | NetStream.pause()
PGDN | Key.PGDN
PGUP | Key.PGUP
PI | Math.PI
pixelAspectRatio | System.capabilities.pixelAspectRatio
play | play(), MovieClip.play(), NetStream.play()
playerType | System.capabilities.playerType
pop | Array.pop()
position | Sound.position
POSITIVE_INFINITY | Number.POSITIVE_INFINITY
pow | Math.pow()
prevFrame | prevFrame(), MovieClip.prevFrame()
previousSibling | XML.previousSibling
prevScene | prevScene()
print | print()
printAsBitmap | printAsBitmap()
printAsBitmapNum | printAsBitmapNum()
PrintJob | PrintJob class
printNum | printNum()
private | private
prototype | Function.prototype
public | public
push | Array.push()
quality | Camera.quality
random | random, Math.random()
rate | Microphone.rate
registerClass | Object.registerClass()
removeListener | Key.removeListener(), Mouse.removeListener(), MovieClipLoader.removeListener(), Selection.removeListener(), Stage.removeListener(), TextField.removeListener()
removeMovieClip | removeMovieClip(), MovieClip.removeMovieClip()
removeNode | XML.removeNode()
removeTextField | TextField.removeTextField()
replaceSel | TextField.replaceSel()
replaceText | TextField.replaceText()
resolutionX | System.capabilities.screenResolutionX
resolutionY | System.capabilities.screenResolutionY
restrict | TextField.restrict
return | return
reverse | Array.reverse()
RIGHT | Key.RIGHT
rightMargin | TextFormat.rightMargin
round | Math.round()
scaleMode | Stage.scaleMode
screenColor | System.capabilities.screenColor
screenDPI | System.capabilities.screenDPI
screenResolutionX | System.capabilities.screenResolutionX
screenResolutionY | System.capabilities.screenResolutionY
scroll | scroll, TextField.scroll
seek | NetStream.seek()
selectable | TextField.selectable
Selection | Selection class
send | LoadVars.send(), LocalConnection.send(), PrintJob.send(), XML.send(), XMLSocket.send()
sendAndLoad | LoadVars.sendAndLoad(), XML.sendAndLoad()
separatorBefore | ContextMenuItem.separatorBefore
serverString | System.capabilities.serverString
set | set
set variable | set variable
setBufferTime | NetStream.setBufferTime()
setClipboard | System.setClipboard()
setDate | Date.setDate()
setFocus | Selection.setFocus()
setFullYear | Date.setFullYear()
setGain | Microphone.setGain()
setHours | Date.setHours()
setInterval | setInterval()
setMask | MovieClip.setMask()
setMilliseconds | Date.setMilliseconds()
setMinutes | Date.setMinutes()
setMode | Camera.setMode()
setMonth | Date.setMonth()
setMotionLevel | Camera.setMotionLevel()
setNewTextFormat | TextField.setNewTextFormat()
setPan | Sound.setPan()
setProperty | setProperty()
setQuality | Camera.setQuality()
setRate | Microphone.setRate()
setRGB | Color.setRGB()
setSeconds | Date.setSeconds()
setSelectColor | TextSnapshot.setSelectColor()
setSelected | TextSnapshot.setSelected()
setSelection | Selection.setSelection()
setSilenceLevel | Microphone.setSilenceLevel()
setStyle | TextField.StyleSheet.setStyle()
setTextFormat | TextField.setTextFormat()
setTime | Date.setTime()
setTransform | Color.setTransform(), Sound.setTransform()
setUseEchoSuppression | Microphone.setUseEchoSuppression()
setUTCDate | Date.setUTCDate()
setUTCFullYear | Date.setUTCFullYear()
setUTCHours | Date.setUTCHours()
setUTCMilliseconds | Date.setUTCMilliseconds()
setUTCMinutes | Date.setUTCMinutes()
setUTCMonth | Date.setUTCMonth()
setUTCSeconds | Date.setUTCSeconds()
setVolume | Sound.setVolume()
setYear | Date.setYear()
SharedObject | SharedObject class
SHIFT (constant) | Key.SHIFT
shift (method) | Array.shift()
show | Mouse.show()
showMenu | Stage.showMenu
showSettings | System.showSettings()
silenceLevel | Microphone.silenceLevel()
silenceTimeout | Microphone.silenceTimeout()
sin | Math.sin()
size | TextFormat.size
slice | Array.slice(), String.slice()
smoothing | Video.smoothing
sort | Array.sort()
sortOn | Array.sortOn()
Sound | Sound class
SPACE | Key.SPACE
splice | Array.splice()
split | String.split()
sqrt | Math.sqrt()
SQRT1_2 | Math.SQRT1_2
SQRT2 | Math.SQRT2
Stage | Stage class
start | PrintJob.start(), Sound.start()
startDrag | startDrag(), MovieClip.startDrag()
static | static
status | XML.status
stop | stop(), MovieClip.stop(), Sound.stop()
stopAllSounds | stopAllSounds()
stopDrag | stopDrag(), MovieClip.stopDrag()
String | String class, String()
StyleSheet (class) | TextField.StyleSheet class
styleSheet (property) | TextField.styleSheet
substr | String.substr()
substring | substring, String.substring()
super | super
swapDepths | MovieClip.swapDepths()
switch | switch
System | System class
TAB | Key.TAB
tabChildren | MovieClip.tabChildren
tabEnabled | Button.tabEnabled, MovieClip.tabEnabled, TextField.tabEnabled
tabIndex | Button.tabIndex, MovieClip.tabIndex, TextField.tabIndex
tabStops | TextFormat.tabStops
tan | Math.tan()
target | TextFormat.target
targetPath | targetPath
tellTarget | tellTarget
text | TextField.text
textColor | TextField.textColor
TextField | TextField class
TextFormat | TextFormat class
textHeight | TextField.textHeight
TextSnapshot | TextSnapshot object
textWidth | TextField.textWidth
this | this
throw | throw
time | NetStream.time
toggleHighQuality | toggleHighQuality()
toLowerCase | String.toLowerCase()
toString | Array.toString(), Boolean.toString(), Date.toString(), Error.toString(), LoadVars.toString(), Number.toString(), Object.toString(), XML.toString()
toUpperCase | String.toUpperCase()
trace | trace()
trackAsMenu | Button.trackAsMenu, MovieClip.trackAsMenu
true | true
try | try..catch..finally
type | TextField.type
typeof | typeof
undefined | undefined
underline | TextFormat.underline
unescape | unescape
uninstall | CustomActions.uninstall()
unloadClip | MovieClipLoader.unloadClip()
unloadMovie | unloadMovie(), MovieClip.unloadMovie()
unLoadMovieNum | unloadMovieNum()
unshift | Array.unshift()
unwatch | Object.unwatch()
UP | Key.UP
updateAfterEvent | updateAfterEvent()
updateProperties | Accessibility.updateProperties()
url | TextFormat.url
useCodePage | System.useCodepage
useEchoSuppression | Microphone.useEchoSuppression
useHandCursor | Button.useHandCursor, MovieClip.useHandCursor
UTC | Date.UTC()
valueOf | Boolean.valueOf(), Number.valueOf(), Object.valueOf()
var | var
variable | TextField.variable
version | System.capabilities.version
Video | Video class
visible | ContextMenuItem.visible
void | void
watch | Object.watch()
while | while
width | Camera.width, Stage.width, Video.width
with | with
wordwrap | TextField.wordWrap
XML | XML class
xmlDecl | XML.xmlDecl
XMLNode | XMLNode class
XMLSocket | XMLSocket class


-- (decrement)

Availability

Flash Player 4.

Usage

--expression
expression--

Parameters

None.

Returns

A number.

Description

Operator (arithmetic); a pre-decrement and post-decrement unary operator that subtracts 1 from the expression. The pre-decrement form of the operator (--expression) subtracts 1 from expression and returns the result. The post-decrement form of the operator (expression--) subtracts 1 from the expression and returns the initial value of expression (the value prior to the subtraction).

Example

The pre-decrement form of the operator decrements x to 2 (x - 1 = 2), and returns the result as y:

x = 3;
y = --x;
//y is equal to 2

The post-decrement form of the operator decrements x to 2 (x - 1 = 2), and returns the original value of x as the result y:

x = 3;
y = x--
//y is equal to 3


++ (increment)

Availability

Flash Player 4.

Usage

++expression
expression++

Parameters

None.

Returns

A number.

Description

Operator (arithmetic); a pre-increment and post-increment unary operator that adds 1 to expression. The expression can be a variable, element in an array, or property of an object. The pre-increment form of the operator (++expression) adds 1 to expression and returns the result. The post-increment form of the operator (expression++) adds 1 to expression and returns the initial value of expression (the value prior to the addition).

The pre-increment form of the operator increments x to 2 (x + 1 = 2), and returns the result as y:

x = 1;
y = ++x
//y is equal to 2

The post-increment form of the operator increments x to 2 (x + 1 = 2), and returns the original value of x as the result y:

x = 1;
y = x++;
//y is equal to 1

Example

The following example uses ++ as a post-increment operator to make a while loop run five times.

i = 0;
while(i++ < 5){
trace("this is execution " + i);
}

This example uses ++ as a pre-increment operator.

var a = [];
var i = 0;
while (i < 10) {
  a.push(++i);
}
trace(a.join());

This script displays the following result in the Output panel:

1,2,3,4,5,6,7,8,9,10

The following example uses ++ as a post-increment operator.

var a = [];
var i = 0;
while (i < 10) {
a.push(i++);
  }
trace(a.join());

This script displays the following result in the Output panel:

0,1,2,3,4,5,6,7,8,9


! (logical NOT)

Availability

Flash Player 4.

Usage

!expression

Parameters

None.

Returns

A Boolean value.

Description

Operator (logical); inverts the Boolean value of a variable or expression. If expression is a variable with the absolute or converted value true, the value of !expression is false. If the expression x && y evaluates to false, the expression !(x && y) evaluates to true.

The following expressions illustrate the result of using the ! operator:

!true returns false

!false returns true

Example

In the following example, the variable happy is set to false. The if condition evaluates the condition !happy, and if the condition is true, the trace() action sends a string to the Output panel.

happy = false;
if (!happy) {
  trace("don't worry, be happy");
}


!= (inequality)

Availability

Flash Player 5.

Usage

expression1 != expression2

Parameters

None.

Returns

A Boolean value.

Description

Operator (inequality); tests for the exact opposite of the == operator. If expression1 is equal to expression2, the result is false. As with the == operator, the definition of equal depends on the data types being compared.

  • Numbers, strings, and Boolean values are compared by value.
  • Variables, objects, arrays, and functions are compared by reference.

Example

The following example illustrates the result of the != operator:

5 != 8 returns true

5 != 5 returns false

This example illustrates the use of the != operator in an if statement.

a = "David";
b = "Fool"
if (a != b){
  trace("David is not a fool");
}

See also

!== (strict inequality), == (equality), === (strict equality)


!== (strict inequality)

Availability

Flash Player 6.

Usage

expression1 !== expression2

Description

Operator; tests for the exact opposite of the === operator. The strict inequality operator performs the same as the inequality operator except that data types are not converted. If expression1 is equal to expression2, and their data types are equal, the result is false. As with the === operator, the definition of equal depends on the data types being compared.

  • Numbers, strings, and Boolean values are compared by value.
  • Variables, objects, arrays, and functions are compared by reference.

Example

The following code displays the returned value of operations that use the equality, strict equality, and strict inequality operators.

s1 = new String("5");
s2 = new String("5");
s3 = new String("Hello");
n  = new Number(5);
b = new Boolean(true);

s1 == s2; // true
s1 == s3; // false
s1 == n; // true
s1 == b; // false

s1 === s2;  // true
s1 === s3; // false
s1 === n; // false
s1 === b; // false

s1 !== s2; // false
s1 !== s3; // true
s1 !== n; // true
s1 !== b; // true

See also

!= (inequality), == (equality), === (strict equality)


% (modulo)

Availability

Flash Player 4. In Flash 4 files, the % operator is expanded in the SWF file as x - int(x/y) * y, and may not be as fast or as accurate in later versions of Flash Player.

Usage

expression1 % expression2

Parameters

None.

Returns

Nothing.

Description

Operator (arithmetic); calculates the remainder of expression1 divided by expression2. If either of the expression parameters are non-numeric, the modulo operator attempts to convert them to numbers. The expression can be a number or string that converts to a numeric value.

Example

The following is a numeric example that uses the modulo (%) operator.

trace (12 % 5);
// returns 2
trace (4.3 % 2.1);
// returns approximately 0.1


%= (modulo assignment)

Availability

Flash Player 4.

Usage

expression1 %= expression2

Parameters

None.

Returns

Nothing.

Description

Operator (arithmetic compound assignment); assigns expression1 the value of expression1 % expression2. For example, the following two expressions are the same:

x %= y
x = x % y

Example

The following example assigns the value 4 to the variable x.

x = 14;
y = 5;
trace(x %= y);
// returns 4

See also

% (modulo)


& (bitwise AND operator)

Availability

Flash Player 5. In Flash 4, the & operator was used for concatenating strings. In Flash 5 and later, the & operator is a bitwise AND, and you must use the add and + operators to concatenate strings. Flash 4 files that use the & operator are automatically updated to use add when brought into the Flash 5 or later authoring environment.

Usage

expression1 & expression2

Parameters

None.

Returns

Nothing.

Description

Operator (bitwise); converts expression1 and expression2 to 32-bit unsigned integers, and performs a Boolean AND operation on each bit of the integer parameters. The result is a new 32-bit unsigned integer.


&& (logical AND)

Availability

Flash Player 4.

Usage

expression1 && expression2

Parameters

None.

Returns

A Boolean value.

Description

Operator (logical); performs a Boolean operation on the values of one or both of the expressions. Evaluates expression1 (the expression on the left side of the operator) and returns false if the expression evaluates to false. If expression1 evaluates to true, expression2 (the expression on the right side of the operator) is evaluated. If expression2 evaluates to true, the final result is true; otherwise, it is false.

Example

This example uses the && operator to perform a test to determine if a player has won the game. The turns variable and the score variable are updated when a player takes a turn or scores points during the game. The following script displays "You Win the Game!" in the Output panel when the player's score reaches 75 or higher in 3 turns or less.

turns=2;
score=77;
winner = (turns <= 3) && (score >= 75);
if (winner) {
  trace("You Win the Game!");
} else {
  trace("Try Again!");
}


&= (bitwise AND assignment)

Availability

Flash Player 5.

Usage

expression1 &= expression2

Parameters

None.

Returns

Nothing.

Description

Operator; assigns expression1 the value of expression1 & expression2. For example, the following two expressions are the same.

x &= y;
x = x & y;

Example

The following example assigns the value 9 to x.

x = 15;
y = 9;
trace(x &= y);
// returns 9

See also

& (bitwise AND operator)


() (parentheses)

Availability

Flash Player 4.

Usage

(expression1, expression2)
function(parameter1,..., parameterN)

Parameters

expression1, expression2 Numbers, strings, variables, or text.

function The function to be performed on the contents of the parentheses.

parameter1...parameterN A series of parameters to execute before the results are passed as parameters to the function outside the parentheses.

Returns

Nothing.

Description

Operator; performs a grouping operation on one or more parameters, or surrounds one or more parameters and passes them as parameters to a function outside the parentheses.

Usage 1: Controls the order in which the operators are executed in the expression. Parentheses override the normal precedence order and cause the expressions within the parentheses to be evaluated first. When parentheses are nested, the contents of the innermost parentheses are evaluated before the contents of the outer ones.

Usage 2: Surrounds one or more parameters and passes them as parameters to the function outside the parentheses.

Example

Usage 1: The following statements illustrate the use of parentheses to control the order in which expressions are executed. The value of each expression is displayed below each line, as follows:

trace((2 + 3) * (4 + 5));
// displays 45
trace(2 + (3 * (4 + 5)));
// displays 29
trace(2 + (3 * 4) + 5);
// displays 19

Usage 2: The following examples illustrate the use of parentheses with functions.

getDate();
invoice(item, amount);
function traceParameter(param){
  trace(param);
}
traceParameter(2*2);

See also

with


- (minus)

Availability

Flash Player 4.

Usage

(Negation) -expression

(Subtraction) expression1 - expression2

Parameters

None.

Returns

Nothing.

Description

Operator (arithmetic); used for negating or subtracting.

Usage 1: When used for negating, it reverses the sign of the numerical expression.

Usage 2: When used for subtracting, it performs an arithmetic subtraction on two numerical expressions, subtracting expression2 from expression1. When both expressions are integers, the difference is an integer. When either or both expressions are floating-point numbers, the difference is a floating-point number.

Example

Usage 1: The following statement reverses the sign of the expression 2 + 3.

-(2 + 3)

The result is -5.

Usage 2: The following statement subtracts the integer 2 from the integer 5.

5 - 2

The result is 3, which is an integer.

Usage 2: The following statement subtracts the floating-point number 1.5 from the floating-point number 3.25.

3.25 - 1.5

The result is 1.75, which is a floating-point number.


* (multiplication)

Availability

Flash Player 4.

Usage

expression1 * expression2

Parameters

None.

Returns

Nothing.

Description

Operator (arithmetic); multiplies two numerical expressions. If both expressions are integers, the product is an integer. If either or both expressions are floating-point numbers, the product is a floating-point number.

Example

Usage 1: The following statement multiplies the integers 2 and 3.

2 * 3

The result is 6, which is an integer.

Usage 2: This statement multiplies the floating-point numbers 2.0 and 3.1416.

2.0 * 3.1416

The result is 6.2832, which is a floating-point number.


*= (multiplication assignment)

Availability

Flash Player 4.

Usage

expression1 *= expression2

Parameters

None.

Returns

Nothing.

Description

Operator (arithmetic compound assignment); assigns expression1 the value of expression1 * expression2. For example, the following two expressions are the same:

x *= y
x = x * y

Example

Usage 1: The following example assigns the value 50 to the variable x.

x = 5;
y = 10;
trace (x *= y);
// returns 50

Usage 2: The second and third lines of the following example calculate the expressions on the right-hand side of the equals sign and assign the results to x and y.

i = 5;
x = 4 - 6;
y = i + 2;
trace(x *= y);
// returns -14

See also

* (multiplication)


, (comma)

Availability

Flash Player 4.

Usage

expression1, expression2

Parameters

None.

Returns

Nothing.

Description

Operator; evaluates expression1, then expression2, and returns the value of expression2. This operator is primarily used with the for loop statement.

Example

The following code sample uses the comma operator:

var a=1, b=2, c=3;

This is equivalent to writing the following code:

var a=1;
var b=2;
var c=3;


. (dot)

Availability

Flash Player 4.

Usage

object.property_or_method
instancename.variable
instancename.childinstance.variable

Parameters

object An instance of a class. The object can be an instance of any of the built-in ActionScript classes or a custom class. This parameter is always to the left of the dot (.) operator.

property_or_method The name of a property or method associated with an object. All of the valid method and properties for the built-in classes are listed in the method and property summary tables for that class. This parameter is always to the right of the dot (.) operator.

instancename The instance name of a movie clip.

childinstance A movie clip instance that is a child of, or nested in, another movie clip.

variable A variable on the Timeline of the movie clip instance name to the left of the dot (.) operator.

Returns

Nothing.

Description

Operator; used to navigate movie clip hierarchies in order to access nested (child) movie clips, variables, or properties. The dot operator is also used to test or set the properties of an object, execute a method of an object, or create a data structure.

Example

The following statement identifies the current value of the variable hairColor in the movie clip person_mc.

person_mc.hairColor

This is equivalent to the following Flash 4 syntax:

/person_mc:hairColor


: (type)

Availability

Flash Player 6.

Usage

[modifiers] [var] variableName:[type]
function functionName():[type] { ... }
function functionName(parameter1[:type], ... , parameterN[:type]) { ... }

Parameters

variableName An identifier for a variable.

type A native data type, class name that you have defined, or interface name.

functionName An identifier for a function.

parameter An identifier for a function parameter.

Description

Operator; specifies the variable type, function return type, or function parameter type. When used in a variable declaration or assignment, this operator specifies the variable's type; when used in a function declaration or definition, this operator specifies the function's return type; when used with a function parameter in a function definition, this operator specifies the variable type expected for that parameter.

Types are a compile-time-only feature. All types are checked at compile time, and errors are generated when there is a mismatch. (For more information, see Error Messages.) Mismatches can occur during assignment operations, function calls, and class member dereferencing using the dot (.) operator. To avoid type mismatch errors, use explicit typing (see Strict data typing).

Types that you can use include all native object types, classes and interfaces that you define, and Void and Function (which exist only as types, not as objects). The recognized native types are Array, Boolean, Button, Color, CustomActions, Date, Function, LoadVars, LocalConnection, Microphone, MovieClip, NetConnection, NetStream, Number, Object, SharedObject, Sound, String, TextField, TextFormat, Video, Void, XML, XMLNode, and XMLSocket.

Example

Usage 1: The following example declares a public variable named userName whose type is String and assigns an empty string to it.

public var userName:String = "";

Usage 2: This example demonstrates how to specify a function's parameter type. The following code defines a function named setDate() that takes a parameter named currentDate of type Date.

function setDate(currentDate:Date) {
   this.date = currentDate;
}

Usage 3: The following code defines a function named squareRoot() that takes a parameter named val of the Number type and returns the square root of val, also a Number type.

function squareRoot(val:Number):Number {
  return Math.sqrt(val);
}


?: (conditional)

Availability

Flash Player 4.

Usage

expression1 ? expression2 : expression3

Parameters

expression1 An expression that evaluates to a Boolean value, usually a comparison expression, such as x < 5.

expression2, expression3 Values of any type.

Returns

Nothing.

Description

Operator; instructs Flash to evaluate expression1, and if the value of expression1 is true, it returns the value of expression2; otherwise it returns the value of expression3.

Example

The following statement assigns the value of variable x to variable z because expression1 evaluates to true:

x = 5;
y = 10;
z = (x < 6) ? x: y;
trace (z);
// returns 5


/ (division)

Availability

Flash Player 4.

Usage

expression1 / expression2

Parameters

expression A number or a variable that evaluates to a number.

Returns

Nothing.

Description

Operator (arithmetic); divides expression1 by expression2. The result of the division operation is a double-precision floating-point number.

Example

The following statement divides the floating-point number 22.0 by 7.0 and then displays the result in the Output panel.

trace(22.0 / 7.0);

The result is 3.1429, which is a floating-point number.


// (comment delimiter)

Availability

Flash 1.

Usage

// comment

Parameters

comment Any characters.

Returns

Nothing.

Description

Comment; indicates the beginning of a script comment. Any characters that appear between the comment delimiter // and the end-of-line character are interpreted as a comment and ignored by the ActionScript interpreter.

Example

This script uses comment delimiters to identify the first, third, fifth, and seventh lines as comments.

// record the X position of the ball movie clip
ballX = ball._x;
// record the Y position of the ball movie clip
ballY = ball._y;
// record the X position of the bat movie clip
batX = bat._x;
// record the Y position of the bat movie clip
batY = bat._y;

See also

/* (comment delimiter)


/* (comment delimiter)

Availability

Flash Player 5.

Usage

/* comment */
/*
comment
comment
*/

Parameters

comment Any characters.

Returns

Nothing.

Description

Comment; indicates one or more lines of script comments. Any characters that appear between the opening comment tag /* and the closing comment tag */, are interpreted as a comment and ignored by the ActionScript interpreter. Use the first type of syntax to identify single-line comments. Use the second type of syntax to identify comments on multiple successive lines. Leaving off the closing tag */ when using this form of comment delimiter returns an error message.

Example

This script uses comment delimiters at the beginning of the script.

/* records the X and Y positions of the
ball and bat movie clips
*/

ballX = ball._x;
ballY = ball._y;
batX = bat._x;
batY = bat._y;

See also

// (comment delimiter)


/= (division assignment)

Availability

Flash Player 4.

Usage

expression1 /= expression2

Parameters

expression1,expression2 A number or a variable that evaluates to a number.

Returns

Nothing.

Description

Operator (arithmetic compound assignment); assigns expression1 the value of expression1 / expression2. For example, the following two statements are the same:

x /= y
x = x / y

Example

The following code illustrates using the /= operator with variables and numbers.

x = 10;
y = 2;
x /= y;
// x now contains the value 5


[] (array access)

Availability

Flash Player 4.

Usage

my_array = ["a0", a1,...aN]
myMultiDimensional_array = [["a0",...aN],...["a0",...aN]]
my_array[E] = value
myMultiDimensional_array[E][E] = value
object["value"]

Parameters

my_array The name of an array.

a0, a1,...aN Elements in an array.

myMultiDimensional_array The name of a simulated multidimensional array.

E The number (or index) of an element in an array.

object The name of an object.

value A string or an expression that evaluates to a string that names a property of the object.

Returns

Nothing.

Description

Operator; initializes a new array or multidimensional array with the specified elements (a0, and so on), or accesses elements in an array. The array access operator lets you dynamically set and retrieve instance, variable, and object names. It also lets you access object properties.

Usage 1: An array is an object whose properties are called elements, which are each identified by a number called an index. When you create an array, you surround the elements with the array access operator (or brackets). An array can contain elements of various types. For example, the following array, called employee, has three elements; the first is a number and the second two are strings (inside quotation marks).

employee = [15, "Barbara", "Erick"];

Usage 2: You can nest brackets to simulate multidimensional arrays. The following code creates an array called ticTacToe with three elements; each element is also an array with three elements.

ticTacToe = [[1,2,3],[4,5,6],[7,8,9]];

// choose Debug > List Variables in test movie mode
// to see a list of the array elements

Usage 3: Surround the index of each element with brackets to access it directly; you can add a new element to an array, change or retrieve the value of an existing element. The first element in an array is always 0:

my_array[0] = 15;
my_array[1] = "Hello";
my_array[2] = true;

You can use brackets to add a fourth element, as in the following:

my_array[3] = "George";

Usage 4: You can use brackets to access an element in a multidimensional array. The first set of brackets identifies the element in the original array, and the second set identifies the element in the nested array. The following line of code sends the number 6 to the Output panel.

ticTacToe = [[1,2,3],[4,5,6],[7,8,9]];
trace(ticTacToe[1][2]);
// returns 6

Usage 5: You can use the array access operator instead of the eval function to dynamically set and retrieve values for movie clip names or any property of an object:

name["mc" + i] = "left_corner";

Example

Usage 1: The following code samples show two different ways of creating a new empty Array object; the first line uses brackets.

my_array =[];
my_array = new Array();

Usage 1 and 2: The following example creates an array called employee_array and uses the trace() action to send the elements to the Output panel. In the fourth line, an element in the array is changed and the fifth line sends the newly modified array to the Output panel:

employee_array = ["Barbara", "George", "Mary"];
trace(employee_array);
// Barbara, George, Mary
employee_array[2]="Sam";
trace(employee_array);
// Barbara, George, Sam

Usage 3: In the following example, the expression inside the brackets ("piece" + i) is evaluated and the result is used as the name of the variable to be retrieved from the my_mc movie clip. In this example, the variable i must live on the same Timeline as the button. If the variable i is equal to 5, for example, the value of the variable piece5 in the my_mc movie clip will be displayed in the Output panel:

on(release){
  x = my_mc["piece"+i];
  trace(x);
}

Usage 3: In the following code, the expression inside the brackets is evaluated and the result is used as the name of the variable to be retrieved from movie clip name_mc:

name_mc["A" + i];

If you are familiar with the Flash 4 ActionScript slash syntax, you can use the eval function to accomplish the same result:

eval("name.A" & i);

Usage 3: You can also use the array access operator on the left side of an assignment statement to dynamically set instance, variable, and object names:

name[index] = "Gary";

See also

Array class, Object class, eval()


^ (bitwise XOR)

Availability

Flash Player 5.

Usage

expression1 ^ expression2

Parameters

expression1,expression2 A number.

Returns

None.

Description

Operator (bitwise); converts expression1 and expression2 to 32-bit unsigned integers, and returns a 1 in each bit position where the corresponding bits in expression1 or expression1, but not both, are 1.

Example

The following example uses the bitwise XOR operator on the decimals 15 and 9 and assigns the result to the variable x.

// 15 decimal = 1111 binary
// 9 decimal = 1001 binary
x = 15 ^ 9
trace(x)
// 1111 ^ 1001 = 0110
// returns 6 decimal( = 0110 binary)


^= (bitwise XOR assignment)

Availability

Flash Player 5.

Usage

expression1 ^= expression2

Parameters

expression1,expression2 Integers and variables.

Returns

None.

Description

Operator (bitwise compound assignment); assigns expression1 the value of expression1 ^ expression2. For example, the following two statements are the same:

x ^= y
x = x ^ y

Example

The following is an example of a ^= operation.

// 15 decimal = 1111 binary
x = 15;
// 9 decimal = 1001 binary
y = 9;
trace(x ^= y);
//returns 6 decimal ( = 0110 binary)

See also

^ (bitwise XOR)


{} (object initializer)

Availability

Flash Player 5.

Usage

object = {name1: value1, name2: value2,...nameN: valueN}

Parameters

object The object to create.

name1,2,...N The names of the properties.

value1,2,...N The corresponding values for each name property.

Returns

None.

Description

Operator; creates a new object and initializes it with the specified name and value property pairs. Using this operator is the same as using the new Object syntax and populating the property pairs using the assignment operator. The prototype of the newly created object is generically named the Object object.

Example

The first line of the following code creates an empty object using the object initializer operator; the second line creates a new object using a constructor function.

object = {};
object = new Object();

The following example creates an object account and initializes the properties name, address, city, state, zip, and balance with accompanying values.

account = { name: "Betty Skate",
  address: "123 Main Street",
  city: "Blossomville",
  state: "California",
  zip: "12345",
  balance: "1000" };

The following example shows how array and object initializers can be nested within each other.

person = { name: "Gina Vechio",
  children: [ "Ruby", "Chickie", "Puppa"] };

The following example uses the information in the previous example and produces the same result using constructor functions.

person = new Object();
person.name = 'Gina Vechio';
person.children = new Array();
person.children[0] = 'Ruby';
person.children[1] = 'Chickie';
person.children[2] = 'Puppa';

See also

[] (array access), new, Object class


| (bitwise OR)

Availability

Flash Player 5.

Usage

expression1 | expression2

Parameters

expression1,expression2 A number.

Returns

None.

Description

Operator (bitwise); converts expression1 and expression2 to 32-bit unsigned integers, and returns a 1 in each bit position where the corresponding bits of either expression1 or expression2 are 1.

Example

The following is an example of a bitwise OR operation.

// 15 decimal = 1111 binary
x = 15;
// 9 decimal = 1001 binary
y = 9;
trace(x | y);
// 1111 | 0011 = 1111
//  returns 15 decimal (= 1111 binary)


|| (logical OR)

Availability

Flash Player 4.

Usage

expression1 || expression2

Parameters

expression1,expression2 A Boolean value or an expression that converts to a Boolean value.

Returns

A Boolean value.

Description

Operator (logical); evaluates expression1 and expression2. The result is true if either or both expressions evaluate to true; the result is false only if both expressions evaluate to false. You can use the logical OR operator with any number of operands; if any operand evaluates to true, the result is true.

With non-Boolean expressions, the logical OR operator causes Flash to evaluate the expression on the left; if it can be converted to true, the result is true. Otherwise, it evaluates the expression on the right and the result is the value of that expression.

Example

Usage 1: The following example uses the || operator in an if statement. The second expression evaluates to true so the final result is true:

x = 10
y = 250
start = false
if(x > 25 || y > 200 || start){
  trace('the logical OR test passed');
}

Usage 2: This example demonstrates how a non-Boolean expression can produce an unexpected result. If the expression on the left converts to true, that result is returned without converting the expression on the right.

function fx1(){
  trace ("fx1 called");
  returns true;
}
function fx2(){
  trace ("fx2 called");
  return true;
}
if (fx1() || fx2()){
  trace ("IF statement entered");
}
// The following is sent to the Output panel:
// fx1 called
// IF statement entered


|= (bitwise OR assignment)

Availability

Flash Player 5.

Usage

expression1 |= expression2

Parameters

expression1,expression2 A number or variable.

Returns

None.

Description

Operator (bitwise compound assignment); assigns expression1 the value of expression1 | expression2. For example, the following two statements are the same:

x |= y;
x = x | y;

Example

The following example uses the |= operator:

// 15 decimal = 1111 binary
x = 15;
// 9 decimal = 1001 binary
y = 9;
trace(x |= y);
// 1111 |= 1001
//  returns 15 decimal (= 1111 binary)

See also

| (bitwise OR)


~ (bitwise NOT)

Availability

Flash Player 5.

Usage

~ expression

Parameters

expression A number.

Returns

None.

Description

Operator (bitwise); converts the expression to a 32-bit unsigned integer, then inverts the bits. A bitwise NOT operation changes the sign of a number and subtracts 1.

Example

The following example shows a bitwise NOT operation performed on a variable.

a = 0;
trace ("when a = 0, ~a = "+~a);
// when a = 0, ~a = -1
a = 1;
trace ("when a = 1, ~a = "+~a);
// when a = 0, ~a = -2
// therefore, ~0=-1 and ~1=-2


+ (addition)

Availability

Flash Player 4; Flash Player 5. In Flash 5 and later, + is either a numeric operator or string concatenator depending on the data type of the parameter. In Flash 4, + is only a numeric operator. Flash 4 files brought into the Flash 5 or later authoring environment undergo a conversion process to maintain data type integrity. The following example illustrates the conversion of a Flash 4 file containing a numeric quality comparison:

Flash 4 file:

x + y

Converted Flash 5 or later file:

Number(x) + Number(y)

Usage

expression1 + expression2

Parameters

expression1,expression2 A number or string.

Returns

None.

Description

Operator; adds numeric expressions or concatenates (combines) strings. If one expression is a string, all other expressions are converted to strings and concatenated.

If both expressions are integers, the sum is an integer; if either or both expressions are floating-point numbers, the sum is a floating-point number.

Example

Usage 1: The following example concatenates two strings and displays the result in the Output panel.

name = "Cola";
instrument = "Drums";
trace (name + " plays " + instrument);

Usage 2: Variables associated with dynamic and input text fields have the data type String. In the following example, the variable deposit is an input text field on the Stage. After a user enters a deposit amount, the script attempts to add deposit to oldBalance. However, because deposit is a String data type, the script concatenates (combines to form one string) the variable values rather than summing them.

oldBalance = 1345.23;
currentBalance = deposit + oldBalance;
trace (currentBalance);

For example, if a user enters 475 in the deposit text field, the trace() action sends the value 4751345.23 to the Output panel.

To correct this, use the Number() function to convert the string to a number, as in the following:

currentBalance = Number(deposit) + oldBalance;

Usage 3: This statement adds the integers 2 and 3 and displays the resulting integer, 5, in the Output panel:

trace (2 + 3);

This statement adds the floating-point numbers 2.5 and 3.25 and displays the result, 5.75, a floating-point number, in the Output panel:

trace (2.5 + 3.25);

See also

_accProps


+= (addition assignment)

Availability

Flash Player 4.

Usage

expression1 += expression2

Parameters

expression1,expression2 A number or string.

Returns

Nothing.

Description

Operator (arithmetic compound assignment); assigns expression1 the value of expression1 + expression2. For example, the following two statements have the same result:

x += y;
x = x + y;

This operator also performs string concatenation. All the rules of the addition operator (+) apply to the addition assignment (+=) operator.

Example

The following example shows a numeric use of the += operator.

x = 5;
y = 10;
x += y;
trace(x);
//x returns 15

This example uses the += operator with a string expression and sends "My name is Gilbert" to the Output panel.

x = "My name is "
x += "Gilbert"
trace (x)
// returns "My name is Gilbert"

See also

+ (addition)


< (less than)

Availability

Flash Player 4; Flash Player 5. In Flash 5 and later, the < (less than) operator is a comparison operator capable of handling various data types. In Flash 4, < is an numeric operator. Flash 4 files brought into the Flash 5 or later authoring environment undergo a conversion process to maintain data type integrity. The following illustrates the conversion of a Flash 4 file containing a numeric quality comparison.

Flash 4 file:

x < y

Converted Flash 5 or later file:

Number(x) < Number(y)

Usage

expression1 < expression2

Parameters

expression1,expression2 A number or string.

Description

Operator (comparison); compares two expressions and determines whether expression1 is less than expression2; if so, the operator returns true. If expression1 is greater than or equal to expression2, the operator returns false. String expressions are evaluated using alphabetical order; all capital letters come before lowercase letters.

Example

The following examples illustrate true and false returns for both numeric and string comparisons.

3 < 10;
// true

10 < 3;
// false

"Allen" < "Jack";
// true

"Jack" < "Allen";
// false

"11" < "3";
//true

"11" < 3;
// numeric comparison
// false

"C" < "abc";
// false

"A" < "a";
// true


<< (bitwise left shift)

Availability

Flash Player 5.

Usage

expression1 << expression2

Parameters

expression1 A number or expression to be shifted left.

expression2 A number or expression that converts to an integer from 0 to 31.

Returns

Nothing.

Description

Operator (bitwise); converts expression1 and expression2 to 32-bit integers, and shifts all of the bits in expression1 to the left by the number of places specified by the integer resulting from the conversion of expression2. The bit positions that are emptied as a result of this operation are filled in with 0. Shifting a value left by one position is the equivalent of multiplying it by 2.

Example

In the following example, the integer 1 is shifted 10 bits to the left.

x = 1 << 10

The result of this operation is x = 1024. This is because 1 decimal equals 1 binary, 1 binary shifted left by 10 is 10000000000 binary, and 10000000000 binary is 1024 decimal.

In the following example, the integer 7 is shifted 8 bits to the left.

x = 7 << 8

The result of this operation is x = 1792. This is because 7 decimal equals 111 binary, 111 binary shifted left by 8 bits is 11100000000 binary, and 11100000000 binary is 1792 decimal.

See also

>>= (bitwise right shift and assignment), >> (bitwise right shift), <<= (bitwise left shift and assignment)


<<= (bitwise left shift and assignment)

Availability

Flash Player 5.

Usage

expression1 <<= expression2

Parameters

expression1 A number or expression to be shifted left.

expression2 A number or expression that converts to an integer from 0 to 31.

Returns

Nothing.

Description

Operator (bitwise compound assignment); this operator performs a bitwise left shift operation and stores the contents as a result in expression1. The following two expressions are equivalent.

A <<= B
A = (A << B)

See also

<< (bitwise left shift), >>= (bitwise right shift and assignment), >> (bitwise right shift)


<= (less than or equal to)

Availability

Flash Player 4.

Flash 4 file:

x <= y

Converted Flash 5 or later file:

Number(x) <= Number(y)

Usage

expression1 <= expression2

Parameters

expression1,expression2 A number or string.

Returns

A Boolean value.

Description

Operator (comparison); compares two expressions and determines whether expression1 is less than or equal to expression2 ; if it is, the operator returns true. If expression1 is greater than expression2, the operator returns false. String expressions are evaluated using alphabetical order; all capital letters come before lowercase letters.

In Flash 5 or later, the less than or equal to (<=) operator is a comparison operator capable of handling various data types. In Flash 4, <= is a numeric operator. Flash 4 files brought into the Flash 5 or later authoring environment undergo a conversion process to maintain data type integrity. The following illustrates the conversion of a Flash 4 file containing a numeric quality comparison.

Example

The following examples illustrate true and false results for both numeric and string comparisons:

5 <= 10;
// true
2 <= 2;
// true
10 <= 3;
// false
"Allen" <= "Jack";
// true
"Jack" <= "Allen";
// false
"11" <= "3";
//true
"11" <= 3;
// numeric comparison
// false
"C" <= "abc";
// false
"A" <= "a";
// true


<> (inequality)

Availability

Flash 2.

Usage

expression1 <> expression2

Parameters

expression1,expression2 A number, string, Boolean value, variable, object, array, or function.

Returns

A Boolean value.

Description

Operator (inequality); tests for the exact opposite of the == operator. If expression1 is equal to expression2, the result is false. As with the == operator, the definition of equal depends on the data types being compared:

  • Numbers, strings, and Boolean values are compared by value.
  • Variables, objects, arrays, and functions are compared by reference.

This operator was deprecated in Flash 5, and Macromedia recommends that you use the != operator.

See also

!= (inequality)


= (assignment)

Availability

Flash Player 4.

Flash 4 file:

x = y

Converted Flash 5 or later file:

Number(x) == Number(y)

Usage

expression1 = expression2

Parameters

expression1 A variable, element of an array, or property of an object.

expression2 A value of any type.

Returns

Nothing.

Description

Operator; assigns the type of expression2 (the parameter on the right) to the variable, array element, or property in expression1.

In Flash 5 or later, = is an assignment operator, and the == operator is used to evaluate equality. In Flash 4, = is a numeric equality operator. Flash 4 files brought into the Flash 5 or later authoring environment undergo a conversion process to maintain data type integrity.

Example

The following example uses the assignment operator to assign the Number data type to the variable x.

x = 5

The following example uses the assignment operator to assign the String data type to the variable x.

x = "hello"

See also

== (equality)


-= (subtraction assignment)

Availability

Flash Player 4.

Usage

expression1 -= expression2

Parameters

expression1,expression2 A number or expression that evaluates to a number.

Returns

Nothing.

Description

Operator (arithmetic compound assignment); assigns expression1 the value of expression1 - expression2. For example, the following two statements are the same:

x -= y;
x = x - y;

String expressions must be converted to numbers; otherwise, NaN is returned.

Example

Usage 1: The following example uses the -= operator to subtract 10 from 5 and assign the result to the variable x.

x = 5;
y = 10;
x -= y
trace(x);
//returns -5

Usage 2: The following example shows how strings are converted to numbers.

x = "5";
y = "10";
x -= y;
trace(x);
// returns -5


== (equality)

Availability

Flash Player 5.

Usage

expression1 == expression2

Parameters

expression1,expression2 A number, string, Boolean value, variable, object, array, or function.

Returns

A Boolean value.

Description

Operator (equality); tests two expressions for equality. The result is true if the expressions are equal.

The definition of equal depends on the data type of the parameter:

  • Numbers and Boolean values are compared by value, and are considered equal if they have the same value.
  • String expressions are equal if they have the same number of characters and the characters are identical.
  • Variables, objects, arrays, and functions are compared by reference. Two variables are equal if they refer to the same object, array, or function. Two separate arrays are never considered equal, even if they have the same number of elements.

Example

Usage 1: The following example uses the == operator with an if statement:

a = "David" , b = "David";
if (a == b){
  trace("David is David");
}

Usage 2: These examples show the results of operations that compare mixed types.

x = "5"; y = "5";
trace(x == y);
// true

x = "5"; y = "66";
trace(x ==y);
// false

x = "chris"; y = "steve";
trace (x == y);
//false

See also

!= (inequality), === (strict equality), !== (strict inequality)


=== (strict equality)

Availability

Flash Player 6.

Usage

expression1 === expression2

Returns

A Boolean value.

Description

Operator; tests two expressions for equality; the strict equality operator performs just like the equality operator except that data types are not converted. The result is true if both expressions, including their data types, are equal.

The definition of equal depends on the data type of the parameter:

  • Numbers and Boolean values are compared by value, and are considered equal if they have the same value.
  • String expressions are equal if they have the same number of characters and the characters are identical.
  • Variables, objects, arrays, and functions are compared by reference. Two variables are equal if they refer to the same object, array, or function. Two separate arrays are never considered equal, even if they have the same number of elements.

Example

The following code displays the returned value of operations that use the equality, strict equality, and strict inequality operators.

s1 = new String("5");
s2 = new String("5");
s3 = new String("Hello");
n  = new Number(5);
b = new Boolean(true);

s1 == s2; // true
s1 == s3; // false
s1 == n; // true
s1 == b; // false

s1 === s2;  // true
s1 === s3; // false
s1 === n; // false
s1 === b; // false

s1 !== s2; // false
s1 !== s3; // true
s1 !== n; // true
s1 !== b; // true

See also

== (equality), != (inequality), === (strict equality)


> (greater than)

Availability

Flash Player 4.

Flash 4 file:

x > y

Converted Flash 5 or later file:

Number(x) > Number(y)

Usage

expression1 >expression2

Parameters

expression1,expression2 A number or string.

Returns

A Boolean value.

Description

Operator (comparison); compares two expressions and determines whether expression1 is greater than expression2 ; if it is, the operator returns true. If expression1 is less than or equal to expression2, the operator returns false. String expressions are evaluated using alphabetical order; all capital letters come before lowercase letters.

In Flash 5 or later, the greater than (>) operator is a comparison operator capable of handling various data types. In Flash 4, > is a numeric operator. Flash 4 files brought into the Flash 5 or later authoring environment undergo a conversion process to maintain data type integrity.


>= (greater than or equal to)

Availability

Flash Player 4.

Flash 4 file:

x > y

Converted Flash 5 or later file:

Number(x) > Number(y)

Usage

expression1 >= expression2

Parameters

expression1, expression2 A string, integer, or floating-point number.

Returns

A Boolean value.

Description

Operator (comparison); compares two expressions and determines whether expression1 is greater than or equal to expression2 (true), or whether expression1 is less than expression2 (false).

In Flash 5 or later, the greater than or equal to (>=) operator is a comparison operator capable of handling various data types. In Flash 4, >= is an numeric operator. Flash 4 files brought into the Flash 5 or later authoring environment undergo a conversion process to maintain data type integrity.


>> (bitwise right shift)

Availability

Flash Player 5.

Usage

expression1 >> expression2

Parameters

expression1 A number or expression to be shifted right.

expression2 A number or expression that converts to an integer from 0 to 31.

Returns

Nothing.

Description

Operator (bitwise); converts expression1 and expression2 to 32-bit integers, and shifts all of the bits in expression1 to the right by the number of places specified by the integer resulting from the conversion of expression2. Bits that are shifted to the right are discarded. To preserve the sign of the original expression, the bits on the left are filled in with 0 if the most significant bit (the bit farthest to the left) of expression1 is 0, and filled in with 1 if the most significant bit is 1. Shifting a value right by one position is the equivalent of dividing by 2 and discarding the remainder.

Example

The following example converts 65535 to a 32-bit integer, and shifts it 8 bits to the right.

x = 65535 >> 8

The result of the above operation is as follows:

x = 255

This is because 65535 decimal equals 1111111111111111 binary (sixteen 1's), 1111111111111111 binary shifted right by 8 bits is 11111111 binary, and 11111111 binary is 255 decimal. The most significant bit is 0 because the integers are 32-bit, so the fill bit is 0.

The following example converts -1 to a 32-bit integer and shifts it 1 bit to the right.

x = -1 >> 1

The result of the above operation is as follows:

x = -1

This is because -1 decimal equals 11111111111111111111111111111111 binary (thirty-two 1's), shifting right by one bit causes the least significant (bit farthest to the right) to be discarded and the most significant bit to be filled in with 1. The result is 11111111111111111111111111111111 (thirty-two 1's) binary, which represents the 32-bit integer -1.

See also

>>= (bitwise right shift and assignment)


>>= (bitwise right shift and assignment)

Availability

Flash Player 5.

Usage

expression1 =>>expression2

Parameters

expression1 A number or expression to be shifted left.

expression2 A number or expression that converts to an integer from 0 to 31.

Returns

Nothing.

Description

Operator (bitwise compound assignment); this operator performs a bitwise right-shift operation and stores the contents as a result in expression1.

Example

The following two expressions are equivalent.

A >>= B
A = (A >> B)

The following commented code uses the bitwise (>>=) operator. It is also an example of using all bitwise operators.

function convertToBinary(number){
  var result = "";
  for (var i=0; i<32; i++) {
    // Extract least significant bit using bitwise AND
    var lsb = number & 1;
    // Add this bit to our result string
    result = (lsb ? "1" : "0") + result;
    // Shift number right by one bit, to see next bit
    number >>= 1;}
  return result;
}
trace(convertToBinary(479));
// Returns the string 00000000000000000000000111011111
// The above string is the binary representation of the decimal
// number 479

See also

<< (bitwise left shift)


>>> (bitwise unsigned right shift)

Availability

Flash Player 5.

Usage

expression1 >>> expression2

Parameters

expression1 A number or expression to be shifted right.

expression2 A number or expression that converts to an integer between 0 and 31.

Returns

Nothing.

Description

Operator (bitwise); the same as the bitwise right shift (>>) operator except that it does not preserve the sign of the original expression because the bits on the left are always filled with 0.

Example

The following example converts -1 to a 32-bit integer and shifts it 1 bit to the right.

x = -1 >>> 1

The result of the above operation is as follows:

x = 2147483647

This is because -1 decimal is 11111111111111111111111111111111 binary (thirty-two 1's), and when you shift right (unsigned) by 1 bit, the least significant (rightmost) bit is discarded, and the most significant (leftmost) bit is filled with a 0. The result is 01111111111111111111111111111111 binary, which represents the 32-bit integer 2147483647.

See also

>>= (bitwise right shift and assignment)


>>>= (bitwise unsigned right shift and assignment)

Availability

Flash Player 5.

Usage

expression1 >>>= expression2

Parameters

expression1 A number or expression to be shifted left.

expression2 A number or expression that converts to an integer from 0 to 31.

Returns

Nothing.

Description

Operator (bitwise compound assignment); performs an unsigned bitwise right-shift operation and stores the contents as a result in expression1. The following two expressions are equivalent:

A >>>= B
A = (A >>> B)

See also

>>> (bitwise unsigned right shift), >>= (bitwise right shift and assignment)


Accessibility class

Availability

Flash Player 6 r65.

Description

The Accessibility class manages communication with screen readers. The methods of the Accessibility class are static—that is, you don't have to create an instance of the class to use its methods.

To get and set accessible properties for a specific object, such as a button, movie clip, or text field, use the _accProps property. To determine whether the player is running in an environment that supports accessibility aids, use System.capabilities.hasAccessibility.

Method summary for the Accessibility class

Method | Description
Accessibility.isActive() | Indicates whether a screen reader program is active.
Accessibility.updateProperties() | Updates the description of objects on the screen for screen readers.


Accessibility.isActive()

Availability

Flash Player 6 r65.

Usage

Accessibility.isActive()

Parameters

None.

Returns

A Boolean value of true if there are active Microsoft Active Accessibility (MSAA) clients and the player is running in an environment that supports communication between Flash Player and accessibility aids, false otherwise.

Description

Method; indicates whether an MSAA screen reader program is currently active and the player is running in an environment that supports communication between Flash Player and accessibility aids. Use this method when you want your application to behave differently in the presence of a screen reader.

To determine whether the player is running in an environment that supports accessibility aids, use System.capabilities.hasAccessibility.

Note: If you call this method within about one or two seconds of the first appearance of the Flash window in which your document is playing, you might get a return value of false even if there is an active MSAA client. This is because of an asynchronous communication mechanism between Flash and MSAA clients. You can work around this limitation by ensuring a delay of one to two seconds after loading your document before calling this method.

See also

Accessibility.updateProperties(), _accProps, System.capabilities.hasAccessibility


Accessibility.updateProperties()

Availability

Flash Player 6 r65.

Usage

Accessibility.updateProperties()

Parameters

None.

Returns

Nothing.

Description

Method; causes Flash Player to reexamine all accessibility properties, update its description of objects for screen readers, and, if necessary, send events to screen readers to indicate that changes have occurred. For information on setting accessibility properties, see _accProps.

To determine whether the player is running in an environment that supports accessibility aids, use System.capabilities.hasAccessibility.

If you modify the accessibility properties for multiple objects, only one call to Accessibility.updateProperties() is necessary; multiple calls can result in reduced performance and unintelligible screen reader results.

Example

The following ActionScript code takes advantage of dynamic accessibility properties. This example is from a nontextual button that can change which icon it displays.

function setIcon( newIconNum, newTextEquivalent )
{
   this.iconImage = this.iconImages[ newIconNum ];
   if ( newTextEquivalent != undefined )
   {
      if ( this._accProps == undefined )
         this._accProps = new Object();
      this._accProps.name = newTextEquivalent;
      Accessibility.updateProperties();
   }
}

See also

Accessibility.isActive(), _accProps, System.capabilities.hasAccessibility


_accProps

Availability

Flash Player 6 r65.

Usage

_accProps.propertyName
instanceName._accProps.propertyName

Parameters

propertyName An accessibility property name (see the following description for valid names).

instanceName The instance name assigned to an instance of a movie clip, button, dynamic text field, or input text field.

Description

Property; lets you control screen reader accessibility options for SWF files, movie clips, buttons, dynamic text fields, and input text fields at runtime. These properties override the corresponding settings available in the Accessibility panel during authoring. For changes to these properties to take effect, you must call Accessibility.updateProperties(). For information on the Accessibility panel, see The Flash Accessibility panel.

To determine whether the player is running in an environment that supports accessibility aids, use System.capabilities.hasAccessibility.

The following table lists the name and data type of each _accProps property, its equivalent setting in the Accessibility panel, and the kinds of objects to which the property can be applied. The term inverse logic means that the property setting is the inverse of the corresponding setting in the Accessibility panel. For example, setting the silent property to true is equivalent to deselecting the Make Movie Accessible or Make Object Accessible option.

Property | Data type | Equivalent in Accessibility panel | Applies to
silent | Boolean | Make Movie Accessible/ Make Object Accessible (inverse logic) | Whole movies Movie clips Buttons Dynamic text Input text
forceSimple | Boolean | Make Child Objects Accessible (inverse logic) | Whole movies Movie clips
name | String | Name | Whole movies Movie clips Buttons Input text
description | String | Description | Whole movies Movie clips Buttons Dynamic text Input text
shortcut | String | Shortcut* | Movie clips Buttons Input text

*For information on assigning a keyboard shortcut to an accessible object, see Key.addListener().

To specify settings that correspond to the Tab index setting in the Accessibility panel, use the Button.tabIndex, MovieClip.tabIndex, or TextField.tabIndex property.

There is no way to specify an Auto Label setting at runtime.

When used without the instanceName parameter, changes made to _accProps properties apply to the whole movie. For example, the following code sets the Accessibility name property for the whole movie to the string "Pet Store", and then calls Accessibility.updateProperties() to effect that change.

_accprops.name = "Pet Store";
Accessbility.updateProperties();

In contrast, the following code sets the name property for a movie clip with the instance name price_mc to the string "Price":

price_mc._accProps.name = "Price";
Accessbility.updateProperties();

If you are specifying several accessibility properties, make as many changes as you can before calling Accessibility.updateProperties(), instead of calling it after each property statement:

_accprops.name = "Pet Store";
animal_mc._accProps.name = "Animal";
animal_mc._accProps.description = "Cat, dog, fish, etc.";
price_mc._accProps.name = "Price";
price_mc._accProps.description = "Cost of a single item";
Accessbility.updateProperties();

If you don't specify an accessibility property for a movie or an object, any values set in the Accessibility panel are implemented.

After you specify an accessibility property, you can't revert its value to a value set in the Accessibility panel. However, you can set the property to its default value (false for Boolean values, empty strings for string values) by deleting the _accProps object:

my_mc._accProps.silent = true; // set a property
// other code here
delete my_mc._accProps.silent; // revert to default value

To revert all accessibility values for an object to default values, you can delete the instanceName._accProps object:

delete my_btn._accProps;

To revert accessibility values for all objects to default values, you can delete the global _accProps object:

delete _accProps;

If you specify a property for an object type that doesn't support that property, the property assignment is ignored and no error is thrown. For example, the forceSimple property isn't supported for buttons, so a line like the following is ignored:

my_btn._accProps.forceSimple = false; //ignored

Example

Here is some example ActionScript code that takes advantage of dynamic accessibility properties. You would assign this code to a nontextual icon button component that can change which icon it displays.

function setIcon( newIconNum, newTextEquivalent )
{
   this.iconImage = this.iconImages[ newIconNum ];
   if ( newTextEquivalent != undefined )
   {
      if ( this._accProps == undefined )
         this._accProps = new Object();
      this._accProps.name = newTextEquivalent;
      Accessibility.updateProperties();
   }
}

See also

Accessibility.isActive(), Accessibility.updateProperties(), System.capabilities.hasAccessibility


add

Availability

Flash Player 4.

Usage

string1 add string2

Parameters

string1, string2 A string.

Returns

Nothing.

Description

Operator; concatenates (combines) two or more strings. The add operator replaces the Flash 4 add (&) operator; Flash Player 4 files that use the & operator are automatically converted to use the add operator for string concatenation when brought into the Flash 5 or later authoring environment. However, the add operator was deprecated in Flash Player 5, and Macromedia recommends that you use the + operator when creating content for Flash Player 5 or later. Use the add operator to concatenate strings if you are creating content for Flash Player 4 or earlier versions of the player.

See also

+ (addition)


and

Availability

Flash Player 4.

Usage

condition1 and condition2

Parameters

condition1,condition2 Conditions or expressions that evaluate to true or false.

Returns

Nothing.

Description

Operator; performs a logical AND operation in Flash Player 4. If both expressions evaluate to true, then the entire expression is true. This operator was deprecated in Flash 5, and Macromedia recommends that you use the && operator.

See also

&& (logical AND)


Arguments class

Availability

Flash Player 5; property added in Flash Player 6.

Description

The Arguments class is an array that contains the values that were passed as parameters to any function. Each time a function is called in ActionScript, an Arguments object is automatically created for that function. A local variable, arguments, is also created and lets you refer to the Arguments object.

Property summary for the Arguments class

Property | Description
arguments.callee | Refers to the function being called.
arguments.caller | Refers to the calling function.
arguments.length | The number of parameters passed to a function.


arguments.callee

Availability

Flash Player 5.

Usage

arguments.callee

Description

Property; refers to the function that is currently being called.

Example

You can use the arguments.callee property to make an anonymous function that is recursive, as in the following:

factorial = function (x) {
  if (x <= 1) {
    return 1;
  } else {
    return x * arguments.callee(x-1);
  }
};

The following is a named recursive function:

function factorial (x) {
  if (x <= 1) {
    return 1;
  } else {
    return x * factorial(x-1);
  }
}


arguments.caller

Availability

Flash Player 6.

Usage

arguments.caller

Description

Property; refers to the calling function.


arguments.length

Availability

Flash Player 5.

Usage

arguments.length

Description

Property; the number of parameters actually passed to a function.


Array class

Availability

Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly).

Description

The Array class lets you access and manipulate arrays. An array is an object whose properties are identified by a number representing their position in the array. This number is referred to as the index. All arrays are zero-based, which means that the first element in the array is [0], the second element is [1], and so on. In the following example, my_array contains the months of the year.

my_array[0] = "January"
my_array[1] = "February"
my_array[2] = "March"
my_array[3] = "April"

To create an Array object, use the constructor new Array() or the array access operator ([]). To access the elements of an array, use the array access operator ([]).

Method summary for the Array class

Method | Description
Array.concat() | Concatenates the parameters and returns them as a new array.
Array.join() | Joins all elements of an array into a string.
Array.pop() | Removes the last element of an array and returns its value.
Array.push() | Adds one or more elements to the end of an array and returns the array's new length.
Array.reverse() | Reverses the direction of an array.
Array.shift() | Removes the first element from an array and returns its value.
Array.slice() | Extracts a section of an array and returns it as a new array.
Array.sort() | Sorts an array in place.
Array.sortOn() | Sorts an array based on a field in the array.
Array.splice() | Adds and removes elements from an array.
Array.toString() | Returns a string value representing the elements in the Array object.
Array.unshift() | Adds one or more elements to the beginning of an array and returns the array's new length.

Property summary for the Array class

Property | Description
Array.length | A nonzero-based integer specifying the number of elements in the array.

Constructor for the Array class

Availability

Flash Player 5.

Usage

new Array()
new Array(length)
new Array(element0, element1, element2,...elementN)

Parameters

length An integer specifying the number of elements in the array. In the case of noncontiguous elements, the length parameter specifies the index number of the last element in the array plus 1.

element0...elementN A list of two or more arbitrary values. The values can be numbers, strings, objects, or other arrays. The first element in an array always has an index or position of 0.

Returns

A reference to an Array object.

Description

Constructor; lets you create an array. You can use the constructor to create different types of arrays: an empty array, an array with a specific length but whose elements have no values, or an array whose elements have specific values.

Usage 1: If you don't specify any parameters, an array with a length of 0 is created.

Usage 2: If you specify only a length, an array is created with length number of elements with no values.

Usage 3: If you use the element parameters to specify values, an array is created with specific values.

Example

Usage 1: The following example creates a new Array object with an initial length of 0.

my_array = new Array();
trace(my_array.length); // returns 0

Usage 2: The following example creates a new Array object with an initial length of 4.

my_array = new Array(4);
trace(my_array.length); // returns 4

Usage 3: The following example creates the new Array object go_gos_array, with an initial length of 5.

go_gos_array = new Array("Belinda", "Gina", "Kathy", "Charlotte", "Jane");
trace(my_array.length); // returns 5
trace(go_gos_array.join(", ")); // displays elements

The initial elements of the go_gos array are identified as follows:

go_gos_array[0] = "Belinda";
go_gos_array[1] = "Gina";
go_gos_array[2] = "Kathy";
go_gos_array[3] = "Charlotte";
go_gos_array[4] = "Jane";

The following code adds a sixth element to the go_gos_array array and changes the second element:

go_gos_array[5] = "Donna";
go_gos_array[1] = "Nina"
trace(go_gos_array.join(" + "));

See also

Array.length, [] (array access)


Array.concat()

Availability

Flash Player 5.

Usage

my_array.concat( [ value0, value1,...valueN ])

Parameters

value0,...valueN Numbers, elements, or strings to be concatenated in a new array. If you don't pass any values, a duplicate of my_array is created.

Returns

Nothing.

Description

Method; concatenates the elements specified in the parameters with the elements in my_array, and creates a new array. If the value parameters specify an array, the elements of that array are concatenated, rather than the array itself. The array my_array is left unchanged.

Example

The following code concatenates two arrays.

alpha_array = new Array("a","b","c");
numeric_array = new Array(1,2,3);
alphaNumeric_array=alpha_array.concat(numeric_array);
trace(alphaNumeric_array);
// creates array ["a","b","c",1,2,3]

The following code concatenates three arrays.

num1_array = [1,3,5];
num2_array = [2,4,6];
num3_array = [7,8,9];
nums_array=num1_array.concat(num2_array,num3_array)
trace(nums_array);
// creates array [1,3,5,2,4,6,7,8,9]

Nested arrays are not flattened in the same way normal arrays are. The elements in a nested array are not broken into separate elements in array x_array, as in the following example.

a_array = new Array ("a","b","c");

// 2 and 3 are elements in a nested array
n_array = new Array(1, [2, 3], 4);

x_array = a_array.concat(n_array);
trace(x_array[0]); // "a"
trace(x_array[1]); // "b"
trace(x_array[2]); // "c"
trace(x_array[3]); // 1
trace(x_array[4]); // 2, 3
trace(x_array[5]); // 4


Array.join()

Availability

Flash Player 5.

Usage

my_array.join([separator])

Parameters

separator A character or string that separates array elements in the returned string. If you omit this parameter, a comma is used as the default separator.

Returns

String.

Description

Method; converts the elements in an array to strings, inserts the specified separator between the elements, concatenates them, and returns the resulting string. A nested array is always separated by a comma, not by the separator passed to the join() method.

Example

The following example creates an array with three elements: Earth, Moon, and Sun. It then joins the array three times—first using the default separator (a comma and a space), then using a dash, and then using a plus sign (+)—and displays them in the Output panel:

a_array = new Array("Earth","Moon","Sun")
trace(a_array.join());
// returns Earth, Moon, Sun
trace(a_array.join(" - "));
// returns Earth - Moon - Sun
trace(a_array.join(" + "));
// returns Earth + Moon + Sun


Array.length

Availability

Flash Player 5.

Usage

my_array.length

Description

Property; a nonzero-based integer specifying the number of elements in the array. This property is automatically updated when new elements are added to the array. When you assign a value to an array element (for example, my_array[index] = value), if index is a number, and index+1 is greater than the length property, the length property is updated to index+1.

Example

The following code explains how the length property is updated.

my_array = new Array();
trace(my_array.length); // initial length is 0
my_array[0] = 'a';
trace(my_array.length); // my_array.length is updated to 1
my_array[1] = 'b';
trace(my_array.length); // my_array.length is updated to 2
my_array[9] = 'c';
trace(my_array.length); // my_array.length is updated to 10


Array.pop()

Availability

Flash Player 5.

Usage

my_array.pop()

Parameters

None.

Returns

The value of the last element in the specified array.

Description

Method; removes the last element from an array and returns the value of that element.

Example

The following code creates the myPets array containing four elements, then removes its last element.

myPets = ["cat", "dog", "bird", "fish"];
popped = myPets.pop();
trace(popped);
// returns fish


Array.push()

Availability

Flash Player 5.

Usage

my_array.push(value,...)

Parameters

value One or more values to append to the array.

Returns

The length of the new array.

Description

Method; adds one or more elements to the end of an array and returns the array's new length.

Example

The following example creates the array myPets with two elements, cat and dog. The second line adds two elements to the array. After the push() method is called, the variable pushed contains four elements. Because the push() method returns the new length of the array, the trace() action in the last line sends the new length of myPets (4) to the Output panel:

myPets = ["cat", "dog"];
pushed = myPets.push("bird", "fish");
trace(pushed);


Array.reverse()

Availability

Flash Player 5.

Usage

my_array.reverse()

Parameters

None.

Returns

Nothing.

Description

Method; reverses the array in place.

Example

The following is an example of using this method.

var numbers_array = [1, 2, 3, 4, 5, 6];
trace(numbers_array.join()); //1,2,3,4,5,6
numbers_array.reverse();
trace(numbers_array.join()); // 6,5,4,3,2,1


Array.shift()

Availability

Flash Player 5.

Usage

my_array.shift()

Parameters

None.

Returns

The first element in an array.

Description

Method; removes the first element from an array and returns that element.

Example

The following code creates the array myPets and then removes the first element from the array and assigns it to the variable shifted.

var myPets_array = ["cat", "dog", "bird", "fish"];
shifted = myPets_array.shift();
trace(shifted); // returns "cat"

See also

Array.pop()


Array.slice()

Availability

Flash Player 5.

Usage

my_array.slice( [ start [ , end ] ] )

Parameters

start A number specifying the index of the starting point for the slice. If start is a negative number, the starting point begins at the end of the array, where -1 is the last element.

end A number specifying the index of the ending point for the slice. If you omit this parameter, the slice includes all elements from the start to the end of the array. If end is a negative number, the ending point is specified from the end of the array, where -1 is the last element.

Returns

An array.

Description

Method; extracts a slice or a substring of the array and returns it as a new array without modifying the original array. The returned array includes the start element and all elements up to, but not including, the end element.

If you don't pass any parameters, a duplicate of my_array is created.


Array.sort()

Availability

Flash Player 5; additional capabilities added in Flash Player 7.

Usage

my_array.sort()
my_array.sort(compareFunction)
my_array.sort(option | option |... )
my_array.sort(compareFunction, option | option |... )

Parameters

compareFunction An optional comparison function used to determine the sorting order of elements in an array. Given the elements A and B, the result of compareFunction can have one of the following three values:

  • -1 if A should appear before B in the sorted sequence
  • 0 if A = B
  • 1 if A should appear after B in the sorted sequence

option One or more numbers or strings, separated by the | (bitwise OR) operator, that change the behavior of the sort from the default. The following values are acceptable for option:

  • 1 or Array.CASEINSENSITIVE
  • 2 or Array.DESCENDING
  • 4 or Array.UNIQUE
  • 8 or Array.RETURNINDEXEDARRAY
  • 16 or Array.NUMERIC

For information on this parameter, see Array.sortOn().

Returns

The return value depends on whether you pass any parameters:

  • If you specify a value of 4 or Array.UNIQUE for option and two or more elements being sorted have identical sort fields, Flash returns a value of 0 and does not modify the array.
  • If you specify a value of 8 or Array.RETURNINDEXEDARRAY for option, Flash returns an array that reflects the results of the sort and does not modify the array.
  • Otherwise, Flash returns nothing and modifies the array to reflect the sort order.

Description

Method; sorts the elements in an array. Flash sorts according to ASCII (Unicode) values. If either of the elements being compared does not contain the field specified in the fieldName parameter, the field is assumed to be undefined, and the elements are placed consecutively in the sorted array in no particular order.

By default, Array.sort() works as follows:

  • Sorting is case sensitive (Z precedes a).
  • Sorting is ascending (a precedes b).
  • The array is modified to reflect the sort order; multiple elements that have identical sort fields are placed consecutively in the sorted array in no particular order.
  • Numeric fields are sorted as if they were strings, so 100 precedes 99, because "1" is a lower string value than "9".
  • Nothing is returned.

If you want to sort in another way, create a function to do the sorting and pass its name as the compareFunction parameter. You might do this, for example, if you want to sort alphabetically by last name, ascending, and then by ZIP code, descending.

If you want to specify one or more fields on which to sort, using either the default sort or the options parameter, use Array.sortOn().

Example

Usage 1: The following example shows the use of Array.sort() with and without a value passed for option:

var fruits_array = ["oranges", "apples", "strawberries", "pineapples", "cherries"];
trace(fruits_array.join());
fruits_array.sort();
trace(fruits_array.join());
fruits_array.sort(Array.DESCENDING);
trace(fruits_array.join());

The Output panel displays the following results:

oranges,apples,strawberries,pineapples,cherries  // original array
apples,cherries,oranges,pineapples,strawberries  // default sort
strawberries,pineapples,oranges,cherries,apples  // descending sort

Usage 2: The following example uses Array.sort() with a compare function.

var passwords = ["mom:glam","ana:ring","jay:mag","anne:home","regina:silly"];
function order (a,b){
  //Entries to be sorted are in form name:password
  //Sort using only the name part of the entry as a key.
  var name1 =a.split(":")[0 ];
  var name2 =b.split(":")[0 ];
  if (name1 <name2){
    return -1;
  }
  else if (name1 >name2){
    return 1;
  }
  else {
    return 0;
  }
}
trace ("Unsorted:");
trace (passwords.join());

passwords.sort(order);
trace ("Sorted:");
trace (passwords.join());

The Output panel displays the following results:

Unsorted:
mom:glam,ana:ring,jay:mag,anne:home,regina:silly
Sorted:
ana:ring,anne:home,jay:mag,mom:glam,regina:silly

See also

| (bitwise OR), Array.sortOn()


Array.sortOn()

Availability

Flash Player 6; additional capabilities added in Flash Player 7.

Usage

my_array.sortOn("fieldName" )
my_array.sortOn("fieldName", option | option |... )
my_array.sortOn( [ "fieldName" , "fieldName" , ... ] )
my_array.sortOn( [ "fieldName" , "fieldName" , ... ] , option | option |... )

Note: Where brackets ([]) are shown, you must include them in the code; that is, the brackets don't represent optional parameters.

Parameters

fieldName A string that identifies a field (in an element of the Array) to be used as the sort value.

option One or more numbers or strings, separated by the | (bitwise OR) operator, that change the behavior of the sort from the default. The following values are acceptable for option:

  • 1 or Array.CASEINSENSITIVE
  • 2 or Array.DESCENDING
  • 4 or Array.UNIQUE
  • 8 or Array.RETURNINDEXEDARRAY
  • 16 or Array.NUMERIC

Each of these options in discussed in more detail in "Description," below.

Returns

The return value depends on whether you pass any parameters:

  • If you specify a value of 4 or Array.UNIQUE for option, and two or more elements being sorted have identical sort fields, Flash returns a value of 0 and does not modify the array.
  • If you specify a value of 8 or Array.RETURNINDEXEDARRAY for option, Flash returns an array that reflects the results of the sort and does not modify the array.
  • Otherwise, Flash returns nothing and modifies the array to reflect the sort order.

Description

Method; sorts the elements in an array according to one or more fields in the array. If you pass multiple fieldName parameters, the first field represents the primary sort field, the second represents the next sort field, and so on. Flash sorts according to ASCII (Unicode) values. If either of the elements being compared does not contain the field specified in the fieldName parameter, the field is assumed to be undefined, and the elements are placed consecutively in the sorted array in no particular order.

By default, Array.sortOn() works as follows:

  • Sorting is case sensitive (Z precedes a).
  • Sorting is ascending (a precedes b).
  • The array is modified to reflect the sort order; multiple elements that have identical sort fields are placed consecutively in the sorted array in no particular order.
  • Numeric fields are sorted as if they were strings, so 100 precedes 99, because "1" is a lower string value than "9".
  • Nothing is returned.

You can use the option flags to override these defaults. The following examples use different forms of the option flag for illustration purposes. If you want to sort a simple array (for example, an array with only one field), or if you want to specify a sort order that the options parameter doesn't support, use Array.sort().

To pass multiple flags in numeric format, separate them with the | (bitwise OR) operator or add the values of the flags together. The following code shows three different ways to specify a numeric descending sort:

my_Array.sortOn(someFieldName, 2 | 16);
my_Array.sortOn(someFieldName, 18);
my_Array.sortOn(someFieldName, Array.DESCENDING | Array.NUMERIC);

Code hinting (see Using code hints) is enabled if you use the string form of the flag (for example, DESCENDING) rather than the numeric form (2).

Consider the following array:

var my_array:Array = new Array();
my_array.push({password: "Bob", age:29});
my_array.push({password: "abcd", age:3});
my_array.push({password: "barb", age:35});
my_array.push({password: "catchy", age:4});

Performing a default sort on the password field produces the following results:

my_array.sortOn("password")
// Bob
// abcd
// barb
// catchy

Performing a case-insensitive sort on the password field produces the following results:

my_array.sortOn("password", Array.CASEINSENSITIVE)
// abcd
// barb
// Bob
// catchy

Performing a case-insensitive, descending sort on the password field produces the following results:

my_array.sortOn("password", 1|2)
// catchy
// Bob
// barb
// abcd

Performing a default sort on the age field produces the following results:

my_array.sortOn("age")
// 29
// 3
// 35
// 4

Performing a numeric sort on the age field produces the following results:

my_array.sortOn("age", 16)
// 3
// 4
// 29
// 35

Performing a descending numeric sort on the age field produces the following results:

my_array.sortOn("age", 18)
// 35
// 29
// 4
// 3

Performing a sort changes the elements in the array as follows:

// Before sorting
// my_array[0].age = 29;
// my_array[1].age = 3;
// my_array[2].age = 35;
// my_array[3].age = 4;

// After any sort that doesn't pass a value of 8 for option
my_array.sortOn("age", Array.NUMERIC);
// my_array[0].age = 3;
// my_array[1].age = 4;
// my_array[2].age = 29;
// my_array[3].age = 35;

Performing a sort that returns an index array doesn't change the elements in the array:

// Before sorting
// my_array[0].age = 29;
// my_array[1].age = 3;
// my_array[2].age = 35;
// my_array[3].age = 4;

// After a sort that returns an array containing index values
// Note that the original array is unchanged.
// You can then use the returned array to display sorted information
// without modifying the original array.
var indexArray:Array = my_array.sortOn("age", Array.RETURNINDEXEDARRAY);
// my_array[0].age = 29;
// my_array[1].age = 3;
// my_array[2].age = 35;
// my_array[3].age = 4;

Example

This example creates a new array and sorts it according to the fields name and city: The first sort uses name as the first sort value and city as the second. The second sort uses city as the first sort value and name as the second.

var rec_array = new Array();
rec_array.push( { name: "john", city: "omaha", zip: 68144 } );
rec_array.push( { name: "john", city: "kansas city", zip: 72345 } );
rec_array.push( { name: "bob", city: "omaha", zip: 94010 } );
for(i=0; i<rec_array.length; i++) {
 trace(rec_array[i].name + ", " + rec_array[i].city);
}
// results in
// john, omaha
// john, kansas city
// bob, omaha

rec_array.sortOn( [ "name", "city" ]);
for(i=0; i<rec_array.length; i++) {
 trace(rec_array[i].name + ", " + rec_array[i].city);
}
// results in
// bob, omaha
// john, kansas city
// john, omaha

rec_array.sortOn( ["city", "name" ]);
for(i=0; i<rec_array.length; i++) {
 trace(rec_array[i].name + ", " + rec_array[i].city);
}
// results in
// john, kansas city
// bob, omaha
// john, omaha

See also

| (bitwise OR), Array.sort()


Array.splice()

Availability

Flash Player 5.

Usage

my_array.splice(start, deleteCount [, value0, value1...valueN])

Parameters

start The index of the element in the array where the insertion or deletion begins.

deleteCount The number of elements to be deleted. This number includes the element specified in the start parameter. If no value is specified for deleteCount, the method deletes all of the values from the start element to the last element in the array. If the value is 0, no elements are deleted.

value An optional parameter specifying the values to insert into the array at the insertion point specified in the start parameter.

Returns

Nothing.

Description

Method; adds and removes elements from an array. This method modifies the array without making a copy.


Array.toString()

Availability

Flash Player 5.

Usage

my_array.toString()

Parameters

None.

Returns

A string.

Description

Method; returns a string value representing the elements in the specified Array object. Every element in the array, starting with index 0 and ending with index my_array.length-1, is converted to a concatenated string and separated by commas.

Example

The following example creates my_array, converts it to a string, and displays 1,2,3,4,5 in the Output panel.

my_array = new Array();
my_array[0] = 1;
my_array[1] = 2;
my_array[2] = 3;
my_array[3] = 4;
my_array[4] = 5;
trace(my_array.toString());


Array.unshift()

Availability

Flash Player 5.

Usage

my_array.unshift(value1,value2,...valueN)

Parameters

value1,...valueN One or more numbers, elements, or variables to be inserted at the beginning of the array.

Returns

The new length of the array.

Description

Method; adds one or more elements to the beginning of an array and returns the array's new length.


Array()

Availability

Flash Player 6 .

Usage

Array()
Array( [element0 [, element1 , element2,...elementN ] ])

Parameters

element One or more elements to place in the array.

Returns

An array.

Description

Conversion function; creates a new, empty array or converts specified elements to an array. Using this function is similar to creating an array with the Array constructor (see Constructor for the Array class).


asfunction

Availability

Flash Player 5.

Usage

asfunction:function,"parameter"

Parameters

function An identifier for a function.

parameter A string that is passed to the function named in the function parameter.

Returns

Nothing.

Description

Protocol; a special protocol for URLs in HTML text fields. In HTML text fields, text may be hyperlinked using the HTML A tag. The HREF attribute of the A tag contains a URL that may be for a standard protocol like HTTP, HTTPS, or FTP. The asfunction protocol is an additional protocol specific to Flash, which causes the link to invoke an ActionScript function.

Example

In this example, the MyFunc() function is defined in the first three lines of code. The TextField object myTextField is associated with an HTML text field. The text "Click Me!" is a hyperlink inside the text field. The MyFunc() function is called when the user clicks on the hyperlink:

function MyFunc(arg){
  trace ("You clicked me! Argument was "+arg);
}
myTextField.htmlText ="<A HREF=\"asfunction:MyFunc,Foo \">Click Me!</A>";

When the hyperlink is clicked, the following results are displayed in the Output panel:

You clicked me!  Parameter was Foo


Boolean class

Availability

Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly).

Description

The Boolean class is a wrapper object with the same functionality as the standard JavaScript Boolean object. Use the Boolean class to retrieve the primitive data type or string representation of a Boolean object.

You must use the constructor new Boolean() to create a Boolean object before calling its methods.

Method summary for the Boolean class

Method | Description
Boolean.toString() | Returns the string representation ("true" or "false") of the Boolean object.
Boolean.valueOf() | Returns the primitive value type of the specified Boolean object.

Constructor for the Boolean class

Availability

Flash Player 5.

Usage

new Boolean([x])

Parameters

x Any expression. This parameter is optional.

Returns

A reference to a Boolean object.

Description

Constructor; creates a Boolean object. If you omit the x parameter, the Boolean object is initialized with a value of false. If you specify a value for the x parameter, the method evaluates it and returns the result as a Boolean value according to the rules in the Boolean() function.

Example

The following code creates a new empty Boolean object called myBoolean.

myBoolean = new Boolean();


Boolean.toString()

Availability

Flash Player 5.

Usage

myBoolean.toString()

Parameters

None.

Returns

A Boolean value.

Description

Method; returns the string representation ("true" or "false") of the Boolean object.


Boolean.valueOf()

Availability

Flash Player 5.

Usage

myBoolean.valueOf()

Parameters

None.

Returns

A Boolean value.

Description

Method; returns true if the primitive value type of the specified Boolean object is true, false if it is false.

Example

var x:Boolean = new Boolean();
trace(x.valueOf());   // false
x = (6==3+3);
trace(x.valueOf());   // true


Boolean()

Availability

Flash Player 5; behavior changed in Flash Player 7.

Usage

Boolean(expression)

Parameters

expression An expression to convert to a Boolean value.

Returns

A Boolean value or the value expression, as described below.

Description

Function; converts the parameter expression to a Boolean value and returns a value as follows:

If expression is a Boolean value, the return value is expression.

If expression is a number, the return value is true if the number is not zero, otherwise the return value is false.

If expression is a string, the return value is as follows:

  • In files published for Flash Player 6 or earlier, the string is first converted to a number; the value is true if the number is nonzero, false otherwise.
  • In files published for Flash Player 7 or later, the result is true if the string has a length greater than zero; the value is false for an empty string.

If expression is undefined, the return value is false.

If expression is a movie clip or an object, the return value is true.

See also

Boolean class


break

Availability

Flash Player 4.

Usage

break

Parameters

None.

Returns

Nothing.

Description

Statement; appears within a loop (for, for..in, do while or while) or within a block of statements associated with a particular case within a switch action. The break action instructs Flash to skip the rest of the loop body, stop the looping action, and execute the statement following the loop statement. When using the break action, the Flash interpreter skips the rest of the statements in that case block and jumps to the first statement following the enclosing switch action. Use the break action to break out of a series of nested loops.

Example

The following example uses the break action to exit an otherwise infinite loop.

i = 0;
while (true) {
  if (i >= 100) {
    break;
  }
  i++;
}

See also

break, for, for..in, do while, while, switch, case


Button class

Availability

Flash Player 6.

Description

All button symbols in a SWF file are instances of the Button object. You can give a button an instance name in the Property inspector, and use the methods and properties of the Button class to manipulate buttons with ActionScript. Button instance names are displayed in the Movie Explorer and in the Insert Target Path dialog box in the Actions panel.

The Button class inherits from the Object class.

Method summary for the Button class

Method | Description
Button.getDepth() | Returns the depth of a button instance.

Property summary for the Button class

Property | Description
Button._alpha | The transparency value of a button instance.
Button.enabled | Indicates whether a button is active.
Button._focusrect | Indicates whether a button with focus has a yellow rectangle around it.
Button._height | The height of a button instance, in pixels.
Button._highquality | The level of anti-aliasing applied to the current SWF file.
Button.menu | Associates a ContextMenu object with the button object.
Button._name | The instance name of a button instance.
Button._parent | A reference to the movie clip or object that contains the current movie clip or object.
Button._quality | Indicates the rendering quality of the SWF file.
Button._rotation | The degree of rotation of a button instance.
Button._soundbuftime | Number of seconds for a sound to preload.
Button.tabEnabled | Indicates whether a button is included in automatic tab ordering.
Button.tabIndex | Indicates the tab order of an object.
Button._target | The target path of a button instance.
Button.trackAsMenu | Indicates whether other buttons can receive mouse release events.
Button._url | The URL of the SWF file that created the button instance.
Button.useHandCursor | Indicates whether the pointing hand is displayed when the mouse passes over a button.
Button._visible | A Boolean value that indicates whether a button instance is hidden or visible.
Button._width | The width of a button instance, in pixels.
Button._x | The x coordinate of a button instance.
Button._xmouse | The x coordinate of the mouse pointer relative to a button instance.
Button._xscale | The value specifying the percentage for horizontally scaling a button instance.
Button._y | The y coordinate of a button instance.
Button._ymouse | The y coordinate of the mouse pointer relative to a button instance.
Button._yscale | The value specifying the percentage for vertically scaling a button instance.

Event handler summary for the Button class

Event handler | Description
Button.onDragOut | Invoked when the mouse button is pressed over the button and the pointer then rolls outside the button.
Button.onDragOver | Invoked when the user presses and drags the mouse button outside and then over the button.
Button.onKeyUp | Invoked when a key is released.
Button.onKillFocus | Invoked when focus is removed from a button.
Button.onPress | Invoked when the mouse is pressed while the pointer is over a button.
Button.onRelease | Invoked when the mouse is released while the pointer is over a button.
Button.onReleaseOutside | Invoked when the mouse is released while the pointer is outside the button after the button is pressed while the pointer is inside the button.
Button.onRollOut | Invoked when the pointer rolls outside of a button area.
Button.onRollOver | Invoked when the mouse pointer rolls over a button.
Button.onSetFocus | Invoked when a button has input focus and a key is released.


Button._alpha

Availability

Flash Player 6.

Usage

my_btn._alpha

Description

Property; the alpha transparency value of the button specified by my_btn. Valid values are 0 (fully transparent) to 100 (fully opaque). The default value is 100. Objects in a button with _alpha set to 0 are active, even though they are invisible.

Example

The following code sets the _alpha property of a button named star_btn to 30% when the button is clicked:

on(release) {
  star_btn._alpha = 30;
}

See also

MovieClip._alpha, TextField._alpha


Button.enabled

Availability

Flash Player 6.

Usage

my_btn.enabled

Description

Property; a Boolean value that specifies whether a button is enabled. The default value is true.


Button._focusrect

Availability

Flash Player 6.

Usage

my_btn._focusrect

Description

Property; a Boolean value that specifies whether a button has a yellow rectangle around it when it has keyboard focus. This property can override the global _focusrect property.


Button.getDepth()

Availability

Flash Player 6.

Usage

my_btn.getDepth()

Returns

An integer.

Description

Method; returns the depth of a button instance.


Button._height

Availability

Flash Player 6.

Usage

my_btn._height

Description

Property; the height of the button, in pixels.

Example

The following code example sets the height and width of a button when the user clicks the mouse:

my_btn._width = 200;
my_btn._height = 200;


Button._highquality

Availability

Flash Player 6.

Usage

my_btn._highquality

Description

Property (global); specifies the level of anti-aliasing applied to the current SWF file. Specify 2 (best quality) to apply high quality with bitmap smoothing always on. Specify 1 (high quality) to apply anti-aliasing; this will smooth bitmaps if the SWF file does not contain animation. Specify 0 (low quality) to prevent anti-aliasing.

See also

_quality


Button.menu

Availability

Flash Player 7.

Usage

my_button.menu = contextMenu

Parameters

contextMenu A ContextMenu object.

Description

Property; associates the ContextMenu object contextMenu with the button object my_button. The ContextMenu class lets you modify the context menu that appears when the user right-clicks (Windows) or Control-clicks (Macintosh) in Flash Player.

Example

The following example assigns a ContextMenu object to a Button object named save_btn. The ContextMenu object contains a single menu item (labeled "Save...") with an associated callback handler function named doSave (not shown).

var menu_cm = new ContextMenu();
menu_cm.customItems.push(new ContextMenuItem("Save...", doSave));
function doSave(menu, obj) {
  // "Save" code here
}
save_btn.menu = menu_cm;

See also

ContextMenu class, ContextMenuItem class, MovieClip.menu, TextField.menu


Button._name

Availability

Flash Player 6.

Usage

my_btn._name

Description

Property; instance name of the button specified by my_btn.


Button.onDragOut

Availability

Flash Player 6.

Usage

my_btn.onDragOut = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the mouse button is pressed over the button and the pointer then rolls outside the button.

You must define a function that executes when the event handler is invoked.


Button.onDragOver

Availability

Flash Player 6.

Usage

my_btn.onDragOver = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the user presses and drags the mouse button outside and then over the button.

You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onKeyDown handler that sends a trace() action to the Output panel:

my_btn.onDragOver = function () {
  trace ("onDragOver called");
};

See also

Button.onKeyUp


Button.onKeyDown

Availability

Flash Player 6.

Usage

my_btn.onKeyDown = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when a button has keyboard focus and a key is pressed. The onKeyDown event handler is invoked with no parameters. You can use Key.getAscii() and Key.getCode() to determine which key was pressed.

You must define a function that executes when the event handler is invoked.

Example

In the following example, a function that sends a trace() action to the Output panel is defined for the onKeyDown handler.

my_btn.onKeyDown = function () {
  trace ("onKeyDown called");
};

See also

Button.onKeyUp


Button.onKeyUp

Availability

Flash Player 6.

Usage

my_btn.onKeyUp = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when a button has input focus and a key is released. The onKeyUp event handler is invoked with no parameters. You can use Key.getAscii() and Key.getCode() to determine which key was pressed.

You must define a function that executes when the event handler is invoked.

Example

In the following example, a function that sends a trace() action to the Output panel is defined for the onKeyPress handler.

my_btn.onKeyUp = function () {
  trace ("onKeyUp called");
};


Button.onKillFocus

Availability

Flash Player 6.

Usage

my_btn.onKillFocus = function (newFocus) {
  // your statements here
}

Parameters

newFocus The object that is receiving the focus.

Returns

Nothing.

Description

Event handler; invoked when a button loses keyboard focus. The onKillFocus method receives one parameter, newFocus, which is an object representing the new object receiving the focus. If no object receives the focus, newFocus contains the value null.


Button.onPress

Availability

Flash Player 6.

Usage

my_btn.onPress = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when a button is pressed. You must define a function that executes when the event handler is invoked.

Example

In the following example, a function that sends a trace() action to the Output panel is defined for the onPress handler.

my_btn.onPress = function () {
  trace ("onPress called");
};


Button.onRelease

Availability

Flash Player 6.

Usage

my_btn.onRelease = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when a button is released. You must define a function that executes when the event handler is invoked.

Example

In the following example, a function that sends a trace() action to the Output panel is defined for the onRelease handler.

my_btn.onRelease = function () {
  trace ("onRelease called");
};


Button.onReleaseOutside

Availability

Flash Player 6.

Usage

my_btn.onReleaseOutside = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the mouse is released while the pointer is outside the button after the button is pressed while the pointer is inside the button.

You must define a function that executes when the event handler is invoked.

Example

In the following example, a function that sends a trace() action to the Output panel is defined for the onReleaseOutside handler.

my_btn.onReleaseOutside = function () {
  trace ("onReleaseOutside called");
};


Button.onRollOver

Availability

Flash Player 6.

Usage

my_btn.onRollOver = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the pointer moves over a button area. You must define a function that executes when the event handler is invoked.

Example

In the following example, a function that sends a trace() action to the Output panel is defined for the onRollOver handler.

my_btn.onRollOver = function () {
  trace ("onRollOver called");
};


Button.onSetFocus

Availability

Flash Player 6.

Usage

my_btn.onSetFocus = function(oldFocus){
  // your statements here
}

Parameters

oldFocus The object to lose keyboard focus.

Returns

Nothing.

Description

Event handler; invoked when a button receives keyboard focus. The oldFocus parameter is the object that loses the focus. For example, if the user presses the Tab key to move the input focus from a text field to a button, oldFocus contains the text field instance.

If there is no previously focused object, oldFocus contains a null value.


Button._parent

Availability

Flash Player 6.

Usage

my_btn._parent.property
_parent.property

Description

Property; a reference to the movie clip or object that contains the current movie clip or object. The current object is the one containing the ActionScript code that references _parent.

Use _parent to specify a relative path to movie clips or objects that are above the current movie clip or object. You can use _parent to climb up multiple levels in the display list as in the following:

_parent._parent._alpha = 20;

See also

MovieClip._parent, _root, targetPath


Button._quality

Availability

Flash Player 6.

Usage

my_btn._quality

Description

Property (global); sets or retrieves the rendering quality used for a SWF file. Device fonts are always aliased and therefore are unaffected by the _quality property.

Note: Although you can specify this property for a Button object, it is actually a global property, and you can specify its value simply as _quality. For more information, see _quality.


Button._rotation

Availability

Flash Player 6.

Usage

my_btn._rotation

Description

Property; the rotation of the button, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement my_btn._rotation = 450 is the same as my_btn._rotation = 90.

See also

MovieClip._rotation, TextField._rotation


Button._soundbuftime

Availability

Flash Player 6.

Usage

myButton._soundbuftime

Description

Property (global); an integer that specifies the number of seconds a sound prebuffers before it starts to stream.

Note: Although you can specify this property for a Button object, it is actually a global property, and you can specify its value simply as _soundbuftime. For more information, see _soundbuftime.


Button.tabEnabled

Availability

Flash Player 6.

Usage

my_btn.tabEnabled

Description

Property; specifies whether my_btn is included in automatic tab ordering. It is undefined by default.

If the tabEnabled property is undefined or true, the object is included in automatic tab ordering. If the tabIndex property is also set to a value, the object is included in custom tab ordering as well. If tabEnabled is false, the object is not included in automatic or custom tab ordering, even if the tabIndex property is set.

See also

Button.tabIndex, MovieClip.tabEnabled, TextField.tabEnabled


Button.tabIndex

Availability

Flash Player 6.

Usage

my_btn.tabIndex

Description

Property; lets you customize the tab ordering of objects in a SWF file. You can set the tabIndex property on a button, movie clip, or text field instance; it is undefined by default.

If any currently displayed object in the SWF file contains a tabIndex property, automatic tab ordering is disabled, and the tab ordering is calculated from the tabIndex properties of objects in the SWF file. The custom tab ordering only includes objects that have tabIndex properties.

The tabIndex property may be an non-negative integer. The objects are ordered according to their tabIndex properties, in ascending order. An object with a tabIndex value of 1 precedes an object with a tabIndex value of 2. If two objects have the same tabIndex value, the one that precedes the other in the tab ordering is undefined.

The custom tab ordering defined by the tabIndex property is flat. This means that no attention is paid to the hierarchical relationships of objects in the SWF file. All objects in the SWF file with tabIndex properties are placed in the tab order, and the tab order is determined by the order of the tabIndex values. If two objects have the same tabIndex value, the one that goes first is undefined. You shouldn't use the same tabIndex value for multiple objects.

See also

Button.tabEnabled, MovieClip.tabChildren, MovieClip.tabEnabled, MovieClip.tabIndex, TextField.tabIndex


Button._target

Availability

Flash Player 6.

Usage

myButton._target

Description

Property (read-only); returns the target path of the button instance specified by my_btn.

See also

targetPath


Button.trackAsMenu

Availability

Flash Player 6.

Usage

my_btn.trackAsMenu

Description

Property; a Boolean value that indicates whether other buttons or movie clips can receive mouse release events. This allows you to create menus. You can set the trackAsMenu property on any button or movie clip object. If the trackAsMenu property has not been defined, the default behavior is false.

You can change the trackAsMenu property at any time; the modified button immediately takes on the new behavior.

See also

MovieClip.trackAsMenu


Button._url

Availability

Flash Player 6.

Usage

my_btn._url

Description

Property (read only); retrieves the URL of the SWF file that created the button.


Button.useHandCursor

Availability

Flash Player 6.

Usage

my_btn.useHandCursor

Description

Property; a Boolean value that, when set to true (the default), indicates whether a hand cursor (pointing hand) is displayed when the mouse rolls over a button. If this property is set to false, the arrow cursor is used instead.

You can change the useHandCursor property at any time; the modified button immediately takes on the new cursor behavior. The useHandCursor property can be read out of a prototype object.


Button._visible

Availability

Flash Player 6.

Usage

my_btn._visible

Description

Property; a Boolean value that indicates whether the button specified by my_btn is visible. Buttons that are not visible (_visible property set to false) are disabled.

See also

MovieClip._visible, TextField._visible


Button._width

Availability

Flash Player 6.

Usage

my_btn._width

Description

Property; the width of the button, in pixels.

Example

The following example sets the height and width properties of a button.

my_btn._width=200;
my_btn._height=200;

See also

MovieClip._width


Button._x

Availability

Flash Player 6.

Usage

my_btn._x

Description

Property; an integer that sets the x coordinate of a button relative to the local coordinates of the parent movie clip. If a button is on the main Timeline, then its coordinate system refers to the upper left corner of the Stage as (0, 0). If the button is inside a movie clip that has transformations, the button is in the local coordinate system of the enclosing movie clip. Thus, for a movie clip rotated 90 degrees counterclockwise, the enclosed button inherits a coordinate system that is rotated 90 degrees counterclockwise. The button's coordinates refer to the registration point position.

See also

Button._xscale, Button._y, Button._yscale


Button._xmouse

Availability

Flash Player 6.

Usage

my_btn._xmouse

Description

Property (read-only); returns the x coordinate of the mouse position relative to the button.

See also

Button._ymouse


Button._xscale

Availability

Flash Player 6.

Usage

my_btn._xscale

Description

Property; the horizontal scale of the button as applied from the registration point of the button, expressed as a percentage. The default registration point is (0,0).

Scaling the local coordinate system affects the _x and _y property settings, which are defined in pixels. For example, if the parent movie clip is scaled to 50%, setting the _x property moves an object in the button by half the number of pixels as it would if the SWF file were at 100%.

See also

Button._x, Button._y, Button._yscale


Button._y

Availability

Flash Player 6.

Usage

my_btn._y

Description

Property; the y coordinate of the button relative to the local coordinates of the parent movie clip. If a button is in the main Timeline, its coordinate system refers to the upper left corner of the Stage as (0, 0). If the button is inside another movie clip that has transformations, the button is in the local coordinate system of the enclosing movie clip. Thus, for a movie clip rotated 90 degrees counterclockwise, the enclosed button inherits a coordinate system that is rotated 90 degrees counterclockwise. The button's coordinates refer to the registration point position.

See also

Button._x, Button._xscale, Button._yscale


Button._ymouse

Availability

Flash Player 6.

Usage

my_btn._ymouse

Description

Property (read-only); indicates the y coordinate of the mouse position relative to the button.

See also

Button._xmouse


Button._yscale

Availability

Flash Player 6.

Usage

my_btn._yscale

Description

Property; the vertical scale of the button as applied from the registration point of the button, expressed as a percentage. The default registration point is (0,0).

See also

Button._y, Button._x, Button._xscale


call()

Availability

Flash Player 4. This action was deprecated in Flash 5, and Macromedia recommends that you use the function action instead.

Usage

call(frame)

Parameters

frame The label or number of a frame in the Timeline.

Returns

Nothing.

Description

Deprecated action; executes the script in the called frame without moving the playhead to that frame. Local variables do not exist after the script executes.

See also

function, Function.call()


Camera class

Availability

Flash Player 6.

Description

The Camera class is primarily for use with Macromedia Flash Communication Server, but can be used in a limited fashion without the server.

The Camera class lets you capture video from a video camera attached to the computer that is running the Macromedia Flash Player—for example, to monitor a video feed from a web camera attached to your local system. (Flash provides similar audio capabilities; for more information, see the Microphone class entry.)

To create or reference a Camera object, use Camera.get().

Method summary for the Camera class

Method | Description
Camera.get() | Returns a default or specified Camera object, or null if the camera is not available.
Camera.setMode() | Sets aspects of the camera capture mode, including height, width, and frames per second.
Camera.setMotionLevel() | Specifies how much motion is required to invoke Camera.onActivity(true) and how much time should elapse without motion before Camera.onActivity(false) is invoked.
Camera.setQuality() | An integer that specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second.

Property summary for the Camera class

Property (read-only) | Description
Camera.activityLevel | The amount of motion the camera is detecting.
Camera.bandwidth | The maximum amount of bandwidth the current outgoing video feed can use, in bytes.
Camera.currentFps | The rate at which the camera is capturing data, in frames per second.
Camera.fps | The rate at which you would like the camera to capture data, in frames per second.
Camera.height | The current capture height, in pixels.
Camera.index | The index of the camera, as reflected in the array returned by Camera.names.
Camera.motionLevel | The amount of motion required to invoke Camera.onActivity(true).
Camera.motionTimeOut | The number of milliseconds between the time when the camera stops detecting motion and the time Camera.onActivity(false) is invoked.
Camera.muted | A Boolean value that specifies whether the user has allowed or denied access to the camera.
Camera.name | The name of the camera as specified by the camera hardware.
Camera.names | Class property; an array of strings reflecting the names of all available video capture devices, including video cards and cameras.
Camera.quality | An integer specifying the required level of picture quality, as determined by the amount of compression being applied to each video frame.
Camera.width | The current capture width, in pixels.

Event handler summary for the Camera class

Event handler | Description
Camera.onActivity | Invoked when the camera starts or stops detecting motion.
Camera.onStatus | Invoked when the user allows or denies access to the camera.

Constructor for the Camera class

See Camera.get().


Camera.activityLevel

Availability

Flash Player 6.

Usage

active_cam.activityLevel

Description

Read-only property; a numeric value that specifies the amount of motion the camera is detecting. Values range from 0 (no motion is being detected) to 100 (a large amount of motion is being detected). The value of this property can help you determine if you need to pass a setting to Camera.setMotionLevel().

If the camera is available but is not yet being used because Video.attachVideo() has not been called, this property is set to -1.

If you are streaming only uncompressed local video, this property is set only if you have assigned a function to the Camera.onActivity event handler. Otherwise, it is undefined.

See also

Camera.motionLevel, Camera.setMotionLevel()


Camera.bandwidth

Availability

Flash Player 6.

Usage

active_cam.bandwidth

Description

Read-only property; an integer that specifies the maximum amount of bandwidth the current outgoing video feed can use, in bytes. A value of 0 means that Flash video can use as much bandwidth as needed to maintain the desired frame quality.

To set this property, use Camera.setQuality().

Example

The following example loads another SWF file if the camera's bandwidth is 32 kilobytes or greater.

if(active_cam.bandwidth >= 32768){
  loadMovie("splat.swf",_root.hiddenvar);
}

See also

Camera.setQuality()


Camera.currentFps

Availability

Flash Player 6.

Usage

active_cam.currentFps

Description

Read-only property; the rate at which the camera is capturing data, in frames per second. This property cannot be set; however, you can use the Camera.setMode() method to set a related property—Camera.fps—which specifies the maximum frame rate at which you would like the camera to capture data.

See also

Camera.fps, Camera.setMode()


Camera.fps

Availability

Flash Player 6.

Usage

active_cam.fps

Description

Read-only property; the maximum rate at which you want the camera to capture data, in frames per second. The maximum rate possible depends on the capabilities of the camera; that is, if the camera doesn't support the value you set here, this frame rate will not be achieved.

  • To set a desired value for this property, use Camera.setMode().
  • To determine the rate at which the camera is currently capturing data, use the Camera.currentFps property.

Example

The following example uses Camera.setMode() to set active_cam.fps to the value provided by the user's text box, this.config.txt_fps.

if (this.config.txt_fps != undefined) {
     active_cam.setMode(active_cam.width, active_cam.height, this.config.txt_fps, false);
}

Note: The setMode function does not guarantee the requested fps setting; it sets the fps you requested or the fastest fps available.

See also

Camera.currentFps, Camera.setMode()


Camera.get()

Availability

Flash Player 6.

Usage

Camera.get([index])

Note: The correct syntax is Camera.get(). To assign the Camera object to a variable, use syntax like active_cam = Camera.get().

Parameters

index An optional zero-based integer that specifies which camera to get, as determined from the array returned by the Camera.names property. To get the default camera (which is recommended for most applications), omit this parameter.

Returns

  • If index is not specified, this method returns a reference to the default camera or, if it is in use by another application, to the first available camera. (If there is more than one camera installed, the user may specify the default camera in the Flash Player Camera Settings panel.) If no cameras are available or installed, the method returns null.
  • If index is specified, this method returns a reference to the requested camera, or null if it is not available.

Description

Method; returns a reference to a Camera object for capturing video. To actually begin capturing the video, you must attach the Camera object to a Video object (see Video.attachVideo()).

Unlike objects that you create using the new constructor, multiple calls to Camera.get() reference the same camera. Thus, if your script contains the lines first_cam = Camera.get() and second_cam = Camera.get(), both first_cam and second_cam reference the same (default) camera.

In general, you shouldn't pass a value for index; simply use Camera.get() to return a reference to the default camera. By means of the Camera settings panel (discussed later in this section), the user can specify the default camera Flash should use. If you pass a value for index, you might be trying to reference a camera other than the one the user prefers. You might use index in rare cases—for example, if your application is capturing video from two cameras at the same time.

When a SWF file tries to access the camera returned by Camera.get(), Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access to the camera. (Make sure your Stage size is at least 215 x 138 pixels; this is the minimum size Flash requires to display the dialog box.)

When the user responds to this dialog box, the Camera.onStatus event handler returns an information object that indicates the user's response. To determine whether the user has denied or allowed access to the camera without processing this event handler, use the Camera.muted property.

The user can also specify permanent privacy settings for a particular domain by right-clicking (Windows) or Control-clicking (Macintosh) while a SWF file is playing, choosing Settings, opening the Privacy panel, and selecting Remember.

You can't use ActionScript to set the Allow or Deny value for a user, but you can display the Privacy panel for the user by using System.showSettings(0). If the user selects Remember, Flash Player no longer displays the Privacy dialog box for SWF files from this domain.

If Camera.get returns null, either the camera is in use by another application, or there are no cameras installed on the system. To determine whether any cameras are installed, use Camera.names.length. To display the Flash Player Camera Settings panel, which lets the user choose the camera to be referenced by Camera.get(), use System.showSettings(3).

Scanning the hardware for cameras takes time. When Flash finds at least one camera, the hardware is not scanned again for the lifetime of the player instance. However, if Flash doesn't find any cameras, it will scan each time Camera.get is called. This is helpful if a user has forgotten to connect the camera; if your SWF file provides a Try Again button that calls Camera.get, Flash can find the camera without the user having to restart the SWF file.

Example

The following example captures and displays video locally within a Video object named my_video on the Stage.

var active_cam = Camera.get();
my_video.attachVideo(active_cam);

See also

Camera.index, Camera.muted, Camera.names, Camera.onStatus, Camera.setMode(), System.showSettings(), Video.attachVideo()


Camera.height

Availability

Flash Player 6.

Usage

active_cam.height

Description

Read-only property; the current capture height, in pixels. To set a value for this property, use Camera.setMode().

Example

The following line of code updates a text box in the user interface with the current height value.

my_txt._height = active_cam.height;

See also the example for Camera.setMode().

See also

Camera.setMode(), Camera.width


Camera.index

Availability

Flash Player 6.

Usage

active_cam.index

Description

Read-only property; a zero-based integer that specifies the index of the camera, as reflected in the array returned by Camera.names.

See also

Camera.get(), Camera.names


Camera.motionLevel

Availability

Flash Player 6.

Usage

active_cam.motionLevel

Description

Read-only property; a numeric value that specifies the amount of motion required to invoke Camera.onActivity(true). Acceptable values range from 0 to 100. The default value is 50.

Video can be displayed regardless of the value of the motionLevel property. For more information, see Camera.setMotionLevel().

See also

Camera.activityLevel, Camera.onActivity, Camera.onStatus, Camera.setMotionLevel()


Camera.motionTimeOut

Availability

Flash Player 6.

Usage

active_cam.motionTimeOut

Description

Read-only property; the number of milliseconds between the time the camera stops detecting motion and the time Camera.onActivity (false) is invoked. The default value is 2000 (2 seconds).

To set this value, use Camera.setMotionLevel().

Example

The following example sets the number of milliseconds between the time the camera stops detecting motion and the time Camera.onActivity (false) is invoked to 1000 milliseconds, or one second.

if(active_cam.motionTimeOut >= 1000){
  active_cam.setMotionLevel(active_cam.motionLevel, 1000);
}

See also

Camera.onActivity, Camera.setMotionLevel()


Camera.muted

Availability

Flash Player 6.

Usage

active_cam.muted

Description

Read-only property; a Boolean value that specifies whether the user has denied access to the camera (true) or allowed access (false) in the Flash Player Privacy Settings panel. When this value changes, Camera.onStatus is invoked. For more information, see Camera.get().

See also

Camera.get(), Camera.onStatus


Camera.name

Availability

Flash Player 6.

Usage

active_cam.name

Description

Read-only property; a string that specifies the name of the current camera, as returned by the camera hardware.

Example

The following example displays the name of the default camera in the Output panel. In Windows, this name is the same as the device name listed in the Scanners and Cameras properties sheet.

active_cam = Camera.get();
trace("The camera name is: " + active_cam.name);

See also

Camera.get(), Camera.names


Camera.names

Availability

Flash Player 6.

Usage

Camera.names

Note: The correct syntax is Camera.names. To assign the return value to a variable, use syntax like cam_array = Camera.names. To determine the name of the current camera, use active_cam.name.

Description

Read-only class property; retrieves an array of strings reflecting the names of all available cameras without displaying the Flash Player Privacy Settings panel. This array behaves the same as any other ActionScript array, implicitly providing the zero-based index of each camera and the number of cameras on the system (by means of Camera.names.length). For more information, see the Array class entry.

Calling the Camera.names property requires an extensive examination of the hardware, and it may take several seconds to build the array. In most cases, you can just use the default camera.

Example

The following example uses the default camera unless more than one camera is available, in which case the user can choose which camera to set as the default camera.

cam_array = Camera.names;
if (cam_array.length == 1){
  active_cam = Camera.get();
}
else {
  System.showSettings(3);
  active_cam = Camera.get();
}

See also

Camera.get(), Camera.index, Camera.name


Camera.onActivity

Availability

Flash Player 6.

Usage

active_cam.onActivity = function(activity) {
  // your statements here
}

Parameters

activity A Boolean value set to true when the camera starts detecting motion, false when it stops.

Returns

Nothing.

Description

Event handler; invoked when the camera starts or stops detecting motion. If you want to respond to this event handler, you must create a function to process its activity value.

To specify the amount of motion required to invoke Camera.onActivity(true) and the amount of time that must elapse without activity before invoking Camera.onActivity(false), use Camera.setMotionLevel().

Example

The following example displays true or false in the Output panel when the camera starts or stops detecting motion.

// Assumes a Video object named "myVideoObject" is on the Stage
active_cam = Camera.get();
myVideoObject.attachVideo(active_cam);
active_cam.setMotionLevel(10, 500);
active_cam.onActivity = function(mode)
{
  trace(mode);
}

See also

Camera.onActivity, Camera.setMotionLevel()


Camera.onStatus

Availability

Flash Player 6.

Usage

active_cam.onStatus = function(infoObject) {
  // your statements here
}

Parameters

infoObject A parameter defined according to the status message.

Returns

Nothing.

Description

Event handler; invoked when the user allows or denies access to the camera. If you want to respond to this event handler, you must create a function to process the information object generated by the camera.

When a SWF file tries to access the camera, Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access.

  • If the user allows access, the Camera.muted property is set to false, and this handler is invoked with an information object whose code property is "Camera.Unmuted" and whose level property is "Status".
  • If the user denies access, the Camera.muted property is set to true, and this handler is invoked with an information object whose code property is "Camera.Muted" and whose level property is "Status".

To determine whether the user has denied or allowed access to the camera without processing this event handler, use the Camera.muted property.

Note: If the user chooses to permanently allow or deny access for all SWF files from a specified domain, this handler is not invoked for SWF files from that domain unless the user later changes the privacy setting. For more information, see Camera.get().

Example

The following event handler displays a message whenever the user allows or denies access to the camera.

active_cam = Camera.get();
myVideoObject.attachVideo(active_cam);
active_cam.onStatus = function(infoMsg) {
  if(infoMsg.code == "Camera.Muted"){
    trace("User denies access to the camera");
  }
  else
    trace("User allows access to the camera");
}
// Change the Allow or Deny value to invoke the function
System.showSettings(0);

See also

Camera.get(), Camera.muted


Camera.quality

Availability

Flash Player 6.

Usage

active_cam.quality

Description

Read-only property; an integer specifying the required level of picture quality, as determined by the amount of compression being applied to each video frame. Acceptable quality values range from 1 (lowest quality, maximum compression) to 100 (highest quality, no compression). The default value is 0, which means that picture quality can vary as needed to avoid exceeding available bandwidth.

See also

Camera.setQuality()


Camera.setMode()

Availability

Flash Player 6.

Usage

active_cam.setMode(width, height, fps [,favorSize])

Parameters

width The requested capture width, in pixels. The default value is 160.

height The requested capture height, in pixels. The default value is 120.

fps The requested rate at which the camera should capture data, in frames per second. The default value is 15.

favorSize Optional: a Boolean value that specifies how to manipulate the width, height, and frame rate if the camera does not have a native mode that meets the specified requirements. The default value is true, which means that maintaining capture size is favored; using this parameter selects the mode that most closely matches width and height values, even if doing so adversely affects performance by reducing the frame rate. To maximize frame rate at the expense of camera height and width, pass false for the favorSize parameter.

Returns

Nothing.

Description

Method; sets the camera capture mode to the native mode that best meets the specified requirements. If the camera does not have a native mode that matches all the parameters you pass, Flash selects a capture mode that most closely synthesizes the requested mode. This manipulation may involve cropping the image and dropping frames.

By default, Flash drops frames as needed to maintain image size. To minimize the number of dropped frames, even if this means reducing the size of the image, pass false for the favorSize parameter.

When choosing a native mode, Flash tries to maintain the requested aspect ratio whenever possible. For example, if you issue the command active_cam.setMode(400, 400, 30), and the maximum width and height values available on the camera are 320 and 288, Flash sets both the width and height at 288; by setting these properties to the same value, Flash maintains the 1:1 aspect ratio you requested.

To determine the values assigned to these properties after Flash selects the mode that most closely matches your requested values, use Camera.width, Camera.height, and Camera.fps.

Example

The following example sets the width, height, and fps based on the user's input if the user clicks the button. The optional parameter, favorSize is not included, because the default value, true, will provide the settings closest to the user's preference without sacrificing the picture quality, although the fps may then be sacrificed. The user interface is then updated with the new settings.

on (press)
{
  // Sets width, height, and fps to user's input.
  _root.active_cam.setMode(txt_width, my_txt._height, txt_fps);

  // Update the user's text fields with the new settings.
  _root.txt_width = active_cam.width;
  _root.txt_height = active_cam.height;
  _root.txt_fps = active_cam.fps;
}

See also

Camera.currentFps, Camera.fps, Camera.height, Camera.width


Camera.setMotionLevel()

Availability

Flash Player 6.

Usage

active_cam.setMotionLevel(sensitivity [, timeout])

Parameters

sensitivity A numeric value that specifies the amount of motion required to invoke Camera.onActivity(true). Acceptable values range from 0 to 100. The default value is 50.

timeout An optional numeric parameter that specifies how many milliseconds must elapse without activity before Flash considers activity to have stopped and invokes the Camera.onActivity(false) event handler. The default value is 2000 (2 seconds).

Returns

Nothing.

Description

Method; specifies how much motion is required to invoke Camera.onActivity(true). Optionally sets the number of milliseconds that must elapse without activity before Flash considers motion to have stopped and invokes Camera.onActivity(false).

Note: Video can be displayed regardless of the value of the sensitivity parameter. This parameter only determines when and under what circumstances Camera.onActivity is invoked, not whether video is actually being captured or displayed.

  • To prevent the camera from detecting motion at all, pass a value of 100 for sensitivity; Camera.onActivity is never invoked. (You would probably use this value only for testing purposes—for example, to temporarily disable any actions set to occur when Camera.onActivity is invoked.)
  • To determine the amount of motion the camera is currently detecting, use the Camera.activityLevel property.

Motion sensitivity values correspond directly to activity values. Complete lack of motion is an activity value of 0. Constant motion is an activity value of 100. Your activity value is less than your motion sensitivity value when you're not moving; when you are moving, activity values frequently exceed your motion sensitivity value.

This method is similar in purpose to Microphone.setSilenceLevel(); both methods are used to specify when the onActivity event handler should be invoked. However, these methods have a significantly different impact on publishing streams:

  • Microphone.setSilenceLevel() is designed to optimize bandwidth. When an audio stream is considered silent, no audio data is sent. Instead, a single message is sent, indicating that silence has started.
  • Camera.setMotionLevel() is designed to detect motion and does not affect bandwidth usage. Even if a video stream does not detect motion, video is still sent.

Example

The following example sends messages to the Output panel when video activity starts or stops. Change the motion sensitivity value of 30 to a higher or lower number to see how different values affect motion detection.

// Assumes a Video object named "myVideoObject" is on the Stage
active_cam = Camera.get();
x = 0;
function motion(mode) {
  trace(x + ": " + mode);
  x++;
}
active_cam.onActivity = function(mode) {
  motion(mode);
}
active_cam.setMotionLevel(30, 500);
myVideoObject.attachVideo(active_cam);

See also

Camera.activityLevel, Camera.motionLevel, Camera.motionTimeOut, Camera.onActivity


Camera.setQuality()

Availability

Flash Player 6.

Usage

active_cam.setQuality(bandwidth, frameQuality)

Parameters

bandwidth An integer that specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash video can use as much bandwidth as needed to maintain the value of frameQuality, pass 0 for bandwidth. The default value is 16384.

frameQuality An integer that specifies the required level of picture quality, as determined by the amount of compression being applied to each video frame. Acceptable values range from 1 (lowest quality, maximum compression) to 100 (highest quality, no compression). To specify that picture quality can vary as needed to avoid exceeding bandwidth, pass 0 for frameQuality. The default value is 0.

Returns

Nothing.

Description

Method; sets the maximum amount of bandwidth per second or the required picture quality of the current outgoing video feed. This method is generally applicable only if you are transmitting video using Flash Communication Server.

Use this method to specify which element of the outgoing video feed is more important to your application—bandwidth use or picture quality.

  • To indicate that bandwidth use takes precedence, pass a value for bandwidth and 0 for frameQuality. Flash will transmit video at the highest quality possible within the specified bandwidth. If necessary, Flash will reduce picture quality to avoid exceeding the specified bandwidth. In general, as motion increases, quality decreases.
  • To indicate that quality takes precedence, pass 0 for bandwidth and a numeric value for frameQuality. Flash will use as much bandwidth as required to maintain the specified quality. If necessary, Flash will reduce the frame rate to maintain picture quality. In general, as motion increases, bandwidth use also increases.
  • To specify that both bandwidth and quality are equally important, pass numeric values for both parameters. Flash will transmit video that achieves the specified quality and that doesn't exceed the specified bandwidth. If necessary, Flash will reduce the frame rate to maintain picture quality without exceeding the specified bandwidth.

Example

The following examples illustrate how to use this method to control bandwidth use and picture quality.

// Ensure that no more than 8192 (8K/second) is used to send video
active_cam.setQuality(8192,0);

// Ensure that no more than 8192 (8K/second) is used to send video
// with a minimum quality of 50
active_cam.setQuality(8192,50);

// Ensure a minimum quality of 50, no matter how much bandwidth it takes
active_cam.setQuality(0,50);

See also

Camera.bandwidth, Camera.get(), Camera.quality


Camera.width

Availability

Flash Player 6.

Usage

active_cam.width

Description

Read-only property; the current capture width, in pixels. To set a desired value for this property, use Camera.setMode().

Example

The following line of code updates a text box in the user interface with the current width value.

my_txt.text=active_cam.width;

See also the example for Camera.setMode().

See also

Camera.height, Camera.setMode()


case

Availability

Flash Player 4.

Usage

case expression: statements

Parameters

expression Any expression.

statements Any statements.

Returns

Nothing.

Description

Statement; defines a condition for the switch action. The statements in the statements parameter execute if the expression parameter that follows the case keyword equals the expression parameter of the switch action using strict equality (===)

If you use the case action outside of a switch statement, it produces an error and the script doesn't compile.

See also

break, default, === (strict equality), switch


chr

Availability

Flash Player 4. This function was deprecated in Flash 5 in favor of String.fromCharCode().

Usage

chr(number)

Parameters

number An ASCII code number.

Returns

Nothing.

Description

String function; converts ASCII code numbers to characters.

Example

The following example converts the number 65 to the letter A and assigns it to the variable myVar.

myVar = chr(65);

See also

String.fromCharCode()


class

Availability

Flash Player 6.

Usage

[dynamic] class className  [ extends superClass ]
              [ implements interfaceName [, interfaceName... ] ]
{
  // class definition here
}

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Parameters

className The fully qualified name of the class.

superClass Optional; the name of the class that className extends (inherits from).

interfaceName Optional; the name of the interface whose methods className must implement.

Description

Statement; defines a custom class, which lets you instantiate objects that share methods and properties that you define. For example, if you are developing an invoice-tracking system, you could create an invoice class that defines all the methods and properties that each invoice should have. You would then use the new invoice() command to create invoice objects.

The name of the class must be the same as the name of the external file that contains the class. For example, if you name a class Student, the file that defines the class must be named Student.as.

The class name must be fully qualified within the file in which it is declared; that is, it must reflect the directory in which it is stored. For example, to create a class named RequiredClass that is stored in the myClasses/education/curriculum directory, you must declare the class in the RequiredClass.as file like this:

class myClasses.education.curriculum.RequiredClass {
}

For this reason, it's good practice to plan your directory structure before you begin creating classes. Otherwise, if you decide to move class files after you create them, you will have to modify the class declaration statements to reflect their new location.

You cannot nest class definitions; that is, you cannot define additional classes within a class definition.

To indicate that objects can add and access dynamic properties at runtime, precede the class statement with the dynamic keyword. To create classes based on interfaces, use the implements keyword. To create subclasses of a class, use the extends keyword. (A class can extend only one class, but can implement several interfaces.) You can use implements and extends in a single statement.

class C implements Interface_i, Interface_j    // OK
class C extends Class_d implements Interface_i, Interface_j    // OK
class C extends Class_d, Class_e    // not OK

For more information, see Creating and using classes.

Example

The following example creates a class called Plant. Its constructor takes two parameters.

// Filename Plant.as
class Plant {
  // Define property names and types
  var leafType:String;
  var bloomSeason:String;
  // Following line is constructor
  // because it has the same name as the class
  function Plant (param_leafType:String, param_bloomSeason:String) {
      // Assign passed values to properties when new Plant object is created
    leafType = param_leafType;
    bloomSeason = param_bloomSeason;
  }
  // Create methods to return property values, because best practice
  // recommends against directly referencing a property of a class
  function getLeafType():String {return leafType};
  function getBloomSeason():String {return bloomSeason};
}

In an external script file or in the Actions panel, use the new operator to create a Plant object.

var pineTree:Plant = new Plant("Evergreen","N/A");
// Confirm parameters were passed correctly
trace(pineTree.getLeafType());
trace(pineTree.getBloomSeason());

See also

dynamic, extends, implements, import, interface, new, Object.registerClass()


clearInterval()

Availability

Flash Player 6.

Usage

clearInterval( intervalID )

Parameters

intervalID An object returned from a call to setInterval().

Returns

Nothing.

Description

Function; clears a call to setInterval().

Example

The following example first sets and then clears an interval call:

function callback() {
        trace("interval called");
}
var intervalID;
intervalID = setInterval( callback, 1000 );

// sometime later
clearInterval( intervalID );

See also

setInterval()


Color class

Availability

Flash Player 5.

Description

The Color class lets you set the RGB color value and color transform of movie clips and retrieve those values once they have been set.

You must use the constructor new Color() to create a Color object before calling its methods.

Method summary for the Color class

Method | Description
Color.getRGB() | Returns the numeric RGB value set by the last setRGB() call.
Color.getTransform() | Returns the transform information set by the last setTransform() call.
Color.setRGB() | Sets the hexadecimal representation of the RGB value for a Color object.
Color.setTransform() | Sets the color transform for a Color object.

Constructor for the Color class

Availability

Flash Player 5.

Usage

new Color(target)

Parameters

target The instance name of a movie clip.

Returns

A reference to a Color object.

Description

Constructor; creates a Color object for the movie clip specified by the target parameter. You can then use the methods of that Color object to change the color of the entire target movie clip.

Example

The following example creates a Color object called my_color for the movie clip my_mc and sets its RGB value:

my_color = new Color(my_mc);
my_color.setRGB(0xff9933);


Color.getRGB()

Availability

Flash Player 5.

Usage

my_color.getRGB()

Parameters

None.

Returns

A number that represents the RGB numeric value for the color specified.

Description

Method; returns the numeric values set by the last setRGB() call.

Example

The following code retrieves the RGB value for the Color object my_color, converts it to a hexadecimal string, and assigns it to the value variable.

value = my_color.getRGB().toString(16);

See also

Color.setRGB()


Color.getTransform()

Availability

Flash Player 5.

Usage

my_color.getTransform()

Parameters

None.

Returns

An object whose properties contain the current offset and percentage values for the specified color.

Description

Method; returns the transform value set by the last Color.setTransform() call.

See also

Color.setTransform()


Color.setRGB()

Availability

Flash Player 5.

Usage

my_color.setRGB(0xRRGGBB)

Parameters

0xRRGGBB The hexadecimal or RGB color to be set. RR, GG, and BB each consist of two hexadecimal digits specifying the offset of each color component. The 0x tells the ActionScript compiler that the number is a hexadecimal value.

Description

Method; specifies an RGB color for a Color object. Calling this method overrides any previous Color.setTransform() settings.

Returns

Nothing.

Example

This example sets the RGB color value for the movie clip my_mc. To see this code work, place a movie clip on the Stage with the instance name my_mc. Then place the following code on Frame 1 in the main Timeline and choose Control > Test Movie.

my_color = new Color(my_mc);
my_color.setRGB(0x993366);

See also

Color.setTransform()


Color.setTransform()

Availability

Flash Player 5.

Usage

my_color.setTransform(colorTransformObject)

Parameters

colorTransformObject An object created with the new Object constructor. This instance of the Object class must have the following properties that specify color transform values: ra, rb, ga, gb, ba, bb, aa, ab. These properties are explained below.

Returns

Nothing.

Description

Method; sets color transform information for a Color object. The colorTransformObject parameter is a generic object that you create from the new Object constructor. It has parameters specifying the percentage and offset values for the red, green, blue, and alpha (transparency) components of a color, entered in the format 0xRRGGBBAA.

The parameters for a color transform object correspond to the settings in the Advanced Effect dialog box and are defined as follows:

  • ra is the percentage for the red component (-100 to 100).
  • rb is the offset for the red component (-255 to 255).
  • ga is the percentage for the green component (-100 to 100).
  • gb is the offset for the green component (-255 to 255).
  • ba is the percentage for the blue component (-100 to 100).
  • bb is the offset for the blue component (-255 to 255).
  • aa is the percentage for alpha (-100 to 100).
  • ab is the offset for alpha (-255 to 255).

You create a colorTransformObject parameter as follows:

myColorTransform = new Object();
myColorTransform.ra = 50;
myColorTransform.rb = 244;
myColorTransform.ga = 40;
myColorTransform.gb = 112;
myColorTransform.ba = 12;
myColorTransform.bb = 90;
myColorTransform.aa = 40;
myColorTransform.ab = 70;

You can also use the following syntax to create a colorTransformObject parameter:

myColorTransform = { ra: '50', rb: '244', ga: '40', gb: '112', ba: '12', bb: '90', aa: '40', ab: '70'}

Example

This example creates a new Color object for a target SWF file, creates a generic object called myColorTransform with the properties defined above, and uses the setTransform() method to pass the colorTransformObject to a Color object. To use this code in a Flash (FLA) document, place it on Frame 1 on the main Timeline and place a movie clip on the Stage with the instance name my_mc, as in the following code:

// Create a color object called my_color for the target my_mc
my_color = new Color(my_mc);
// Create a color transform object called myColorTransform using
// the generic Object object
myColorTransform = new Object();
// Set the values for myColorTransform
myColorTransform = { ra: '50', rb: '244', ga: '40', gb: '112', ba: '12', bb: '90', aa: '40', ab: '70'};
// Associate the color transform object with the Color object
// created for my_mc
my_color.setTransform(myColorTransform);


ContextMenu class

Availability

Flash Player 7.

Description

The ContextMenu class provides runtime control over the items in the Flash Player context menu, which appears when a user right-clicks (Windows) or Control-clicks (Macintosh) on Flash Player. You can use the methods and properties of the ContextMenu class to add custom menu items, control the display of the built-in context menu items (for example, Zoom In and Print), or create copies of menus.

You can attach a ContextMenu object to a specific button, movie clip, or text field object, or to an entire movie level. You use the menu property of the Button, MovieClip, or TextField classes to do this. For more information about the menu property, see Button.menu, MovieClip.menu, and TextField.menu.

To add new items to a ContextMenu object, you create a ContextMenuItem object, and then add that object to the ContextMenu.customItems array. For more information about creating context menu items, see the ContextMenuItem class entry.

Flash Player has three types of context menus: the standard menu (which appears when you right-click in Flash Player), the edit menu (which appears when you right-click over a selectable or editable text field), and an error menu (which appears when a SWF file has failed to load into Flash Player.) Only the standard and edit menus can be modified with the ContextMenu class.

Custom menu items always appear at the top of the Flash Player context menu, above any visible built-in menu items; a separator bar distinguishes built-in and custom menu items. A context menu can contain no more than 15 custom menu items.

You must use the constructor new ContextMenu() to create a ContextMenu object before calling its methods.

Method summary for the ContextMenu class

Method | Description
ContextMenu.copy() | Returns a copy of the specified ContextMenu object.
ContextMenu.hideBuiltInItems() | Hides most built-in items in the Flash Player context menu.

Property summary for the ContextMenu class

Property | Description
ContextMenu.builtInItems | An object whose members correspond to built-in context menu items.
ContextMenu.customItems | An array, undefined by default, that contains ContextMenuItem objects.

Event handler summary for the ContextMenu class

Property | Description
ContextMenu.onSelect | Invoked before the menu is displayed.

Constructor for the ContextMenu class

Availability

Flash Player 7.

Usage

new ContextMenu ([callBackFunction])

Parameters

callBackFunction A reference to a function that is called when the user right-clicks or Control-clicks, before the menu is displayed. This parameter is optional.

Returns

A reference to a ContextMenu object.

Description

Constructor; creates a new ContextMenu object. You can optionally specify an identifier for an event handler when you create the object. The specified function is called when the user invokes the context menu, but before the menu is actually displayed. This is useful for customizing menu contents based on application state or based on the type of object (movie clip, text field, or button) that the user right-clicks or Control-clicks. (For an example of creating an event handler, see ContextMenu.onSelect.)

Example

The following example hides all the built-in objects in the Context menu. (However, the Settings and About items still appear, because they cannot be disabled.)

var newMenu = new ContextMenu();
newMenu.hideBuiltInItems();
_root.menu = newMenu;

In this example, the specified event handler, menuHandler, enables or disables a custom menu item (using the ContextMenu.customItems array) based on the value of a Boolean variable named showItem. If false, the custom menu item is disabled; otherwise, it's enabled.

var showItem = false; // Change this to true to see its effect
my_cm = new ContextMenu(menuHandler);
my_cm.customItems.push(new ContextMenuItem("Hello", itemHandler));
function menuHandler(obj, menuObj) {
  if (showItem == false) {
    menuObj.customItems[0].enabled = false;
  } else {
    menuObj.customItems[0].enabled = true;
  }
}
function itemHandler(obj, item) {
}
_root.menu = my_cm;

See also

Button.menu, ContextMenu.onSelect, ContextMenu.customItems, ContextMenu.hideBuiltInItems(), MovieClip.menu, TextField.menu


ContextMenu.builtInItems

Availability

Flash Player 7.

Usage

my_cm.builtInItems

Description

Property; an object that has the following Boolean properties: save, zoom, quality, play, loop, rewind, forward_back, and print. Setting these variables to false removes the corresponding menu items from the specified ContextMenu object. These properties are enumerable and are set to true by default.

Example

In this example, the built-in Quality and Print menu items are disabled for the ContextMenu object my_cm, which is attached to the root Timeline of the SWF file.

var my_cm = new ContextMenu ();
my_cm.builtInItems.quality=false;
my_cm.builtInItems.print=false;
_root.menu = my_cm;

In the next example, a for..in loop enumerates through all names and values of the built-in menu items of the ContextMenu object, my_cm.

my_cm = new ContextMenu();
for(eachProp in my_cm.builtInItems) {
  var propName = eachProp;
  var propValue = my_cm.builtInItems[propName];
  trace(propName + ": " + propValue;
}


ContextMenu.copy()

Availability

Flash Player 7.

Usage

my_cm.copy()

Parameters

None.

Returns

A ContextMenu object.

Description

Method; creates a copy of the specified ContextMenu object. The copy inherits all the properties of the original menu object.

Example

This example creates a copy of the ContextMenu object named my_cm whose built-in menu items are hidden, and adds a menu item with the text "Save...". It then creates a copy of my_cm and assigns it to the variable clone_cm, which inherits all the properties of the original menu.

my_cm = new ContextMenu();
my_cm.hideBuiltInItems();
my_cm.customItems.push(new ContextMenuItem("Save...", saveHandler);
function saveHandler (obj, menuItem) {
  saveDocument(); // custom function (not shown)
}
clone_cm = my_cm.copy();


ContextMenu.customItems

Availability

Flash Player 7.

Usage

my_cm.customItems

Description

Property; an array of ContextMenuItem objects. Each object in the array represents a context menu item that you have defined. Use this property to add, remove, or modify these custom menu items.

To add new menu items, you first create a new ContextMenuItem object, and then add it to the menu_mc.customItems array (using Array.push(), for example). For more information about creating new menu items, see the ContextMenuItem class entry.

Example

The following example creates a new custom menu item called menuItem_cm with a caption of "Send e-mail" and a callback handler named emailHandler (not shown). The new menu item is then added to the ContextMenu object, my_cm, using the customItems array. Lastly, the new menu is attached to a movie clip named email_mc.

var my_cm = new ContextMenu();
var menuItem_cm = new ContextMenuItem("Send e-mail", emailHandler);
my_cm.customItems.push(menuItem_cm);
email_mc.menu = my_cm;

See also

Button.menu, ContextMenu class, MovieClip.menu, TextField.menu


ContextMenu.hideBuiltInItems()

Availability

Flash Player 7.

Usage

my_cm.hideBuiltInItems()

Parameters

None.

Returns

Nothing.

Description

Method; hides all built-in menu items (except Settings) in the specified ContextMenu object. If the Flash Debug Player is running, the Debugging menu item shows, although it is dimmed for SWF files that don't have remote debugging enabled.

This method hides only menu items that appear in the standard context menu; it does not affect items that appear in the edit or error menus. For more information about the different menu types, see the ContextMenu class entry.

This method works by setting all the Boolean members of my_cm.builtInItems to false. You can selectively make a built-in item visible by setting its corresponding member in my_cm.builtInItems to true (as demonstrated in the following example).

Example

The following example creates a new ContextMenu object named my_cm whose built-in menu items are hidden, except for Print. The menu object is attached to the root Timeline.

my_cm = new ContextMenu();
my_cm.hideBuiltInItems();
my_cm.builtInItems.print = true;
_root.menu = my_cm;


ContextMenu.onSelect

Availability

Flash Player 7.

Usage

my_cm.onSelect = function (item:Object, item_menu:ContextMenu) {
  // your code here
}

Parameters

item A reference to the object (movie clip, button, or selectable text field) that was under the mouse pointer when the Flash Player context menu was invoked and whose menu property is set to a valid ContextMenu object.

item_menu A reference to the ContextMenu object assigned to the menu property of object.

Returns

Nothing.

Description

Event handler; called when a user invokes the Flash Player context menu, but before the menu is actually displayed. This lets you customize the contents of the context menu based on the current application state.

You can also specify the callback handler for a ContextMenu object when you construct a new ContextMenu object. For more information, see the ContextMenu class entry.

Example

The following example determines over what type of object the context menu was invoked.

my_cm = new ContextMenu();
menuHandler = function (obj:Object, menu:ContextMenu) {
  if(obj instanceof MovieClip) {
    trace("Movie clip: " + obj);
  }
  if(obj instanceof TextField) {
    trace("Text field: " + obj);
  }
  if(obj instanceof Button) {
    trace("Button: " + obj);
  }
}
my_cm.onSelect = menuHandler;


ContextMenuItem class

Availability

Flash Player 7.

Description

You use the ContextMenuItem class to create custom menu items to display in the Flash Player context menu. Each ContextMenuItem object has a caption (text) that's displayed in the context menu and a callback handler (a function) that's invoked when the menu item is selected. To add a new context menu item to a context menu, you add it to the customItems array of a ContextMenu object.

You can enable or disable specific menu items, make items visible or invisible, or change the caption or callback handler associated with a menu item.

Custom menu items appear at the top of the context menu, above any built-in items. A separator bar always divides custom menu items from built-in items. You can add no more than 15 custom items to the Flash Player context menu. Each item must contain at least one visible character— control characters, newlines, and other white space characters are ignored. No item can be more than 100 characters long. Items that are identical to any built-in menu item, or to another custom item, are ignored, whether the matching item is visible or not. Menu items are compared without regard to case, punctuation, or white space.

None of the following words can appear in a custom item: Macromedia, Flash Player, or Settings.

Method summary for the ContextMenuItem class

Method | Description
ContextMenuItem.copy() | Returns a copy of the specified ContextMenuItem object.

Property summary for the ContextMenuItem class

Property | Description
ContextMenuItem.caption | Specifies the text displayed in the menu item.
ContextMenuItem.enabled | Specifies whether the menu item is enabled or disabled.
ContextMenuItem.separatorBefore | Specifies whether a separator bar should appear above the menu item.
ContextMenuItem.visible | Specifies whether the menu item is visible or not.

Event handler summary for the ContextMenuItem class

Event handler | Description
ContextMenuItem.onSelect | Invoked when the menu item is selected.

Constructor for the ContextMenuItem class

Availability

Flash Player 7.

Usage

new ContextMenuItem(caption, callbackFunction, [ separatorBefore, [ enabled, [ visible ] ] ] )

Parameters

caption A string that specifies the text associated with the menu item.

callbackFunction A function that you define, which is called when the menu item is selected.

separatorBefore A Boolean value that indicates whether a separator bar should appear above the menu item in the context menu. This parameter is optional; its default value is false.

enabled A Boolean value that indicates whether the menu item is enabled or disabled in the context menu. This parameter is optional; its default value is true.

visible A Boolean value that indicates whether the menu item is visible or invisible. This parameter is optional; its default value is true.

Returns

A reference to a ContextMenuItem object.

Description

Constructor; creates a new ContextMenuItem object that can be added to the ContextMenu.customItems array.

Example

This example adds Start and Stop menu items, separated by a bar, to the ContextMenu object my_cm. The startHandler() function is called when Start is selected from the context menu; stopHandler() is called when Stop is selected. The ContextMenu object is applied to the root Timeline.

my_cm = new ContextMenu();
my_cm.customItems.push(new ContextMenuItem("Start", startHandler));
my_cm.customItems.push(new ContextMenuItem("Stop", stopHandler, true));
function stopHandler(obj, item) {
  trace("Stopping...");
}
function startHandler(obj, item) {
  trace("Starting...");
}
_root.menu = my_cm;


ContextMenuItem.caption

Availability

Flash Player 7.

Usage

menuItem_cmi.caption

Description

Property; a string that specifies the menu item caption (text) displayed in the context menu.

Example

This example displays the caption for the selected menu item (Pause Game) in the Output panel.

my_cm = new ContextMenu();
menuItem_cmi = new ContextMenuItem("Pause Game", onPause);
my_cm.customItems.
function onPause(obj, menuItem) {
  trace("You chose: " + menuItem.caption);
}


ContextMenuItem.copy()

Availability

Flash Player 7.

Usage

menuItem_cmi.copy();

Returns

A ContextMenuItem object.

Description

Method; creates and returns a copy of the specified ContextMenuItem object. The copy includes all properties of the original object.

Example

This example creates a new ContextMenuItem object named original_cmi with the caption text Pause and a callback handler set to the function onPause. The example then creates a copy of the ContextMenuItem object and assigns it to the variable copy_cmi.

original_cmi = new ContextMenuItem("Pause", onPause);
function onPause(obj, menu) {
  _root.stop();
}
original_cmi.visible = false;
copy_cmi = orig_cmi.copy();


ContextMenuItem.enabled

Availability

Flash Player 7.

Usage

menuItem_cmi.enabled

Description

Property; a Boolean value that indicates whether the specified menu item is enabled or disabled. By default, this property is true.

Example

The following example creates a new context menu item and then disables that menu item.

var saveMenuItem = new ContextMenuItem("Save...", doSave);
saveMenuItem.enabled = false;


ContextMenuItem.onSelect

Availability

Flash Player 7.

Usage

menuItem_cmi.onSelect = function (obj, menuItem) {
  // your statements here
}

Parameters

obj A reference to the movie clip (or Timeline), button, or selectable (editable) text field that the user right-clicked or Control-clicked.

menuItem A reference to the selected ContextMenuItem object.

Returns

Nothing.

Description

Event handler; invoked when the specified menu item is selected from the Flash Player context menu. The specified callback handler receives two parameters: obj, a reference to the object under the mouse when the user invoked the Flash Player context menu, and menuItem, a reference to the ContextMenuItem object that represents the selected menu item.

Example

The following example assigns a function to the onSelect handler for a ContextMenuItem object named start_cmi. The function displays the caption of the selected menu item.

start_cmi.onSelect = function (obj, item) {
    trace("You choose: " + item.caption);
}

See also

ContextMenu.onSelect


ContextMenuItem.separatorBefore

Availability

Flash Player 7.

Usage

menuItem_cmi.separatorBefore

Description

Property; a Boolean value that indicates whether a separator bar should appear above the specified menu item. By default, this property is false.

Note: A separator bar always appears between any custom menu items and the built-in menu items.

Example

This example creates three menu items labeled Open, Save, and Print. A separator bar divides the Save and Print items. The menu items are then added to the ContextMenu object's customItems array. Lastly, the menu is attached to the root Timeline of the SWF file.

my_cm = new ContextMenu();
open_cmi = new ContextMenuItem("Open", itemHandler);
save_cmi = new ContextMenuItem("Save", itemHandler);
print_cmi = new ContextMenuItem("Print", itemHandler);
print_cmi.separatorBefore = true;
my_cm.customItems.push(open_cmi, save_cmi, print_cmi);
function itemHandler(obj, menuItem) {
    trace("You chose: " + menuItem.caption);
};
_root.menu = my_cm;

See also

ContextMenu.onSelect


ContextMenuItem.visible

Availability

Flash Player 7.

Usage

menuItem_cmi.visible

Description

Property; a Boolean value that indicates whether the specified menu item is visible when the Flash Player context menu is displayed. By default, this property is true.


continue

Availability

Flash Player 4.

Usage

continue

Parameters

None.

Returns

Nothing.

Description

Statement; appears within several types of loop statements; it behaves differently in each type of loop.

In a while loop, continue causes the Flash interpreter to skip the rest of the loop body and jump to the top of the loop, where the condition is tested.

In a do while loop, continue causes the Flash interpreter to skip the rest of the loop body and jump to the bottom of the loop, where the condition is tested.

In a for loop, continue causes the Flash interpreter to skip the rest of the loop body and jump to the evaluation of the for loop's post-expression.

In a for..in loop, continue causes the Flash interpreter to skip the rest of the loop body and jump back to the top of the loop, where the next value in the enumeration is processed.

See also

do while, for, for..in, while


CustomActions class

Availability

Flash Player 6.

Description

The methods of the CustomActions class allow a SWF file playing in the Flash authoring tool to manage any custom actions that are registered with the authoring tool. A SWF file can install and uninstall custom actions, retrieve the XML definition of a custom action, and retrieve the list of registered custom actions.

You can use these methods to build SWF files that are extensions of the Flash authoring tool. Such an extension could, for example, use the Flash Application Protocol to navigate a UDDI repository and download web services into the Actions toolbox.

Method summary for the CustomActions class

Method | Description
CustomActions.get() | Reads the contents of a custom action XML definition file.
CustomActions.install() | Installs a new custom action XML definition file.
CustomActions.list() | Returns a list of all registered custom actions.
CustomActions.uninstall() | Removes a custom action XML definition file.


CustomActions.get()

Availability

Flash Player 6.

Usage

CustomActions.get(customActionsName)

Parameters

customActionsName The name of the custom action definition to retrieve.

Returns

If the custom action XML definition is located, returns a string; otherwise, returns undefined.

Description

Method; reads the contents of the custom action XML definition file named customActionsName.

The name of the definition file must be a simple filename, without the .xml file extension, and without any directory separators (':', '/' or '\').

If the definition file specified by the customActionsName cannot be found, a value of undefined is returned. If the custom action XML definition specified by the customActionsName parameter is located, it is read in its entirety and returned as a string.


CustomActions.install()

Availability

Flash Player 6.

Usage

CustomActions.install(customActionsName, customXMLDefinition)

Parameters

customActionsName The name of the custom action definition to install.

customXMLDefinition The text of the XML definition to install.

Returns

A Boolean value of false if an error occurs during installation; otherwise, a value of true is returned to indicate that the custom action has been successfully installed.

Description

Method; installs a new custom action XML definition file indicated by the customActionsName parameter. The contents of the file is specified by the string customXMLDefinition.

The name of the definition file must be a simple filename, without the .xml file extension, and without any directory separators (':', '/' or '\').

If a custom actions file already exists with the name customActionsName, it is overwritten.

If the Configuration/ActionsPanel/CustomActions directory does not exist when this method is invoked, the directory is created.


CustomActions.list()

Availability

Flash Player 6.

Usage

CustomActions.list()

Parameters

None.

Returns

An array.

Description

Method; returns an Array object containing the names of all the custom actions that are registered with the Flash authoring tool. The elements of the array are simple names, without the .xml file extension, and without any directory separators (for example, ":", "/", or "\"). If there are no registered custom actions, list() returns a zero-length array. If an error occurs, list() returns the value undefined.


CustomActions.uninstall()

Availability

Flash Player 6.

Usage

CustomActions.uninstall(customActionsName)

Parameters

customActionsName The name of the custom action definition to uninstall.

Returns

A Boolean value of false if no custom actions are found with the name customActionsName. If the custom actions were successfully removed, a value of true is returned.

Description

Method; removes the Custom Actions XML definition file named customActionsName.

The name of the definition file must be a simple filename, without the .xml file extension, and without any directory separators (':', '/' or '\').


Date class

Availability

Flash Player 5.

Description

The Date class lets you retrieve date and time values relative to universal time (Greenwich Mean Time, now called universal time or UTC) or relative to the operating system on which Flash Player is running. The methods of the Date class are not static, but apply only to the individual Date object specified when the method is called. The Date.UTC() method is an exception; it is a static method.

The Date class handles daylight saving time differently depending on the operating system and Flash Player version. Flash Player 6 and later versions handle daylight saving time on the following operating systems in these ways:

  • Windows—the Date object automatically adjusts its output for daylight saving time. The Date object detects whether daylight saving time is employed in the current locale, and if so, it detects what the standard-to-daylight-saving-time transition date and times are. However, the transition dates currently in effect are applied to dates in the past and the future, so the daylight saving time bias may be calculated incorrectly for dates in the past when the locale had different transition dates.
  • Mac OS X—the Date object automatically adjusts its output for daylight saving time. The time zone information database in Mac OS X is used to determine whether any date or time in the present or past should have a daylight-saving-time bias applied.

Flash Player 5 handles daylight saving time on the following operating systems as follows:

  • Windows—the U.S. rules for daylight saving time are always applied, which leads to incorrect transitions in Europe and other areas that employ daylight saving time but have different transition times than the U.S. Flash correctly detects whether DST is employed in the current locale.

To call the methods of the Date class, you must first create a Date object using the constructor for the Date class, described later in this section.

Method summary for the Date class

Method | Description
Date.getDate() | Returns the day of the month according to local time.
Date.getDay() | Returns the day of the week according to local time.
Date.getFullYear() | Returns the four-digit year according to local time.
Date.getHours() | Returns the hour according to local time.
Date.getMilliseconds() | Returns the milliseconds according to local time.
Date.getMinutes() | Returns the minutes according to local time.
Date.getMonth() | Returns the month according to local time.
Date.getSeconds() | Returns the seconds according to local time.
Date.getTime() | Returns the number of milliseconds since midnight January 1, 1970, universal time.
Date.getTimezoneOffset() | Returns the difference, in minutes, between the computer's local time and the universal time.
Date.getUTCDate() | Returns the day (date) of the month according to universal time.
Date.getUTCDay() | Returns the day of the week according to universal time.
Date.getUTCFullYear() | Returns the four-digit year according to universal time.
Date.getUTCHours() | Returns the hour according to universal time.
Date.getUTCMilliseconds() | Returns the milliseconds according to universal time.
Date.getUTCMinutes() | Returns the minutes according to universal time.
Date.getUTCMonth() | Returns the month according to universal time.
Date.getUTCSeconds() | Returns the seconds according to universal time.
Date.getYear() | Returns the year according to local time.
Date.setDate() | Sets the day of the month according to local time. Returns the new time in milliseconds.
Date.setFullYear() | Sets the full year according to local time. Returns the new time in milliseconds.
Date.setHours() | Sets the hour according to local time. Returns the new time in milliseconds.
Date.setMilliseconds() | Sets the milliseconds according to local time. Returns the new time in milliseconds.
Date.setMinutes() | Sets the minutes according to local time. Returns the new time in milliseconds.
Date.setMonth() | Sets the month according to local time. Returns the new time in milliseconds.
Date.setSeconds() | Sets the seconds according to local time. Returns the new time in milliseconds.
Date.setTime() | Sets the date in milliseconds. Returns the new time in milliseconds.
Date.setUTCDate() | Sets the date according to universal time. Returns the new time in milliseconds.
Date.setUTCFullYear() | Sets the year according to universal time. Returns the new time in milliseconds.
Date.setUTCHours() | Sets the hour according to universal time. Returns the new time in milliseconds.
Date.setUTCMilliseconds() | Sets the milliseconds according to universal time. Returns the new time in milliseconds.
Date.setUTCMinutes() | Sets the minutes according to universal time. Returns the new time in milliseconds.
Date.setUTCMonth() | Sets the month according to universal time. Returns the new time in milliseconds.
Date.setUTCSeconds() | Sets the seconds according to universal time. Returns the new time in milliseconds.
Date.setYear() | Sets the year according to local time.
Date.toString() | Returns a string value representing the date and time stored in the specified Date object.
Date.UTC() | Returns the number of milliseconds between midnight on January 1, 1970, universal time, and the specified time.

Constructor for the Date class

Availability

Flash Player 5.

Usage

new Date()
new Date(year, month [, date [, hour [, minute [, second [, millisecond ]]]]])

Parameters

year A value of 0 to 99 indicates 1900 though 1999; otherwise all four digits of the year must be specified.

month An integer from 0 (January) to 11 (December).

date An integer from 1 to 31. This parameter is optional.

hour An integer from 0 (midnight) to 23 (11 p.m.).

minute An integer from 0 to 59. This parameter is optional.

second An integer from 0 to 59. This parameter is optional.

millisecond An integer from 0 to 999. This parameter is optional.

Returns

A reference to a Date object.

Description

Object; constructs a new Date object that holds the current date and time, or the date specified.

Example

The following example retrieves the current date and time.

now_date = new Date();

The following example creates a new Date object for Gary's birthday, August 12, 1974. (Because the month parameter is zero-based, the example uses 7 for the month, not 8.)

garyBirthday_date = new Date (74, 7, 12);

The following example creates a new Date object, concatenates the returned values of Date.getMonth(), Date.getDate(), and Date.getFullYear(), and displays them in the text field specified by the variable date_str.

today_date = new Date();
date_str = ((today_date.getMonth() + 1) + "/" + today_date.getDate() + "/" + today_date.getFullYear());


Date.getDate()

Availability

Flash Player 5.

Usage

my_date.getDate()

Parameters

None.

Returns

An integer.

Description

Method; returns the day of the month (an integer from 1 to 31) of the specified Date object according to local time. Local time is determined by the operating system on which Flash Player is running.


Date.getDay()

Availability

Flash Player 5.

Usage

my_date.getDay()

Parameters

None.

Returns

An integer.

Description

Method; returns the day of the week (0 for Sunday, 1 for Monday, and so on) of the specified Date object according to local time. Local time is determined by the operating system on which Flash Player is running.


Date.getFullYear()

Availability

Flash Player 5.

Usage

my_date.getFullYear()

Parameters

None.

Returns

An integer.

Description

Method; returns the full year (a four-digit number, for example, 2000) of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running.

Example

The following example uses the constructor to create a new Date object and send the value returned by the getFullYear() method to the Output panel:

my_date = new Date();
trace(my_date.getFullYear());


Date.getHours()

Availability

Flash Player 5.

Usage

my_date.getHours()

Parameters

None.

Returns

An integer.

Description

Method; returns the hour (an integer from 0 to 23) of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running.


Date.getMilliseconds()

Availability

Flash Player 5.

Usage

my_date.getMilliseconds()

Parameters

None.

Returns

An integer.

Description

Method; returns the milliseconds (an integer from 0 to 999) of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running.


Date.getMinutes()

Availability

Flash Player 5.

Usage

my_date.getMinutes()

Parameters

None.

Returns

An integer.

Description

Method; returns the minutes (an integer from 0 to 59) of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running.


Date.getMonth()

Availability

Flash Player 5.

Usage

my_date.getMonth()

Parameters

None.

Returns

An integer.

Description

Method; returns the month (0 for January, 1 for February, and so on) of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running.


Date.getSeconds()

Availability

Flash Player 5.

Usage

my_date.getSeconds()

Parameters

None.

Returns

An integer.

Description

Method; returns the seconds (an integer from 0 to 59) of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running.


Date.getTime()

Availability

Flash Player 5.

Usage

my_date.getTime()

Parameters

None.

Returns

An integer.

Description

Method; returns the number of milliseconds since midnight January 1, 1970, universal time, for the specified Date object. Use this method to represent a specific instant in time when comparing two or more Date objects.


Date.getTimezoneOffset()

Availability

Flash Player 5.

Usage

my_date.getTimezoneOffset()

Parameters

None.

Returns

An integer.

Description

Method; returns the difference, in minutes, between the computer's local time and universal time.

Example

The following example returns the difference between the local daylight saving time for San Francisco and universal time. Daylight saving time is factored into the returned result only if the date defined in the Date object occurs during daylight saving time.

trace(new Date().getTimezoneOffset());
// 420 is displayed in the Output panel
// (7 hours * 60 minutes/hour = 420 minutes)
// This example is Pacific Daylight Time (PDT, GMT-0700).
// Result will vary depending on locale and time of year.


Date.getUTCDate()

Availability

Flash Player 5.

Usage

my_date.getUTCDate()

Parameters

None.

Returns

An integer.

Description

Method; returns the day of the month (an integer from 1 to 31) in the specified Date object, according to universal time.


Date.getUTCDay()

Availability

Flash Player 5.

Usage

my_date.getUTCDay()

Parameters

None.

Returns

An integer.

Description

Method; returns the day of the week (0 for Sunday, 1 for Monday, and so on) of the specified Date object, according to universal time.


Date.getUTCFullYear()

Availability

Flash Player 5.

Usage

my_date.getUTCFullYear()

Parameters

None.

Returns

An integer.

Description

Method; returns the four-digit year of the specified Date object, according to universal time.


Date.getUTCHours()

Availability

Flash Player 5.

Usage

my_date.getUTCHours()

Parameters

None.

Returns

An integer.

Description

Method; returns the hours of the specified Date object, according to universal time.


Date.getUTCMilliseconds()

Availability

Flash Player 5.

Usage

my_date.getUTCMilliseconds()

Parameters

None.

Returns

An integer.

Description

Method; returns the milliseconds of the specified Date object, according to universal time.


Date.getUTCMinutes()

Availability

Flash Player 5.

Usage

my_date.getUTCMinutes()

Parameters

None.

Returns

An integer.

Description

Method; returns the minutes of the specified Date object, according to universal time.


Date.getUTCMonth()

Availability

Flash Player 5.

Usage

my_date.getUTCMonth()

Parameters

None.

Returns

An integer.

Description

Method; returns the month (0 for January, 1 for February, and so on) of the specified Date object, according to universal time.


Date.getUTCSeconds()

Availability

Flash Player 5.

Usage

my_date.getUTCSeconds()

Parameters

None.

Returns

An integer.

Description

Method; returns the seconds in the specified Date object, according to universal time.


Date.getYear()

Availability

Flash Player 5.

Usage

my_date.getYear()

Parameters

None.

Returns

An integer.

Description

Method; returns the year of the specified Date object, according to local time. Local time is determined by the operating system on which Flash Player is running. The year is the full year minus 1900. For example, the year 2000 is represented as 100.

See also

Date.getFullYear()


Date.setDate()

Availability

Flash Player 5.

Usage

my_date.setDate(date)

Parameters

date An integer from 1 to 31.

Returns

An integer.

Description

Method; sets the day of the month for the specified Date object, according to local time, and returns the new time in milliseconds. Local time is determined by the operating system on which Flash Player is running.


Date.setFullYear()

Availability

Flash Player 5.

Usage

my_date.setFullYear(year [, month [, date]] )

Parameters

year A four-digit number specifying a year. Two-digit numbers do not represent years; for example, 99 is not the year 1999, but the year 99.

month An integer from 0 (January) to 11 (December). This parameter is optional.

date A number from 1 to 31. This parameter is optional.

Returns

An integer.

Description

Method; sets the year of the specified Date object, according to local time, and returns the new time in milliseconds. If the month and date parameters are specified, they are also set to local time. Local time is determined by the operating system on which Flash Player is running.

Calling this method does not modify the other fields of the specified Date object but Date.getUTCDay() and Date.getDay() may report a new value if the day of the week changes as a result of calling this method.


Date.setHours()

Availability

Flash Player 5.

Usage

my_date.setHours(hour)

Parameters

hour An integer from 0 (midnight) to 23 (11 p.m.).

Returns

An integer.

Description

Method; sets the hours for the specified Date object according to local time, and returns the new time in milliseconds. Local time is determined by the operating system on which Flash Player is running.


Date.setMilliseconds()

Availability

Flash Player 5.

Usage

my_date.setMilliseconds(millisecond)

Parameters

millisecond An integer from 0 to 999.

Returns

An integer.

Description

Method; sets the milliseconds for the specified Date object according to local time, and returns the new time in milliseconds. Local time is determined by the operating system on which Flash Player is running.


Date.setMinutes()

Availability

Flash Player 5.

Usage

my_date.setMinutes(minute)

Parameters

minute An integer from 0 to 59.

Returns

An integer.

Description

Method; sets the minutes for a specified Date object according to local time, and returns the new time in milliseconds. Local time is determined by the operating system on which Flash Player is running.


Date.setMonth()

Availability

Flash Player 5.

Usage

my_date.setMonth(month [, date ])

Parameters

month An integer from 0 (January) to 11 (December).

date An integer from 1 to 31. This parameter is optional.

Returns

An integer.

Description

Method; sets the month for the specified Date object in local time, and returns the new time in milliseconds. Local time is determined by the operating system on which Flash Player is running.


Date.setSeconds()

Availability

Flash Player 5.

Usage

my_date.setSeconds(second)

Parameters

second An integer from 0 to 59.

Returns

An integer.

Description

Method; sets the seconds for the specified Date object in local time, and returns the new time in milliseconds. Local time is determined by the operating system on which Flash Player is running.


Date.setTime()

Availability

Flash Player 5.

Usage

my_date.setTime(milliseconds)

Parameters

milliseconds An integer value where 0 is 0:00 GMT 1970 Jan 1.

Returns

An integer.

Description

Method; sets the date for the specified Date object in milliseconds since midnight on January 1, 1970, and returns the new time in milliseconds.


Date.setUTCDate()

Availability

Flash Player 5.

Usage

my_date.setUTCDate(date)

Parameters

date An integer from 1 to 31.

Returns

An integer.

Description

Method; sets the date for the specified Date object in universal time, and returns the new time in milliseconds. Calling this method does not modify the other fields of the specified Date object, but Date.getUTCDay() and Date.getDay() may report a new value if the day of the week changes as a result of calling this method.


Date.setUTCFullYear()

Availability

Flash Player 5.

Usage

my_date.setUTCFullYear(year [, month [, date]])

Parameters

year The year specified as a full four-digit year, for example, 2000.

month An integer from 0 (January) to 11 (December). This parameter is optional.

date An integer from 1 to 31. This parameter is optional.

Returns

An integer.

Description

Method; sets the year for the specified Date object (my_date) in universal time, and returns the new time in milliseconds.

Optionally, this method can also set the month and date represented by the specified Date object. Calling this method does not modify the other fields of the specified Date object, but Date.getUTCDay() and Date.getDay() may report a new value if the day of the week changes as a result of calling this method.


Date.setUTCHours()

Availability

Flash Player 5.

Usage

my_date.setUTCHours(hour [, minute [, second [, millisecond]]])

Parameters

hour An integer from 0 (midnight) to 23 (11 p.m.).

minute An integer from 0 to 59. This parameter is optional.

second An integer from 0 to 59. This parameter is optional.

millisecond An integer from 0 to 999. This parameter is optional.

Returns

An integer.

Description

Method; sets the hour for the specified Date object in universal time, and returns the new time in milliseconds.


Date.setUTCMilliseconds()

Availability

Flash Player 5.

Usage

my_date.setUTCMilliseconds(millisecond)

Parameters

millisecond An integer from 0 to 999.

Returns

An integer.

Description

Method; sets the milliseconds for the specified Date object in universal time, and returns the new time in milliseconds.


Date.setUTCMinutes()

Availability

Flash Player 5.

Usage

my_date.setUTCMinutes(minute [, second [, millisecond]])

Parameters

minute An integer from 0 to 59.

second An integer from 0 to 59. This parameter is optional.

millisecond An integer from 0 to 999. This parameter is optional.

Returns

An integer.

Description

Method; sets the minute for the specified Date object in universal time, and returns the new time in milliseconds.


Date.setUTCMonth()

Availability

Flash Player 5.

Usage

my_date.setUTCMonth(month [, date])

Parameters

month An integer from 0 (January) to 11 (December).

date An integer from 1 to 31. This parameter is optional.

Returns

An integer.

Description

Method; sets the month, and optionally the day (date), for the specified Date object in universal time, and returns the new time in milliseconds. Calling this method does not modify the other fields of the specified Date object, but Date.getUTCDay() and Date.getDay() may report a new value if the day of the week changes as a result of specifying a value for the date parameter.


Date.setUTCSeconds()

Availability

Flash Player 5.

Usage

my_date.setUTCSeconds(second [, millisecond]))

Parameters

second An integer from 0 to 59.

millisecond An integer from 0 to 999. This parameter is optional.

Returns

An integer.

Description

Method; sets the seconds for the specified Date object in universal time, and returns the new time in milliseconds.


Date.setYear()

Availability

Flash Player 5.

Usage

my_date.setYear(year)

Parameters

year If year is an integer between 0-99, setYear sets the year at 1900 + year; otherwise, the year is the value of the year parameter.

Returns

An integer.

Description

Method; sets the year for the specified Date object in local time, and returns the new time in milliseconds. Local time is determined by the operating system on which Flash Player is running.


Date.toString()

Availability

Flash Player 5.

Usage

my_date.toString()

Parameters

None.

Returns

A string.

Description

Method; returns a string value for the specified date object in a readable format, and returns the new time in milliseconds.

Example

The following example returns the information in the dateOfBirth_date Date object as a string.

var dateOfBirth_date = new Date(74, 7, 12, 18, 15);
trace (dateOfBirth_date.toString());

Output (for Pacific Standard Time):

Mon Aug 12 18:15:00 GMT-0700 1974


Date.UTC()

Availability

Flash Player 5.

Usage

Date.UTC(year, month [, date [, hour [, minute [, second [, millisecond ]]]]])

Parameters

year A four-digit number, for example, 2000.

month An integer from 0 (January) to 11 (December).

date An integer from 1 to 31. This parameter is optional.

hour An integer from 0 (midnight) to 23 (11 p.m.).

minute An integer from 0 to 59. This parameter is optional.

second An integer from 0 to 59. This parameter is optional.

millisecond An integer from 0 to 999. This parameter is optional.

Returns

An integer.

Description

Method; returns the number of milliseconds between midnight on January 1, 1970, universal time, and the time specified in the parameters. This is a static method that is invoked through the Date object constructor, not through a specific Date object. This method lets you create a Date object that assumes universal time, whereas the Date constructor assumes local time.

Example

The following example creates a new garyBirthday_date Date object defined in universal time. This is the universal time variation of the example used for the new Date constructor method:

garyBirthday_date = new Date(Date.UTC(1974, 7, 12));


default

Availability

Flash Player 6.

Usage

default: statements

Parameters

statements Any statements.

Returns

Nothing.

Description

Statement; defines the default case for a switch action. The statements execute if the expression parameter of the switch action doesn't equal (using strict equality) any of the expression parameters that follow the case keywords for a given switch action.

A switch is not required to have a default case. A default case does not have to be last in the list. Using a default action outside a switch action is an error and the script doesn't compile.

Example

In the following example, the expression A does not equal the expressions B or D so the statement following the default keyword is run and the trace() action is sent to the Output panel.

switch ( A ) {
  case B:
    C;
    break;
  case D:
    E;
    break;
  default:
    trace ("no specific case was encountered");
}

See also

switch, case, break


delete

Availability

Flash Player 5.

Usage

delete reference

Parameters

reference The name of the variable or object to eliminate.

Returns

A Boolean value.

Description

Operator; destroys the object or variable specified by the reference parameter, and returns true if the object was successfully deleted; otherwise returns a value of false. This operator is useful for freeing up memory used by scripts. Although delete is an operator, it is typically used as a statement, as in the following:

delete x;

The delete operator may fail and return false if the reference parameter does not exist, or may not be deleted. Predefined objects and properties, and variables declared with var, may not be deleted. You cannot use the delete operator to remove movie clips.

Example

Usage 1: The following example creates an object, uses it, and then deletes it after it is no longer needed.

account = new Object();
account.name = 'Jon';
account.balance = 10000;

delete account;

Usage 2: The following example deletes a property of an object.

// create the new object "account"
account = new Object();
// assign property name to the account
account.name = 'Jon';
// delete the property
delete account.name;

Usage 3: The following is another example of deleting an object property.

// create an Array object with length 0
my_array = new Array();
// add an element to the array. Array.length is now 1
my_array[0] = "abc";
// add another element to the array. Array.length is now 2
my_array[1] = "def";
// add another element to the array. Array.length is now 3
my_array[2] = "ghi";
// my_array[2] is deleted, but Array.length is not changed
delete array[2];
trace(my_array.length);

Usage 4: The following example illustrates the behavior of delete on object references.

// create a new object, and assign the variable ref1

// to refer to the object
ref1 = new Object();
ref1.name = "Jody";
// copy the reference variable into a new variable
// and delete ref1
ref2 = ref1;
delete ref1;

If ref1 had not been copied into ref2, the object would have been deleted when ref1 was deleted, because there would be no references to it. If you delete ref2, there will no longer be any references to the object; it will be destroyed, and the memory it was using will be made available.

See also

var


do while

Availability

Flash Player 4.

Usage

do {
  statement(s)
} while (condition)

Parameters

condition The condition to evaluate.

statement(s) The statement(s) to execute as long as the condition parameter evaluates to true.

Returns

Nothing.

Description

Statement; executes the statements, and then evaluates the condition in a loop for as long as the condition is true.

See also

break, continue


duplicateMovieClip()

Availability

Flash Player 4.

Usage

duplicateMovieClip(target, newname, depth)

Parameters

target The target path of the movie clip to duplicate.

newname A unique identifier for the duplicated movie clip.

depth A unique depth level for the duplicated movie clip. The depth level is a stacking order for duplicated movie clips. This stacking order is much like the stacking order of layers in the Timeline; movie clips with a lower depth level are hidden under clips with a higher stacking order. You must assign each duplicated movie clip a unique depth level to prevent it from replacing SWF files on occupied depths.

Returns

A reference to the duplicated movie clip.

Description

Function; creates an instance of a movie clip while the SWF file is playing. The playhead in duplicate movie clips always starts at Frame 1, regardless of where the playhead is in the original (or "parent") movie clip. Variables in the parent movie clip are not copied into the duplicate movie clip. If the parent movie clip is deleted the duplicate movie clip is also deleted. Use the removeMovieClip() action or method to delete a movie clip instance created with duplicateMovieClip().

See also

MovieClip.duplicateMovieClip(), removeMovieClip(), MovieClip.removeMovieClip()


dynamic

Availability

Flash Player 6.

Usage

dynamic class className  [ extends superClass ]
              [ implements interfaceName [, interfaceName... ] ]
{
  // class definition here
}

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Description

Keyword; specifies that objects based on the specified class can add and access dynamic properties at runtime.

Type checking on dynamic classes is less strict than type-checking on nondynamic classes, because members accessed inside the class definition and on class instances are not compared to those defined in the class scope. Class member functions, however, can still be type checked for return type and parameter types. This behavior is especially useful when you work with MovieClip objects, because there are many different ways of adding properties and objects to a movie clip dynamically, such as MovieClip.createEmptyMovieClip() and MovieClip.createTextField().

Subclasses of dynamic classes are also dynamic.

For more information, see Creating dynamic classes.

Example

In the following example, class B has been marked as dynamic, so calling an undeclared function on it will not throw an error at compile time.

// in B.as
dynamic class B extends class_A {
  function B() {
    /*this is the constructor*/
  }
  function m():Number {return 25;}
  function o(s:String):Void {trace(s);}
}
// in C.as
class C extends class_A {
  function C() {
    /*this is the constructor*/
  }
  function m():Number {return 25;}
  function o(s:String):Void {trace(s);}
}
// in another script
var var1 = B.n();   // no error
var var2 = C.n()    // error, as there is no function n in C.as

See also

class, extends


else

Availability

Flash Player 4.

Usage

if (condition){
  statement(s);
} else (condition){
  statement(s);
}

Parameters

condition An expression that evaluates to true or false.

statement(s) An alternative series of statements to run if the condition specified in the if statement is false.

Returns

Nothing.

Description

Statement; specifies the statements to run if the condition in the if statement returns false.

See also

if


else if

Availability

Flash Player 4.

Usage

if (condition){
  statement(s);
} else if (condition){
  statement(s);
}

Parameters

condition An expression that evaluates to true or false.

statement(s) An alternative series of statements to run if the condition specified in the if statement is false.

Returns

Nothing.

Description

Statement; evaluates a condition and specifies the statements to run if the condition in the initial if statement returns false. If the else if condition returns true, the Flash interpreter runs the statements that follow the condition inside curly braces ({}). If the else if condition is false, Flash skips the statements inside the curly braces and runs the statements following the curly braces. Use the else if action to create branching logic in your scripts.

Example

The following example uses else if actions to check whether each side of an object is within a specific boundary:

// if the object goes off bounds,
// send it back and reverse its travel speed
    if (this._x>rightBound) {
      this._x = rightBound;
      xInc = -xInc;
    } else if (this._x<leftBound) {
      this._x = leftBound;
      xInc = -xInc;
    } else if (this._y>bottomBound) {
      this._y = bottomBound;
      yInc = -yInc;
    } else if (this._y<topBound) {
      this._y = topBound;
      yInc = -yInc;
    }

See also

if


#endinitclip

Availability

Flash Player 6.

Usage

#endinitclip

Parameters

None.

Returns

Nothing.

Description

Compiler directive; indicates the end of a block of initialization actions.

Example

#initclip
...initialization actions go here...
#endinitclip

See also

#initclip


eq (equal — string specific)

Availability

Flash Player 4. This operator was deprecated in Flash 5 in favor of the == (equality) operator.

Usage

expression1 eq expression2

Parameters

expression1, expression2 Numbers, strings, or variables.

Returns

Nothing.

Description

Comparison operator; compares two expressions for equality and returns a value of true if the string representation of expression1 is equal to the string representation of expression2; otherwise, the operation returns a value of false.

See also

== (equality)


Error class

Availability

Flash Player 7.

Description

Contains information about an error that occurred in a script. You create an Error object using the Error constructor function. Typically, you "throw" a new Error object from within a try code block that is then "caught" by a catch or finally code block.

You can also create a subclass of the Error class and throw instances of that subclass.

Method summary for the Error class

Method | Description
Error.toString() | Returns the string representation of an Error object.

Property summary for the Error class

Property | Description
Error.message | A string that contains an error message associated with an error.
Error.name | A string that contains the name of the Error object.

Constructor for the Error class

Availability

Flash Player 7.

Usage

new Error([message])

Parameters

message A string associated with the Error object; this parameter is optional.

Returns

A reference to an Error object.

Description

Constructor; creates a new Error object. If message is specified, its value is assigned to the object's Error.message property.

Example

In the following example, a function throws an error (with a specified message) if the two strings that are passed to it are not identical.

function compareStrings(string_1, string_2) {
  if(string_1 != string_2) {
    throw new Error("Strings do not match.");
  }
}
try {
  compareStrings("Dog","dog");
} catch (e) {
  trace(e.toString());
}

See also

throw, try..catch..finally


Error.message

Availability

Flash Player 7.

Usage

myError.message

Description

Property; contains the message associated with the Error object. By default, the value of this property is "Error". You can specify a message property when you create a new Error object by passing the error string to the Error constructor function.

See also

throw, try..catch..finally


Error.name

Availability

Flash Player 7.

Usage

myError.name

Description

Property; contains the name of the Error object. By default, the value of this property is "Error".

See also

throw, try..catch..finally


Error.toString()

Availability

Flash Player 7.

Usage

my_err.toString()

Returns

A string.

Description

Method; returns the string "Error" by default, or the value contained in Error.message, if defined.

See also

Error.message, throw, try..catch..finally


escape

Availability

Flash Player 5.

Usage

escape(expression)

Parameters

expression The expression to convert into a string and encode in a URL-encoded format.

Returns

Nothing.

Description

Function; converts the parameter to a string and encodes it in a URL-encoded format, where all nonalphanumeric characters are escaped with % hexadecimal sequences.

Example

Running the following code gives the result, Hello%7B%5BWorld%5D%7D.

escape("Hello{[World]}");

See also

unescape


eval()

Availability

Flash Player 5 or later for full functionality. You can use the eval() function when exporting to Flash Player 4, but you must use slash notation, and can only access variables, not properties or objects.

Usage

eval(expression)

Parameters

expression A string containing the name of a variable, property, object, or movie clip to retrieve.

Returns

A value, reference to an object or movie clip, or undefined.

Description

Function; accesses variables, properties, objects, or movie clips by name. If expression is a variable or a property, the value of the variable or property is returned. If expression is an object or movie clip, a reference to the object or movie clip is returned. If the element named in expression cannot be found, undefined is returned.

In Flash 4, eval() was used to simulate arrays; in Flash 5 or later, it is recommended that you use the Array class to simulate arrays.

In Flash 4, you can also use eval() to dynamically set and retrieve the value of a variable or instance name. However, you can also do this with the array access operator ([]).

In Flash 5 or later, you cannot use eval() to dynamically set and retrieve the value of a variable or instance name, because you cannot use eval() on the left side of an equation. For example, replace the code

eval ("var" + i) = "first";

with this:

this["var"+i] = "first"

or this:

set ("var" + i, "first");

Example

The following example uses eval() to determine the value of the expression "piece" + x. Because the result is a variable name, piece3, eval() returns the value of the variable and assigns it to y:

piece3 = "dangerous";
x = 3;
y = eval("piece" + x);
trace(y);
// Output: dangerous

See also

Array class


extends

Availability

Flash Player 6.

Usage

class className extends otherClassName {}
interface interfaceName extends otherInterfaceName {}

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Parameters

className The name of the class you are defining.

otherClassName The name of the class on which className is based.

interfaceName The name of the interface you are defining.

otherInterfaceName The name of the interface on which interfaceName is based.

Description

Keyword; defines a class or interface that is a subclass of another class or interface; the latter is the superclass. The subclass inherits all the methods, properties, functions, and so on that are defined in the superclass.

For more information, see Creating subclasses.

Example

In class B as defined below, a call to class A's constructor will automatically be inserted as the first statement of B's constructor function, because a call does not already exist there. (That is, it is commented out in the example.)

class B extends class A
{
  function B() { // this is the constructor
//    super(); // optional; inserted during compilation if omitted
  }
  function m():Number {return 25;}
  function o(s:String):Void {trace(s);}
}

See also

class, implements, interface


false

Availability

Flash Player 5.

Usage

false

Description

Constant; a unique Boolean value that represents the opposite of true.

See also

true


_focusrect

Availability

Flash Player 4.

Usage

_focusrect = Boolean;

Description

Property (global); specifies whether a yellow rectangle appears around the button or movie clip that has keyboard focus. The default value, true, displays a yellow rectangle around the currently focused button or movie clip as the user presses the Tab key to navigate through objects in a SWF file. Specify false if you do not want to display the yellow rectangle. This is a global property that can be overridden for specific instances.

See also

Button._focusrect, MovieClip._focusrect


for

Availability

Flash Player 5.

Usage

for(init; condition; next) {
  statement(s);
}

Parameters

init An expression to evaluate before beginning the looping sequence, typically an assignment expression. A var statement is also permitted for this parameter.

condition An expression that evaluates to true or false. The condition is evaluated before each loop iteration; the loop exits when the condition evaluates to false.

next An expression to evaluate after each loop iteration; usually an assignment expression using the ++ (increment) or -- (decrement) operators.

statement(s) An instruction or instructions to execute within the body of the loop.

Description

Statement; a loop construct that evaluates the init (initialize) expression once, and then begins a looping sequence by which, as long as the condition evaluates to true, statement is executed and the next expression is evaluated.

Some properties cannot be enumerated by the for or for..in actions. For example, the built-in methods of the Array class (such as Array.sort() and Array.reverse()) are not included in the enumeration of an Array object, and movie clip properties, such as _x and _y, are not enumerated. In external class files, instance members are not enumerable; only dynamic and static members are enumerable.

Example

The following example uses for to add the elements in an array:

my_array=new Array();
for(i=0; i<10; i++) {
  my_array [i] = (i + 5)*10;
  trace(my_array[i]);
}

The following results are displayed in the Output panel:

50
60
70
80
90
100
110
120
130
140

The following is an example of using for to perform the same action repeatedly. In the following code, the for loop adds the numbers from 1 to 100:

var sum = 0;
  for (var i=1; i<=100; i++) {
    sum = sum + i;
  }

See also

++ (increment), -- (decrement), for..in, var


for..in

Availability

Flash Player 5.

Usage

for(variableIterant in object){
  statement(s);
}

Parameters

variableIterant The name of a variable to act as the iterant, referencing each property of an object or element in an array.

object The name of an object to be repeated.

statement(s) An instruction to execute for each iteration.

Returns

Nothing.

Description

Statement; loops through the properties of an object or element in an array, and executes the statement for each property of an object.

Some properties cannot be enumerated by the for or for..in actions. For example, the built-in methods of the Array class (such as Array.sort() and Array.reverse()) are not included in the enumeration of an Array object, and movie clip properties, such as _x and _y, are not enumerated. In external class files, instance members are not enumerable; only dynamic and static members are enumerable.

The for..in statement iterates over properties of objects in the iterated object's prototype chain. If the child's prototype is parent, iterating over the properties of the child with for..in, will also iterate over the properties of parent.

The for..in action enumerates all objects in the prototype chain of an object. Properties of the object are enumerated first, then properties of its immediate prototype, then properties of the prototype's prototype, and so on. The for..in action does not enumerate the same property name twice. If the object child has prototype parent and both contain the property prop, the for..in action called on child enumerates prop from child but ignores the one in parent.

Example

The following is an example of using for..in to iterate over the properties of an object:

myObject = { name:'Tara', age:27, city:'San Francisco' };
for (name in myObject) {
  trace ("myObject." + name + " = " + myObject[name]);
}

The output of this example is as follows:

myObject.name = Tara
myObject.age = 27
myObject.city = San Francisco

The following is an example of using the typeof operator with for..in to iterate over a particular type of child:

for (name in my_mc) {
  if (typeof (my_mc[name]) = "movieclip") {
    trace ("I have a movie clip child named " + name);
  }
}

The following example enumerates the children of a movie clip and sends each to Frame 2 in their respective Timelines. The RadioButtonGroup movie clip is a parent with several children, _RedRadioButton_, _GreenRadioButton_ and _BlueRadioButton.

for (var name in RadioButtonGroup) {
  RadioButtonGroup[name].gotoAndStop(2);
}


fscommand()

Availability

Flash Player 3.

Usage

fscommand("command", "parameters")

Parameters

command A string passed to the host application for any use or a command passed to Flash Player.

parameters A string passed to the host application for any use or a value passed to Flash Player.

Returns

Nothing.

Description

Function; allows the SWF file to communicate with either Flash Player or the program hosting Flash Player, such as a web browser. You can also use the fscommand action to pass messages to Macromedia Director, or to Visual Basic, Visual C++, and other programs that can host ActiveX controls.

Usage 1: To send a message to Flash Player, you must use predefined commands and parameters. The following table shows the values you can specify for the command and parameters parameters of the fscommand action to control a SWF file playing in Flash Player (including projectors):

Command | Parameters | Purpose
quit | None | Closes the projector.
fullscreen | true or false | Specifying true sets Flash Player to full-screen mode. Specifying false returns the player to normal menu view.
allowscale | true or false | Specifying false sets the player so that the SWF file is always drawn at its original size and never scaled. Specifying true forces the SWF file to scale to 100% of the player.
showmenu | true or false | Specifying true enables the full set of context menu items. Specifying false dims all the context menu items except About Flash Player.
exec | Path to application | Executes an application from within the projector.
trapallkeys | true or false | Specifying true sends all key events, including accelerator keys, to the onClipEvent(keyDown/keyUp) handler in Flash Player.

The exec command can contain only the characters A-Z, a-z, 0-9, period ()., and underscore (_). The exec command runs in the subdirectory fscommand only. In other words, if you use the fscommand exec command to call an application, the application must reside in a subdirectory named fscommand.

Usage 2: To use the fscommand action to send a message to a scripting language such as JavaScript in a web browser, you can pass any two parameters in the command and parameters parameters. These parameters can be strings or expressions and are used in a JavaScript function that "catches," or handles, the fscommand action.

In a web browser, the fscommand action calls the JavaScript function moviename_DoFScommand in the HTML page containing the SWF file. The moviename is the name of the Flash Player as assigned by the NAME attribute of the EMBED tag or the ID property of the OBJECT tag. If you assign the Flash Player the name myDocument, the JavaScript function called is myDocument_DoFScommand.

Usage 3: The fscommand action can send messages to Macromedia Director that are interpreted by Lingo as strings, events, or executable Lingo code. If the message is a string or an event, you must write the Lingo code to receive the message from the fscommand action and carry out an action in Director. For more information, see the Director Support Center at www.macromedia.com/support/director.

Usage 4: In Visual Basic, Visual C++, and other programs that can host ActiveX controls, fscommand sends a VB event with two strings that can be handled in the environment's programming language. For more information, use the keywords Flash method to search the Flash Support Center at www.macromedia.com/support/flash.

Example

Usage 1: In the following example, the fscommand action sets the Flash Player to scale the SWF file to the full monitor screen size when the button is released.

on(release){
  fscommand("fullscreen", true);
}

Usage 2: The following example uses the fscommand action applied to a button in Flash to open a JavaScript message box in an HTML page. The message itself is sent to JavaScript as the fscommand parameter.

You must add a function to the HTML page that contains the SWF file. This function, myDocument_DoFSCommand sits in the HTML page and waits for an fscommand action in Flash. When an fscommand is triggered in Flash (for example, when a user presses the button), the command and parameter strings are passed to the myDocument_DoFSCommand function. You can use the passed strings in your JavaScript or VBScript code in any way you like. In this example, the function contains a conditional if statement that checks to see if the command string is "messagebox". If it is, a JavaScript alert box (or "message box") opens and displays the contents of the parameters string.

function myDocument_DoFSCommand(command, args) {
  if (command == "messagebox") {
    alert(args);
  }
}

In the Flash document, add the fscommand action to a button:

fscommand("messagebox", "This is a message box called from within Flash.")

You can also use expressions for the fscommand action and parameters, as in the following example:

fscommand("messagebox", "Hello, " + name + ", welcome to our website!")

To test the movie, choose File > Publish Preview > HTML.

Note: If you publish your SWF file using the Flash with FSCommand template in the HTML Publish Settings, the myDocument_DoFSCommand function is inserted automatically. The SWF file's NAME and ID attributes will be the filename. For example, for the file myDocument.fla, the attributes would be set to myDocument.


function

Availability

Flash Player 5.

Usage

function functionname ([parameter0, parameter1,...parameterN]){
  statement(s)
}
function ([parameter0, parameter1,...parameterN]){
  statement(s)
}

Parameters

functionname The name of the new function.

parameter An identifier that represents a parameter to pass to the function. These parameters are optional.

statement(s) Any ActionScript instruction you have defined for the body of the function.

Returns

Nothing.

Description

Statement; comprises a set of statements that you define to perform a certain task. You can declare, or define, a function in one location and call, or invoke, it from different scripts in a SWF file. When you define a function, you can also specify parameters for the function. Parameters are placeholders for values on which the function operates. You can pass different parameters to a function each time you call it. This lets you reuse one function in many different situations.

Use the return action in a function's statement(s) to cause a function to return, or generate, a value.

Usage 1: Declares a function with the specified functionname, parameters, and statement(s). When a function is called, the function declaration is invoked. Forward referencing is permitted; within the same Action list, a function may be declared after it is called. A function declaration replaces any prior declaration of the same function. You can use this syntax wherever a statement is permitted.

Usage 2: Creates an anonymous function and returns it. This syntax is used in expressions, and is particularly useful for installing methods in objects.

Example

Usage 1: The following example defines the function sqr, which accepts one parameter and returns the square(x*x) of the parameter. If the function is declared and used in the same script, the function declaration may appear after using the function.

y=sqr(3);

function sqr(x) {
  return x*x;
}

Usage 2: The following function defines a Circle object:

function Circle(radius) {
 this.radius = radius;
}

The following statement defines an anonymous function that calculates the area of a circle and attaches it to the object Circle as a method:

Circle.prototype.area = function () {return Math.PI * this.radius * this.radius}


Function class

Availability

Flash Player 6.

Method summary for the Function class

Method | Description
Function.apply() | Enables ActionScript code to call a function.
Function.call() | Invokes the function represented by a Function object.

Property summary for the Function class

Property | Description
Function.prototype | Refers to an object that is the prototype for a class.


Function.apply()

Availability

Flash Player 6.

Usage

myFunction.apply(thisObject, argumentsObject)

Parameters

thisObject The object that myFunction is applied to.

argumentsObject An array whose elements are passed to myFunction as parameters.

Returns

Any value that the called function specifies.

Description

Method; specifies the value of this to be used within any function that ActionScript calls. This method also specifies the parameters to be passed to any called function. Because apply() is a method of the Function class, it is also a method of every function object in ActionScript.

The parameters are specified as an Array object. This is often useful when the number of parameters to be passed is not known until the script actually executes.

Example

The following function invocations are equivalent:

Math.atan2(1, 0)
Math.atan2.apply(null, [1, 0])

You could construct a SWF file that contains input entry fields that permit the user to enter the name of a function to invoke, and zero or more parameters to pass to the function. Pressing a "Call" button would then use the apply method to call the function, specifying the parameters.

In this example, the user specifies a function name in an input text field called functionName. The number of parameters is specified in an input text field called numParameters. Up to 10 parameters are specified in text fields called parameter1, parameter2, up to parameter10.

on (release) {
  callTheFunction();
}
...
function callTheFunction()
{
   var theFunction = eval(functionName.text);
   var n = Number(numParameters);
   var parameters = [];
   for (var i = 0; i < n; i++) {
      parameters.push(eval("parameter" + i));
   }
   theFunction.apply(null, parameters);
}


Function.call()

Availability

Flash Player 6.

Usage

myFunction.call(thisObject, parameter1, ..., parameterN)

Parameters

thisObject Specifies the value of this within the function body.

parameter1 A parameter to be passed to the myFunction. You can specify zero or more parameters.

parameterN

Returns

Nothing.

Description

Method; invokes the function represented by a Function object. Every function in ActionScript is represented by a Function object, so all functions support this method.

In almost all cases, the function call operator (()) can be used instead of this method. The function call operator produces code that is concise and readable. This method is primarily useful when the this parameter of the function invocation needs to be explicitly controlled. Normally, if a function is invoked as a method of an object, within the body of the function, this is set to myObject as in the following:

myObject.myMethod(1, 2, 3);

In some situations, you may want this to point somewhere else; for example, if a function must be invoked as a method of an object, but is not actually stored as a method of that object.

myObject.myMethod.call(myOtherObject, 1, 2, 3);

You can pass the value null for the thisObject parameter to invoke a function as a regular function and not as a method of an object. For example, the following function invocations are equivalent:

Math.sin(Math.PI / 4)
Math.sin.call(null, Math.PI / 4)

Example

This example uses Function.call() to make a function behave as a method of another object, without storing the function in the object.

function MyObject() {
}
function MyMethod(obj) {
  trace("this == obj? " + (this == obj));
}
var obj = new MyObject();
MyMethod.call(obj, obj);

The trace() action sends the following code to the Output panel:

this == obj? true


Function.prototype

Availability

Flash Player 5. If you are using ActionScript 2.0, you don't need to use this property; it reflects the implementation of inheritance in ActionScript 1.

Usage

myFunction.prototype

Description

Property; in an ActionScript 1 constructor function, the prototype property refers to an object that is the prototype of the constructed class. Each instance of the class that is created by the constructor function inherits all the properties and methods of the prototype object.


ge (greater than or equal to — string specific)

Availability

Flash Player 4. This operator was deprecated in Flash 5 in favor of the >= (greater than or equal to) operator.

Usage

expression1 ge expression2

Parameters

expression1, expression2 Numbers, strings, or variables.

Returns

Nothing.

Description

Operator (comparison); compares the string representation of expression1 to the string representation of expression2 and returns true if expression1 is greater than or equal to expression2; otherwise, returns false.

See also

>= (greater than or equal to)


get

Availability

Flash Player 6.

Usage

function get property() {
  // your statements here
}

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Parameters

property The word you want to use to refer to the property that get accesses; this value must be the same as the value used in the corresponding set command.

Returns

The value of the property specified by propertyName.

Description

Keyword; permits implicit "getting" of properties associated with objects based on classes you have defined in external class files. Using implicit get methods lets you access properties of objects without accessing them directly. Implicit get/set methods are syntactic shorthand for the Object.addProperty() method in ActionScript 1.

For more information, see Implicit get/set methods.

See also

Object.addProperty(), set


getProperty

Availability

Flash Player 4.

Usage

getProperty(my_mc, property)

Parameters

my_mc The instance name of a movie clip for which the property is being retrieved.

property A property of a movie clip.

Returns

The value of the specified property.

Description

Function; returns the value of the specified property for the movie clip my_mc.

Example

The following example retrieves the horizontal axis coordinate (_x) for the movie clip my_mc and assigns it to the variable my_mc_x:

my_mc_x = getProperty(_root.my_mc, _x);


getTimer

Availability

Flash Player 4.

Usage

getTimer()

Parameters

None.

Returns

The number of milliseconds that have elapsed since the SWF file started playing.

Description

Function; returns the number of milliseconds that have elapsed since the SWF file started playing.


getURL()

Availability

Flash 2. The GET and POST options are only available to Flash Player 4 and later versions of the player.

Usage

getURL(url [, window [, "variables"]])

Parameters

url The URL from which to obtain the document.

window An optional parameter specifying the window or HTML frame that the document should load into. You can enter the name of a specific window or choose from the following reserved target names:

  • _self specifies the current frame in the current window.
  • _blank specifies a new window.
  • _parent specifies the parent of the current frame.
  • _top specifies the top-level frame in the current window.

variables A GET or POST method for sending variables. If there are no variables, omit this parameter. The GET method appends the variables to the end of the URL, and is used for small numbers of variables. The POST method sends the variables in a separate HTTP header and is used for sending long strings of variables.

Returns

Nothing.

Description

Function; loads a document from a specific URL into a window or passes variables to another application at a defined URL. To test this action, make sure the file to be loaded is at the specified location. To use an absolute URL (for example, http://www.myserver.com), you need a network connection.

Example

This example loads a new URL into a blank browser window. The getURL() action targets the variable incomingAd as the url parameter so that you can change the loaded URL without having to edit the SWF file. The incomingAd variable's value is passed into Flash earlier in the SWF file using a loadVariables() action.

on(release) {
  getURL(incomingAd, "_blank");
}

See also

loadVariables(), XML.send(), XML.sendAndLoad(), XMLSocket.send()


getVersion

Availability

Flash Player 5.

Usage

getVersion()

Parameters

None.

Returns

A string containing Flash Player version and platform information.

Description

Function; returns a string containing Flash Player version and platform information.

The getVersion function only returns information for Flash Player 5 or later versions of the Player.

Example

The following is an example of a string returned by the getVersion function.

WIN 5,0,17,0

This indicates that the platform is Microsoft Windows, and the version number of Flash Player is major version 5, minor version 17 (5.0r17).

See also

System.capabilities.os, System.capabilities.version


_global object

Availability

Flash Player 6.

Usage

_global.identifier

Parameters

None.

Returns

A reference to the global object that holds the core ActionScript classes, such as String, Object, Math, and Array.

Description

Identifier; creates global variables, objects, or classes. For example, you could create a library that is exposed as a global ActionScript object, much like the Math or Date object. Unlike Timeline-declared or locally declared variables and functions, global variables and functions are visible to every Timeline and scope in the SWF file, provided they are not obscured by identifiers with the same names in inner scopes.

Example

The following example creates a top-level function factorial() that is available to every Timeline and scope in a SWF file:

_global.factorial = function (n) {
  if (n <= 1) {
    return 1;
  } else {
    return n * factorial(n-1);
  }
}

See also

var, set variable


gotoAndPlay()

Availability

Flash 2.

Usage

gotoAndPlay([scene,] frame)

Parameters

scene An optional string specifying the name of the scene to which the playhead is sent.

frame A number representing the frame number, or a string representing the label of the frame, to which the playhead is sent.

Returns

Nothing.

Description

Function; sends the playhead to the specified frame in a scene and plays from that frame. If no scene is specified, the playhead goes to the specified frame in the current scene.

You can use the scene parameter only on the root Timeline, not within Timelines for movie clips or other objects in the document.

Example

When the user clicks a button to which gotoAndPlay() is assigned, the playhead is sent to Frame 16 in the current scene and starts to play.

on(release) {
  gotoAndPlay(16);
}

See also

MovieClip.gotoAndPlay(), play()


gotoAndStop()

Availability

Flash 2.

Usage

gotoAndStop([scene,] frame)

Parameters

scene An optional string specifying the name of the scene to which the playhead is sent.

frame A number representing the frame number, or a string representing the label of the frame, to which the playhead is sent.

Returns

Nothing.

Description

Function; sends the playhead to the specified frame in a scene and stops it. If no scene is specified, the playhead is sent to the frame in the current scene.

You can use the scene parameter only on the root Timeline, not within Timelines for movie clips or other objects in the document.

Example

When the user clicks a button that gotoAndStop() is assigned to, the playhead is sent to Frame 5 in the current scene and the SWF file stops playing.

on(release) {
  gotoAndStop(5);
}

See also

MovieClip.gotoAndStop(), stop()


gt (greater than — string specific)

Availability

Flash Player 4. This operator was deprecated in Flash 5 in favor of the new > (greater than) operator.

Usage

expression1 gt expression2

Parameters

expression1, expression2 Numbers, strings, or variables.

Description

Operator (comparison); compares the string representation of expression1 to the string representation of expression2 and returns true if expression1 is greater than expression2; otherwise, returns false.

See also

> (greater than)


_highquality

Availability

Flash Player 4; deprecated in favor of _quality.

Usage

_highquality

Description

Deprecated property (global); specifies the level of anti-aliasing applied to the current SWF file. Specify 2 (best quality) to apply high quality with bitmap smoothing always on. Specify 1 (high quality) to apply anti-aliasing; this will smooth bitmaps if the SWF file does not contain animation. Specify 0 (low quality) to prevent anti-aliasing.

Example

_highquality = 1;

See also

_quality, toggleHighQuality()


if

Availability

Flash Player 4.

Usage

if(condition) {
  statement(s);
}

Parameters

condition An expression that evaluates to true or false.

statement(s) The instructions to execute if or when the condition evaluates to true.

Returns

Nothing.

Description

Statement; evaluates a condition to determine the next action in a SWF file. If the condition is true, Flash runs the statements that follow the condition inside curly braces ({}). If the condition is false, Flash skips the statements inside the curly braces and runs the statements following the curly braces. Use the if action to create branching logic in your scripts.

Example

In the following example, the condition inside the parentheses evaluates the variable name to see if it has the literal value "Erica". If it does, the play() action inside the curly braces runs.

if(name == "Erica"){
  play();
}

The following example uses an if action to evaluate when a draggable object in the SWF file is released by the user. If the object was released less than 300 milliseconds after dragging it, the condition evaluates to true and the statements inside the curly braces run. Those statements set variables to store the new location of the object, how hard it was thrown, and the speed at which it was thrown. The timePressed variable is also reset. If the object was released more than 300 milliseconds after it was dragged, the condition evaluates to false and none of the statements run.

if (getTimer()<timePressed+300) {
    // if the condition is true,
    // the object was thrown.
    // what is the new location of this object?
    xNewLoc = this._x;
    yNewLoc = this._y;
    // how hard did they throw it?
    xTravel = xNewLoc-xLoc;
    yTravel = yNewLoc-yLoc;
    // setting the speed of the object depending on
    // how far they travelled with it
    xInc = xTravel/2;
    yInc = yTravel/2;
    timePressed = 0;
  }

See also

else


ifFrameLoaded

Availability

Flash Player 3. The ifFrameLoaded action was deprecated in Flash 5; Macromedia recommends using the MovieClip._framesloaded property.

Usage

ifFrameLoaded([scene,] frame) {
  statement(s);
}

Parameters

scene An optional string specifying the name of the scene that must be loaded.

frame The frame number or frame label that must be loaded before the next statement is executed.

statement(s) The instructions to execute if the specified scene, or scene and frame, are loaded.

Returns

Nothing.

Description

Deprecated action; checks whether the contents of a specific frame are available locally. Use ifFrameLoaded to start playing a simple animation while the rest of the SWF file downloads to the local computer. The difference between using _framesloaded and ifFrameLoaded is that _framesloaded allows you to add your own if or else statements.

See also

MovieClip._framesloaded


implements

Availability

Flash Player 6.

Usage

myClass implements interface01 [, interface02, ...]

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Description

Keyword; defines a class that must supply implementations for all the methods defined in the interface (or interfaces) being implemented. For more information, see Interfaces as data types.

Example

See interface.

See also

class, extends, interface


import

Availability

Flash Player 6.

Usage

import className
import packageName.*

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This statement is supported in the Actions panel as well as in external class files.

Parameters

className The fully qualified name of a class you have defined in an external class file.

packageName A directory in which you have stored related class files.

Description

Keyword; lets you access classes without specifying their fully qualified names. For example, if you want to use the class macr.util.users.UserClass.as in a script, you must either refer to it by its fully qualified name or import it; if you import it, you can then refer to it by the class name:

// before importing
var myUser:UserClass = new macr.util.users.UserClass();
// after importing
import macr.util.users.UserClass;
var myUser:UserClass = new UserClass();

If there are several class files in the directory that you want to access, you can import them all in a single statement:

import macr.util.users.*;

You must issue the import statement before you try to access the imported class without fully specifying its name.

If you import a class but then don't use it in your script, the class isn't exported as part of the SWF file. This means you can import large packages without worrying about the size of your SWF file; the bytecode associated with a class is included in a SWF file only if that class is actually used.

The import statement applies only to the current script (frame or object) in which it's called. For example, suppose on Frame 1 of a Flash document you import all the classes in the macr.util package. On that frame, you can reference classes in that package by their simple names.

// On Frame 1 of a FLA:
import macr.util.*;

var myFoo:foo = new foo();

On another frame script, however, you would need to reference classes in that package by their fully qualified names (var myFoo:foo = new macr.util.foo();) or add an import statement to the other frame, as well, that imports the classes in that package.

For more information on importing, see Importing classes and Using packages.


#include

Availability

Flash Player 4.

Usage

#include "[path] filename.as"

Note: Do not place a semicolon (;) at the end of the line that contains the #include statement.

Parameters

[path] filename.as The filename and optional path for the script to add to the Actions panel; .as is the recommended file extension.

Returns

Nothing.

Description

Compiler directive: includes the contents of the specified file, as if the commands in the file were part of the calling script itself. The #include directive is invoked at compile time. Therefore, if you make any changes to an external file, you must save the file and recompile any FLA files that use it.

If you use the Check Syntax button for a script that contains #include statements, the syntax of the included files is also checked.

You can use #include in FLA files and in external script files, but not in ActionScript 2.0 class files.

You can specify no path, a relative path, or an absolute path for the file to be included.

If you don't specify a path, the AS file must be in one of the following locations:

  • The same directory as the FLA file.
  • The same directory as the script containing the #include statement.
  • The global Include directory, which is one of the following:
    • Windows 2000 or Windows XP: C:\Documents and Settings\user\Local Settings\ Application Data\Macromedia\Flash MX 2004\language\Configuration\Include
    • Windows 98: C:\Windows\Application Data\Macromedia\Flash MX 2004\ language\Configuration\Include
    • Macintosh OS X: Hard Drive/Users/Library/Application Support/Macromedia/Flash MX 2004/language/Configuration/Include
  • The Flash MX 2004 program\language\First Run\Include directory; if you save a file here, it is copied to the global Include directory the next time you launch Flash.

To specify a relative path for the AS file, use a single dot (.) to indicate the current directory, two dots (..) to indicate a parent directory, and forward slashes (/) to indicate subdirectories. See the following examples.

To specify an absolute path for the AS file, use the format supported by your platform (Macintosh or Windows). See the following examples. However, this usage is not recommended, because it requires that the directory structure be the same on any machine you use to compile the script.

Note: If you place files in the First Run/Include directory or in the global Include directory, back up these files. If you ever need to uninstall and reinstall Flash, these directories might be deleted and overwritten.

Example

The following examples show various ways of specifying a path for a file to be included in your script.

// Note that #include statements do not end with a semicolon (;)
// AS file is in same directory as FLA file or script
// or is in the global Include directory or the First Run/Include directory
#include "init_script.as"

// AS file is in a subdirectory of one of the above directories
// The subdirectory is named "FLA_includes"
#include "FLA_includes/init_script.as"

// AS file is in a directory at the same level as one of the above directories
// The directory is named "ALL_includes"
#include "../ALL_includes/init_script.as"

// AS file is specified by an absolute path in Windows
// Note use of forward slashes, not backslashes
#include "C:/Flash_scripts/init_script.as"

// AS file is specified by an absolute path on Macintosh
#include "Mac HD:Flash_scripts:init_script.as"

See also

import


Infinity

Availability

Flash Player 5.

Usage

Infinity

Description

Constant; specifies the IEEE-754 value representing positive infinity. The value of this constant is the same as Number.POSITIVE_INFINITY.


-Infinity

Availability

Flash Player 5.

Usage

-Infinity

Description

Constant; specifies the IEEE-754 value representing negative infinity. The value of this constant is the same as Number.NEGATIVE_INFINITY.


#initclip

Availability

Flash Player 6.

Usage

#initclip order

Parameters

order An integer that specifies the execution order of blocks of #initclip code. This is an optional parameter.

Description

Compiler directive; indicates the beginning of a block of initialization actions. When multiple clips are initialized at the same time, you can use the order parameter to specify which initialization occurs first. Initialization actions execute when a movie clip symbol is defined. If the movie clip is an exported symbol, the initialization actions execute before the actions on Frame 1 of the SWF file. Otherwise, they execute immediately before the frame actions of the frame that contains the first instance of the associated movie clip symbol.

Initialization actions execute only once during the playback of a SWF file; use them for one-time initializations, such as class definition and registration.

See also

#endinitclip


instanceof

Availability

Flash Player 6.

Usage

object instanceof class

Parameters

object An ActionScript object.

class A reference to an ActionScript constructor function, such as String or Date.

Returns

If object is an instance of class, instanceof returns true; otherwise, instanceof returns false. Also, _global instanceof Object returns false.

Description

Operator; determines whether an object belongs to a specified class. Tests whether object is an instance of class.

The instanceof operator does not convert primitive types to wrapper objects. For example, the following code returns true:

new String("Hello") instanceof String;

Whereas the following code returns false:

"Hello" instanceof String;

See also

typeof


int

Availability

Flash Player 4. This function was deprecated in Flash 5 in favor of Math.round().

Usage

int(value)

Parameters

value A number to be rounded to an integer.

Returns

Nothing.

Description

Function; converts a decimal number to the closest integer value.

See also

Math.floor()


interface

Availability

Flash Player 6.

Usage

interface InterfaceName [extends InterfaceName ] {}

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Description

Keyword; defines an interface. An interface is similar to a class, with the following important differences:

  • Interfaces contain only declarations of methods, not their implementation. That is, every class that implements an interface must provide an implementation for each method declared in the interface.
  • Only public members are allowed in an interface definition. In addition, instance and class members are not permitted.
  • The get and set statements are not allowed in interface definitions.

For more information, see Creating and using interfaces.

Example

The following example shows several ways to define and implement interfaces.

(in top-level package .as files Ia, B, C, Ib, D, Ic, E)

// filename Ia.as
interface Ia
{
  function k():Number;         // method declaration only
  function n(x:Number):Number; // without implementation
}
// filename B.as
class B implements Ia
{
  function k():Number {return 25;}
  function n(x:Number):Number {return x+5;}
}
// external script or Actions panel
var mvar:B = new B();
trace(mvar.k());   // 25
trace(mvar.n(7)); // 12

// filename c.as
class C implements Ia
{
  function k():Number {return 25;}
} // error: class must implement all interface methods

// filename Ib.as
interface Ib
{
  function o():Void;
}
class D implements Ia, Ib
{
  function k():Number {return 15;}
  function n(x:Number):Number {return x*x;}
  function o():Void {trace("o");}
}

// external script or Actions panel
mvar = new D();
trace(mvar.k());   // 15
trace(mvar.n(7));  // 49
trace(mvar.o());   // "o"

interface Ic extends Ia
{
  function p():Void;
}
class E implements Ib, Ic
{
  function k():Number {return 25;}
  function n(x:Number):Number {return x+5;}
  function o():Void {trace("o");}
  function p():Void {trace("p");}
}

See also

class, extends, implements


isFinite

Availability

Flash Player 5.

Usage

isFinite(expression)

Parameters

expression A Boolean value, variable, or other expression to be evaluated.

Returns

A Boolean value.

Description

Function; evaluates expression and returns true if it is a finite number or false if it is infinity or negative infinity. The presence of infinity or negative infinity indicates a mathematical error condition such as division by 0.

Example

The following are examples of return values for isFinite:

isFinite(56)
// returns true

isFinite(Number.POSITIVE_INFINITY)
// returns false


isNaN()

Availability

Flash Player 5.

Usage

isNaN(expression)

Parameters

expression A Boolean, variable, or other expression to be evaluated.

Returns

A Boolean value.

Description

Function; evaluates the parameter and returns true if the value is not a number (NaN), indicating the presence of mathematical errors.

Example

The following code illustrates return values for the isNaN function.

isNaN("Tree")

// returns true

isNaN(56)

// returns false

isNaN(Number.POSITIVE_INFINITY)
// returns false

See also

NaN, Number.NaN


Key class

Availability

Flash Player 6.

Description

The Key class is a top-level class whose methods and properties you can use without using a constructor. Use the methods of the Key class to build an interface that can be controlled by a user with a standard keyboard. The properties of the Key class are constants representing the keys most commonly used to control games. For a complete list of key code values, see Keyboard Keys and Key Code Values.

Method summary for the Key class

Method | Description
Key.addListener() | Registers an object to receive notification when the onKeyDown and onKeyUp methods are invoked.
Key.getAscii() | Returns the ASCII value of the last key pressed.
Key.getCode() | Returns the virtual key code of the last key pressed.
Key.isDown() | Returns true if the key specified in the parameter is pressed.
Key.isToggled() | Returns true if the Num Lock or Caps Lock key is activated.
Key.removeListener() | Removes an object that was previously registered with Key.addListener().

Property summary for the Key class

All of the properties for the Key class are constants.

Property | Description
Key.BACKSPACE | Constant associated with the key code value for the Backspace key (8).
Key.CAPSLOCK | Constant associated with the key code value for the Caps Lock key (20).
Key.CONTROL | Constant associated with the key code value for the Control key (17).
Key.DELETEKEY | Constant associated with the key code value for the Delete key (46).
Key.DOWN | Constant associated with the key code value for the Down Arrow key (40).
Key.END | Constant associated with the key code value for the End key (35).
Key.ENTER | Constant associated with the key code value for the Enter key (13).
Key.ESCAPE | Constant associated with the key code value for the Escape key (27).
Key.HOME | Constant associated with the key code value for the Home key (36).
Key.INSERT | Constant associated with the key code value for the Insert key (45).
Key.LEFT | Constant associated with the key code value for the Left Arrow key (37).
Key.PGDN | Constant associated with the key code value for the Page Down key (34).
Key.PGUP | Constant associated with the key code value for the Page Up key (33).
Key.RIGHT | Constant associated with the key code value for the Right Arrow key (39).
Key.SHIFT | Constant associated with the key code value for the Shift key (16).
Key.SPACE | Constant associated with the key code value for the Spacebar (32).
Key.TAB | Constant associated with the key code value for the Tab key (9).
Key.UP | Constant associated with the key code value for the Up Arrow key (38).

Listener summary for the Key class

Method | Description
Key.onKeyDown | Notified when a key is pressed.
Key.onKeyUp | Notified when a key is released.


Key.addListener()

Availability

Flash Player 6.

Usage

Key.addListener (newListener)

Parameters

newListener An object with methods onKeyDown and onKeyUp.

Returns

Nothing.

Description

Method; registers an object to receive onKeyDown and onKeyUp notification. When a key is pressed or released, regardless of the input focus, all listening objects registered with addListener() have either their onKeyDown method or onKeyUp method invoked. Multiple objects can listen for keyboard notifications. If the listener newListener is already registered, no change occurs.

Example

The following example creates a new listener object and defines a function for onKeyDown and onKeyUp. The last line uses addListener() to register the listener with the Key object so that it can receive notification from the key down and key up events.

myListener = new Object();
myListener.onKeyDown = function () {
  trace ("You pressed a key.");
}
myListener.onKeyUp = function () {
  trace ("You released a key.");
}
Key.addListener(myListener);

The following example assigns the keyboard shortcut Control+7 to a button with an instance name of myButton, and makes information about the shortcut available to screen readers (see _accProps). In this example, when you press Control+7 the myOnPress function displays the text "hello" in the Output panel; in your file, you would create a function that does something more meaningful.

function myOnPress() {
  trace( "hello" );
}

function myOnKeyDown() {
  if (Key.isDown(Key.CONTROL) && Key.getCode() == 55) // 55 is key code for 7
  {
    Selection.setFocus( myButton );
    myButton.onPress();
  }
}

var myListener = new Object();
myListener.onKeyDown = myOnKeyDown;
Key.addListener( myListener );

myButton.onPress = myOnPress;
myButton._accProps.shortcut = "Ctrl+F"
Accessibility.updateProperties();

See also

Key.getCode(), Key.isDown(), Key.onKeyDown, Key.onKeyUp, Key.removeListener()


Key.BACKSPACE

Availability

Flash Player 5.

Usage

Key.BACKSPACE

Description

Property; constant associated with the key code value for the Backspace key (8).


Key.CAPSLOCK

Availability

Flash Player 5.

Usage

Key.CAPSLOCK

Description

Property; constant associated with the key code value for the Caps Lock key (20).


Key.CONTROL

Availability

Flash Player 5.

Usage

Key.CONTROL

Description

Property; constant associated with the key code value for the Control key (17).


Key.DELETEKEY

Availability

Flash Player 5.

Usage

Key.DELETEKEY

Description

Property; constant associated with the key code value for the Delete key (46).


Key.DOWN

Availability

Flash Player 5.

Usage

Key.DOWN

Description

Property; constant associated with the key code value for the Down Arrow key (40).


Key.END

Availability

Flash Player 5.

Usage

Key.END

Description

Property; constant associated with the key code value for the End key (35).


Key.ENTER

Availability

Flash Player 5.

Usage

Key.ENTER

Description

Property; constant associated with the key code value for the Enter key (13).


Key.ESCAPE

Availability

Flash Player 5.

Usage

Key.ESCAPE

Description

Property; constant associated with the key code value for the Escape key (27).


Key.getAscii()

Availability

Flash Player 5.

Usage

Key.getAscii();

Parameters

None.

Returns

An integer that represents the ASCII value of the last key pressed.

Description

Method; returns the ASCII code of the last key pressed or released. The ASCII values returned are English keyboard values. For example, if you press Shift+2, Key.getAscii() returns @ on a Japanese keyboard, just as it does on an English keyboard.


Key.getCode()

Availability

Flash Player 5.

Usage

Key.getCode();

Parameters

None.

Returns

An integer that represents the key code of the last key pressed.

Description

Method; returns the key code value of the last key pressed. To match the returned key code value with the key on a standard keyboard, see Keyboard Keys and Key Code Values.


Key.HOME

Availability

Flash Player 5.

Usage

Key.HOME

Description

Property; constant associated with the key code value for the Home key (36).


Key.INSERT

Availability

Flash Player 5.

Usage

Key.INSERT

Description

Property; constant associated with the key code value for the Insert key (45).


Key.isDown()

Availability

Flash Player 5.

Usage

Key.isDown(keycode)

Parameters

keycode The key code value assigned to a specific key, or a Key class property associated with a specific key. To match the returned key code value with the key on a standard keyboard, see Keyboard Keys and Key Code Values.

Returns

A Boolean value.

Description

Method; returns true if the key specified in keycode is pressed, false if it is not. On the Macintosh, the key code values for the Caps Lock and Num Lock keys are identical.

Example

The following script lets the user control a movie clip's location.

onClipEvent (enterFrame) {
  if(Key.isDown(Key.RIGHT)) {
    this._x=_x+10;
  } else if (Key.isDown(Key.DOWN)) {
    this._y=_y+10;
  }
}


Key.isToggled()

Availability

Flash Player 5.

Usage

Key.isToggled(keycode)

Parameters

keycode The key code for Caps Lock (20) or Num Lock (144).

Returns

A Boolean value.

Description

Method; returns true if the Caps Lock or Num Lock key is activated (toggled), false if it is not. On the Macintosh, the key code values for the Caps Lock and Num Lock keys are identical.


Key.LEFT

Availability

Flash Player 5.

Usage

Key.LEFT

Description

Property; constant associated with the key code value for the Left Arrow key (37).


Key.onKeyDown

Availability

Flash Player 6.

Usage

someListener.onKeyDown

Description

Listener; notified when a key is pressed. To use onKeyDown you must create a listener object. You can then define a function for onKeyDown and use addListener() to register the listener with the Key object, as in the following:

someListener = new Object();
someListener.onKeyDown = function () { ... };
Key.addListener(someListener);

Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event.

See also

Key.addListener()


Key.onKeyUp

Availability

Flash Player 6.

Usage

someListener.onKeyUp

Description

Listener; notified when a key is released. To use onKeyUp you must create a listener object. You can then define a function for onKeyUp and use addListener() to register the listener with the Key object, as in the following:

someListener = new Object();
someListener.onKeyUp = function () { ... };
Key.addListener(someListener);

Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event.

See also

Key.addListener()


Key.PGDN

Availability

Flash Player 5.

Usage

Key.PGDN

Description

Property; constant associated with the key code value for the Page Down key (34).


Key.PGUP

Availability

Flash Player 5.

Usage

Key.PGUP

Description

Property; constant associated with the key code value for the Page Up key (33).


Key.removeListener()

Availability

Flash Player 6.

Usage

Key.removeListener (listener)

Parameters

listener An object.

Returns

If the listener was successfully removed, the method returns true. If the listener was not successfully removed, for example if the listener was not on the Key object's listener list, the method returns false.

Description

Method; removes an object previously registered with Key.addListener().


Key.RIGHT

Availability

Flash Player 5.

Usage

Key.RIGHT

Description

Property; constant associated with the key code value for the Right Arrow key (39).


Key.SHIFT

Availability

Flash Player 5.

Usage

Key.SHIFT

Description

Property; constant associated with the key code value for the Shift key (16).


Key.SPACE

Availability

Flash Player 5.

Usage

Key.SPACE

Description

Property; constant associated with the key code value for the Spacebar (32).


Key.TAB

Availability

Flash Player 5.

Usage

Key.TAB

Description

Property; constant associated with the key code value for the Tab key (9).


Key.UP

Availability

Flash Player 5.

Usage

Key.UP

Description

Property; constant associated with the key code value for the Up Arrow key (38).


le (less than or equal to — string specific)

Availability

Flash Player 4. This operator was deprecated in Flash 5 in favor of the <= (less than or equal to) operator.

Usage

expression1 le expression2

Parameters

expression1,expression2 Numbers, strings, or variables.

Returns

Nothing.

Description

Operator (comparison); compares expression1 to expression2 and returns a value of true if expression1 is less than or equal to expression2; otherwise, it returns a false value.

See also

<= (less than or equal to)


length

Availability

Flash Player 4. This function, along with all of the string functions, was deprecated in Flash 5. Macromedia recommends using the methods of the String class and the String.length property to perform the same operations.

Usage

length(expression)
length(variable)

Parameters

expression A string.

variable The name of a variable.

Returns

The length of the specified string or variable name.

Description

String function; returns the length of the specified string or variable name.

Example

The following example returns the value of the string "Hello".

length("Hello");

The result is 5.

See also

" " (string delimiter), String class, String.length


_level

Availability

Flash Player 4.

Usage

_levelN

Description

Identifier; a reference to the root Timeline of _levelN. You must use loadMovieNum() to load SWF files into the Flash Player before you use the _level property to target them. You can also use _levelN to target a loaded SWF file at the level assigned by N.

The initial SWF file loaded into an instance of the Flash Player is automatically loaded into _level0. The SWF file in _level0 sets the frame rate, background color, and frame size for all subsequently loaded SWF files. SWF files are then stacked in higher-numbered levels above the SWF file in _level0.

You must assign a level to each SWF file that you load into the Flash Player using loadMovieNum(). You can assign levels in any order. If you assign a level that already contains a SWF file (including _level0), the SWF file at that level is unloaded and replaced by the new SWF file.

Example

The following example stops the playhead in the main Timeline of the SWF file in _level9.

_level9.stop();

The following example sends the playhead in the main Timeline of the SWF file in _level4 to Frame 5. The SWF file in _level4 must have previously been loaded with a loadMovieNum() action.

_level4.gotoAndStop(5);

See also

loadMovie(), MovieClip.swapDepths()


loadMovie()

Availability

Flash Player 3.

Usage

loadMovie("url",target [, method])

Parameters

url The absolute or relative URL of the SWF file or JPEG file to be loaded. A relative path must be relative to the SWF file at level 0. Absolute URLs must include the protocol reference, such as http:// or file:///.

target A path to a target movie clip. The target movie clip will be replaced by the loaded SWF file or image.

method An optional parameter specifying an HTTP method for sending variables. The parameter must be the string GET or POST. If there are no variables to be sent, omit this parameter. The GET method appends the variables to the end of the URL, and is used for small numbers of variables. The POST method sends the variables in a separate HTTP header and is used for long strings of variables.

Returns

Nothing.

Description

Function; loads a SWF or JPEG file into Flash Player while the original SWF file is playing.

Tip: If you want to monitor the progress of the download, use MovieClipLoader.loadClip() instead of this function.

The loadMovie() function lets you display several SWF files at once and switch between SWF files without loading another HTML document. Without the loadMovie() function, Flash Player displays a single SWF file and then closes.

If you want to load a SWF or JPEG file into a specific level, use loadMovieNum() instead of loadMovie().

When a SWF file is loaded into a target movie clip, you can use the target path of that movie clip to target the loaded SWF file. A SWF file or image loaded into a target inherits the position, rotation, and scale properties of the targeted movie clip. The upper left corner of the loaded image or SWF file aligns with the registration point of the targeted movie clip. Alternatively, if the target is the root Timeline, the upper left corner of the image or SWF file aligns with the upper left corner of the Stage.

Use unloadMovie() to remove SWF files that were loaded with loadMovie().

Example

The following loadMovie() statement is attached to a navigation button labeled Products. There is an invisible movie clip on the Stage with the instance name dropZone. The loadMovie() function uses this movie clip as the target parameter to load the products in the SWF file into the correct position on the Stage.

on(release) {
  loadMovie("products.swf",_root.dropZone);
}

The following example loads a JPEG image from the same directory as the SWF file that calls the loadMovie() function:

loadMovie("image45.jpeg", "ourMovieClip");

See also

_level, loadMovieNum(), MovieClipLoader.loadClip(), unloadMovie()


loadMovieNum()

Availability

Flash Player 4. Flash 4 files opened in Flash 5 or later are converted to use the correct syntax.

Usage

loadMovieNum("url",level [, variables])

Parameters

url The absolute or relative URL of the SWF or JPEG file to be loaded. A relative path must be relative to the SWF file at level 0. For use in the stand-alone Flash Player or for testing in test-movie mode in the Flash authoring application, all SWF files must be stored in the same folder; and the filenames cannot include folder or disk drive specifications.

level An integer specifying the level in Flash Player into which the SWF file will be loaded.

variables An optional parameter specifying an HTTP method for sending variables. The parameter must be the string GET or POST. If there are no variables to be sent, omit this parameter. The GET method appends the variables to the end of the URL and is used for small numbers of variables. The POST method sends the variables in a separate HTTP header and is used for long strings of variables.

Returns

Nothing.

Description

Function; loads a SWF or JPEG file into a level in Flash Player while the originally loaded SWF file is playing.

Tip: If you want to monitor the progress of the download, use MovieClipLoader.loadClip() instead of this function.

Normally, Flash Player displays a single SWF file and then closes. The loadMovieNum() action lets you display several SWF files at once and switch between SWF files without loading another HTML document.

If you want to specify a target instead of a level, use loadMovie() instead of loadMovieNum().

Flash Player has a stacking order of levels starting with level 0. These levels are like layers of acetate; they are transparent except for the objects on each level. When you use loadMovieNum(), you must specify a level in Flash Player into which the SWF file will load. When a SWF file is loaded into a level, you can use the syntax, _levelN, where N is the level number, to target the SWF file.

When you load a SWF file, you can specify any level number and you can load SWF files into a level that already has a SWF file loaded into it. If you do, the new SWF file will replace the existing SWF file. If you load a SWF file into level 0, every level in Flash Player is unloaded, and level 0 is replaced with the new file. The SWF file in level 0 sets the frame rate, background color, and frame size for all other loaded SWF files.

The loadMovieNum() action also allows you to load JPEG files into a SWF file while it plays. For both images and SWF files, the upper left corner of the image aligns with the upper left corner of the Stage when the file loads. Also in both cases, the loaded file inherits rotation and scaling, and the original content is overwritten.

Use unloadMovieNum() to remove SWF files or images that were loaded with loadMovieNum().

Example

This example loads the JPEG image image45.jpg into level 2 of Flash Player.

loadMovieNum("http://www.blag.com/image45.jpg", 2);

See also

loadMovie(), unloadMovieNum(), _level


loadVariables()

Availability

Flash Player 4; behavior changed in Flash Player 7.

Usage

loadVariables ("url" , target [, variables])

Parameters

url An absolute or relative URL where the variables are located. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see "Description," below.

target The target path to a movie clip that receives the loaded variables.

variables An optional parameter specifying an HTTP method for sending variables. The parameter must be the string GET or POST. If there are no variables to be sent, omit this parameter. The GET method appends the variables to the end of the URL and is used for small numbers of variables. The POST method sends the variables in a separate HTTP header and is used for long strings of variables.

Returns

Nothing.

Description

Function; reads data from an external file, such as a text file or text generated by a CGI script, Active Server Pages (ASP), or PHP, or Perl script, and sets the values for variables in a target movie clip. This action can also be used to update variables in the active SWF file with new values.

The text at the specified URL must be in the standard MIME format application/x-www-form-urlencoded (a standard format used by CGI scripts). Any number of variables can be specified. For example, the following phrase defines several variables:

company=Macromedia&address=600+Townsend&city=San+Francisco&zip=94103

In SWF files running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.com can load variables from a SWF file at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

In SWF files of any version running in Flash Player 7 or later, url must be in exactly the same domain (see Flash Player security features). For example, a SWF file at www.someDomain.com can load variables only from SWF files that are also at www.someDomain.com. If you want to load variables from a different domain, you can place a cross-domain policy file on the server hosting the SWF file that is being accessed. For more information, see About allowing cross-domain data loading.

If you want to load variables into a specific level, use loadVariablesNum() instead of loadVariables().

Example

This example loads information from a text file into text fields into the varTarget movie clip on the main Timeline. The variable names of the text fields must match the variable names in the data.txt file.

on(release) {
  loadVariables("data.txt", "_root.varTarget");
}

See also

loadVariablesNum(), loadMovie(), loadMovieNum(), getURL(), MovieClip.loadMovie(), MovieClip.loadVariables()


loadVariablesNum()

Availability

Flash Player 4. Flash 4 files opened in Flash 5 or later will be converted to use the correct syntax. Behavior changed in Flash Player 7.

Usage

loadVariablesNum ("url" ,level [, variables])

Parameters

url An absolute or relative URL where the variables are located. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see "Description," below.

level An integer specifying the level in Flash Player to receive the variables.

variables An optional parameter specifying an HTTP method for sending variables. The parameter must be the string GET or POST. If there are no variables to be sent, omit this parameter. The GET method appends the variables to the end of the URL, and is used for small numbers of variables. The POST method sends the variables in a separate HTTP header and is used for long strings of variables.

Returns

Nothing.

Description

Function; reads data from an external file, such as a text file or text generated by a CGI script, Active Server Pages (ASP), PHP, or Perl script, and sets the values for variables in a Flash Player level. You can also use this function to update variables in the active SWF file with new values.

The text at the specified URL must be in the standard MIME format a pplication/x-www-form-urlencoded (a standard format used by CGI scripts). Any number of variables can be specified. For example, the following phrase defines several variables:

company=Macromedia&address=600+Townsend&city=San+Francisco&zip=94103

In SWF files running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.com can load variables from a SWF file at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

In SWF files of any version running in Flash Player 7 or later, url must be in exactly the same domain (see Flash Player security features). For example, a SWF file at www.someDomain.com can load variables only from SWF files that are also at www.someDomain.com. If you want to load variables from a different domain, you can place a cross-domain policy file on the server hosting the SWF file that is being accessed. For more information, see About allowing cross-domain data loading.

If you want to load variables into a target MovieClip, use loadVariables() instead of loadVariablesNum().

Example

This example loads information from a text file into text fields in the main Timeline of the SWF at level 0 in Flash Player. The variable names of the text fields must match the variable names in the data.txt file.

on(release) {
  loadVariablesNum("data.txt", 0);
}

See also

getURL(), loadMovie(), loadMovieNum(), loadVariables(), MovieClip.loadMovie(), MovieClip.loadVariables()


LoadVars class

Availability

Flash Player 6.

Description

The LoadVars class is an alternative to the loadVariables() function for transferring variables between a Flash application and a server.

You can use the LoadVars class to obtain verification of successful data loading, progress indications, and stream data while it downloads. The LoadVars class works much like the XML class; it uses the methods load(), send(), and sendAndLoad() to communicate with a server. The main difference between the LoadVars class and the XML class is that LoadVars transfers ActionScript name and value pairs, rather than an XML DOM tree stored in the XML object.

The LoadVars class follows the same security restrictions as the XML class.

Method summary for the LoadVars class

Method | Description
LoadVars.addRequestHeader() | Adds or changes HTTP headers for POST operations.
LoadVars.getBytesLoaded() | Returns the number of bytes downloaded by LoadVars.load() or LoadVars.sendAndLoad().
LoadVars.getBytesTotal() | Returns the total number of bytes that will be downloaded by a load or sendAndLoad method.
LoadVars.load() | Downloads variables from a specified URL.
LoadVars.send() | Posts variables from a LoadVars object to a URL.
LoadVars.sendAndLoad() | Posts variables from a LoadVars object to a URL and downloads the server's response to a target object.
LoadVars.toString() | Returns a URL-encoded string that contains all the enumerable variables in the LoadVars object.

Property summary for the LoadVars class

Property | Description
LoadVars.contentType | Indicates the MIME type of the data.
LoadVars.loaded | A Boolean value that indicates whether a load or sendAndLoad operation has completed.

Event handler summary for the LoadVars class

Event handler | Description
LoadVars.onData | Invoked when data has been completely downloaded from the server, or when an error occurs while data is downloading from a server.
LoadVars.onLoad | Invoked when a load or sendAndLoad operation has completed.

Constructor for the LoadVars class

Availability

Flash Player 6.

Usage

new LoadVars()

Parameters

None.

Returns

A reference to a LoadVars object.

Description

Constructor; creates a LoadVars object. You can then use the methods of that LoadVars object to send and load data.

Example

The following example creates a LoadVars object called my_lv:

var my_lv = new LoadVars();


LoadVars.addRequestHeader()

Availability

Flash Player 6.

Usage

my_lv.addRequestHeader(headerName, headerValue)
my_lv.addRequestHeader(["headerName_1", "headerValue_1" ... "headerName_n", "headerValue_n"])

Parameters

headerName An HTTP request header name.

headerValue The value associated with headerName.

Returns

Nothing.

Description

Method; adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions. In the first usage, you pass two strings to the method: headerName and headerValue. In the second usage, you pass an array of strings, alternating header names and header values.

If multiple calls are made to set the same header name, each successive value will replace the value set in the previous call.

The following standard HTTP headers cannot be added or changed with this method: Accept-Ranges, Age, Allow, Allowed, Connection, Content-Length, Content-Location, Content-Range, ETag, Host, Last-Modified, Locations, Max-Forwards, Proxy-Authenticate, Proxy-Authorization, Public, Range, Retry-After, Server, TE, Trailer, Transfer-Encoding, Upgrade, URI, Vary, Via, Warning, and WWW-Authenticate.

Example

This example adds a custom HTTP header named SOAPAction with a value of Foo to the my_lv object.

my_lv.addRequestHeader("SOAPAction", "'Foo'");

This next example creates an array named headers that contains two alternating HTTP headers and their associated values. The array is passed as an argument to addRequestHeader().

var headers = ["Content-Type", "text/plain", "X-ClientAppVersion", "2.0"];
my_lv.addRequestHeader(headers);

See also

XML.addRequestHeader()


LoadVars.contentType

Availability

Flash Player 6.

Usage

my_lv.contentType

Description

Property; the MIME type that is sent to the server when you call LoadVars.send() or LoadVars.sendAndLoad(). The default is application/x-www-form-urlencoded.

See also

LoadVars.send(), LoadVars.sendAndLoad()


LoadVars.getBytesLoaded()

Availability

Flash Player 6.

Usage

my_lv.getBytesLoaded()

Parameters

None.

Returns

An integer.

Description

Method; returns the number of bytes downloaded by LoadVars.load() or LoadVars.sendAndLoad(). This method returns undefined if no load operation is in progress, or if a load operation has not yet begun.


LoadVars.getBytesTotal()

Availability

Flash Player 6.

Usage

my_lv.getBytesTotal()

Parameters

None.

Returns

An integer.

Description

Method; returns the total number of bytes downloaded by LoadVars.load() or LoadVars.sendAndLoad(). This method returns undefined if no load operation is in progress or if a load operation has not yet begun. This method also returns undefined if the number of total bytes can't be determined; for example, if the download was initiated but the server did not transmit an HTTP content-length.


LoadVars.load()

Availability

Flash Player 6; behavior changed in Flash Player 7.

Usage

my_lv.load(url)

Parameters

url The URL from which to download the variables. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see "Description," below.

Returns

A string.

Description

Method; downloads variables from the specified URL, parses the variable data, and places the resulting variables into my_lv. Any properties in my_lv with the same names as downloaded variables are overwritten. Any properties in my_lv with different names than downloaded variables are not deleted. This is an asynchronous action.

The downloaded data must be in the MIME content type application/x-www-form-urlencoded. This is the same format used by loadVariables().

In SWF files running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.com can load variables from a SWF file at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

In SWF files of any version running in Flash Player 7 or later, url must be in exactly the same domain (see Flash Player security features). For example, a SWF file at www.someDomain.com can load variables only from SWF files that are also at www.someDomain.com. If you want to load variables from a different domain, you can place a cross-domain policy file on the server hosting the SWF file that is being accessed. For more information, see About allowing cross-domain data loading.

Also, in files published for Flash Player 7, case sensitivity (see Case sensitivity) is supported for external variables loaded with LoadVars.load().

This method is similar to XML.load().


LoadVars.loaded

Availability

Flash Player 6.

Usage

my_lv.loaded

Description

Property; undefined by default. When a LoadVars.load() or LoadVars.sendAndLoad() operation is started, the loaded property is set to false; when the operation completes, the loaded property is set to true. If the operation has not yet completed or has failed with an error, the loaded property remains set to false.

This property is similar to the XML.loaded property.


LoadVars.onData

Availability

Flash Player 6.

Usage

my_lv.onData = function(src) {
  // your statements here
}

Parameters

src The raw (unparsed) data from a LoadVars.load() or LoadVars.sendAndLoad() method call.

Returns

Nothing.

Description

Event handler; invoked when data has been completely downloaded from the server, or when an error occurs while data is downloading from a server. This handler is invoked before the data is parsed and therefore can be used to call a custom parsing routine instead of the one built in to Flash Player. The value of the src parameter passed to the function assigned to LoadVars.onData can either be undefined, or a string that contains the URL-encoded name-value pairs downloaded from the server. If the returned value is undefined, an error occurred while downloading the data from the server.

The default implementation of LoadVars.onData invokes LoadVars.onLoad. You can override this default implementation by assigning a custom function to LoadVars.onData, but LoadVars.onLoad will no longer be called unless you call it in your implementation of LoadVars.onData.


LoadVars.onLoad

Availability

Flash Player 6.

Usage

my_lv.onLoad = function(success) {
  // your statements here
}

Parameters

success The parameter indicates whether the load operation ended in success (true) or failure (false).

Returns

A Boolean value.

Description

Event handler; invoked when a LoadVars.load() or LoadVars.sendAndLoad() operation has ended. If the operation was successful, my_lv is populated with variables downloaded by the operation, and these variables are available when this handler is invoked.

This handler is undefined by default.

This method is similar to XML.onLoad().


LoadVars.send()

Availability

Flash Player 6.

Usage

my_lv.send(url [,target, method])

Parameters

url The URL to upload variables to.

target The browser frame window in which any response will be displayed.

method The GET or POST method of the HTTP protocol.

Returns

A string.

Description

Method; sends the variables in the my_lv object to the specified URL. All enumerable variables in my_lv are concatenated into a string in the application/x-www-form-urlencoded format by default, and the string is posted to the URL using the HTTP POST method. This is the same format used by the loadVariables() action. The MIME content type sent in the HTTP request headers is the value of my_lv.contentType, or the default application/x-www-form-urlencoded. The POST method is used unless GET is specified.

If the target parameter is specified, the server's response is displayed in the browser frame window named target. If the target parameter is omitted, the server's response is discarded.

This method is similar to XML.send().


LoadVars.sendAndLoad()

Availability

Flash Player 6; behavior changed in Flash Player 7.

Usage

my_lv.sendAndLoad(url, targetObject[, method])

Parameters

url The URL to upload variables to. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see "Description," below.

targetObject The LoadVars object that receives the downloaded variables.

method The GET or POST method of the HTTP protocol.

Returns

A string.

Description

Method; posts variables in the my_lv object to the specified URL. The server response is downloaded, parsed as variable data, and the resulting variables are placed in the targetObject object.

Variables are posted in the same manner as LoadVars.send(). Variables are downloaded into targetObject in the same manner as LoadVars.load().

In SWF files running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.com can load variables from a SWF file at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

In SWF files of any version running in Flash Player 7 or later, url must be in exactly the same domain (see Flash Player security features). For example, a SWF file at www.someDomain.com can load variables only from SWF files that are also at www.someDomain.com. If you want to load variables from a different domain, you can place a cross-domain policy file on the server hosting the SWF file that is being accessed. For more information, see About allowing cross-domain data loading.

This method is similar to XML.sendAndLoad().


LoadVars.toString()

Availability

Flash Player 6.

Usage

my_lv.toString()

Parameters

None.

Returns

A string.

Description

Method; returns a string containing all enumerable variables in my_lv, in the MIME content encoding application/x-www-form-urlencoded.

Example

var myVars = new LoadVars();
myVars.name = "Gary";
myVars.age = 26;
trace (myVars.toString());
//would output
//name=Gary&age=26


LocalConnection class

Availability

Flash Player 6.

Description

The LocalConnection class lets you develop SWF files that can send instructions to each other without the use of fscommand() or JavaScript. LocalConnection objects can communicate only between SWF files that are running on the same client machine, but they can be running in two different applications—for example, a SWF file running in a browser and a SWF file running in a projector. You can use LocalConnection objects to send and receive data within a single SWF file, but this is not a standard implementation; all the examples in this section illustrate communication between different SWF files.

The primary methods used to send and receive data are LocalConnection.send() and LocalConnection.connect(). At its most basic, your code will implement the following commands; notice that both the LocalConnection.send() and LocalConnection.connect() commands specify the same connection name, lc_name:

// Code in the receiving movie
receiving_lc = new LocalConnection();
receiving_lc.methodToExecute = function(param1, param2)
{
  // Code to be executed
}
receiving_lc.connect("lc_name");
// Code in the sending movie
sending_lc = new LocalConnection();
sending_lc.send("lc_name", "methodToExecute", dataItem1, dataItem2)

The simplest way to use a LocalConnection object is to allow communication only between LocalConnection objects located in the same domain, since you won't have to address issues related to security. However, if you need to allow communication between domains, you have a number of ways to implement security measures. For more information, see the discussion of the connectionName parameter in LocalConnection.send(), and also the LocalConnection.allowDomain and LocalConnection.domain() entries.

Method summary for the LocalConnection class

Method | Description
LocalConnection.close() | Closes (disconnects) the LocalConnection object.
LocalConnection.connect() | Prepares the LocalConnection object to receive commands from a LocalConnection.send() command.
LocalConnection.domain() | Returns a string representing the superdomain of the location of the current SWF file.
LocalConnection.send() | Invokes a method on a specified LocalConnection object.

Event handler summary for the LocalConnection class

Event handler | Description
LocalConnection.allowDomain | Invoked whenever the current (receiving) LocalConnection object receives a request to invoke a method from a sending LocalConnection object.
LocalConnection.allowInsecureDomain | Invoked whenever the current (receiving) LocalConnection object, which is in a SWF file hosted at a domain using a secure protocol (HTTPS), receives a request to invoke a method from a sending LocalConnection object that is in a SWF file that is hosted at a nonsecure protocol.
LocalConnection.onStatus | Invoked after a sending LocalConnection object tries to send a command to a receiving LocalConnection object.

Constructor for the LocalConnection class

Availability

Flash Player 6.

Usage

new LocalConnection()

Parameters

None.

Returns

A reference to a LocalConnection object.

Description

Constructor; creates a LocalConnection object.

Example

The following example shows how receiving and sending SWF files create LocalConnnection objects. Notice that the two SWF files can use the same name or different names for their respective LocalConnection objects. In this example, they use the same name—my_lc.

// Code in the receiving SWF
my_lc = new LocalConnection();
my_lc.someMethod = function() {
  // Your statements here
}
my_lc.connect("connectionName");

// Code in the sending SWF
my_lc = new LocalConnection();
my_lc.send("connectionName", "someMethod");

See also

LocalConnection.connect(), LocalConnection.send()


LocalConnection.allowDomain

Availability

Flash Player 6; behavior changed in Flash Player 7.

Usage

receiving_lc.allowDomain = function([sendingDomain]) {
  // Your statements here return true or false
}

Parameters

sendingDomain An optional parameter specifying the domain of the SWF file containing the sending LocalConnection object.

Returns

Nothing.

Description

Event handler; invoked whenever receiving_lc receives a request to invoke a method from a sending LocalConnection object. Flash expects the code you implement in this handler to return a Boolean value of true or false. If the handler doesn't return true, the request from the sending object is ignored, and the method is not invoked.

Use this command to explicitly permit LocalConnection objects from specified domains, or from any domain, to execute methods of the receiving LocalConnection object. If you don't declare the sendingDomain parameter, you probably want to accept commands from any domain, and the code in your handler would be simply return true. If you do declare sendingDomain, you probably want to compare the value of sendingDomain with domains from which you want to accept commands. The following examples illustrate both of these implementations.

In files running in Flash Player 6, the sendingDomain parameter contains the superdomain of the caller. In files running in Flash Player 7 or later, the sendingDomain parameter contains the exact domain of the caller. In the latter case, to allow access by SWF files hosted at either www.domain.com or store.domain.com, you must explicitly allow access from both domains.

// For Flash Player 6
receiving_lc.allowDomain = function(sendingDomain) {
  return(sendingDomain=="domain.com");
}
// Corresponding commands to allow access by SWF files
// that are running in Flash Player 7 or later
receiving_lc.allowDomain = function(sendingDomain) {
  return(sendingDomain=="www.domain.com" ||
    sendingDomain=="store.domain.com");
}

Also, for files running in Flash Player 7 or later, you can't use this method to allow SWF files hosted using a secure protocol (HTTPS) to permit access from SWF files hosted in nonsecure protocols; you must use the LocalConnection.allowInsecureDomain event handler instead.

Occasionally, you might encounter the following situation. Suppose you load a child SWF file from a different domain. You want to implement this method so that the child SWF can make LocalConnection calls to the parent SWF, but you don't know the final domain from which the child SWF will come. This can happen, for example, when you use load-balancing redirects or third-party servers.

In this situation, you can use the MovieClip._url property in your implementation of this method. For example, if you load a SWF file into my_mc, you can then implement this method by checking whether the domain argument matches the domain of my_mc._url. (You must parse the domain out of the full URL contained in my_mc._url.)

If you do this, be sure to wait until the SWF file in my_mc is loaded, because the _url property will not have its final, correct value until the file is completely loaded. The best way to determine when a child SWF finishes loading is to use MovieClipLoader.onLoadComplete().

The opposite situation can also occur: that is, you might create a child SWF file that wants to accept LocalConnection calls from its parent, but doesn't know what the domain of its parent will be. In this situation, implement this method by checking whether the domain argument matches the domain of _parent._url. Again, you must parse the domain out of the full URL from _parent._url. In this situation, you don't have to wait for the parent SWF file to load; the parent will already be loaded by the time the child loads.

Example

The following example shows how a LocalConnection object in a receiving SWF file can permit SWF files from any domain to invoke its methods. Compare this to the example in LocalConnection.connect(), in which only SWF files from the same domain can invoke the Trace method in the receiving SWF file. For a discussion of the use of the underscore (_) in the connection name, see LocalConnection.send().

var aLocalConnection = new LocalConnection();
aLocalConnection.Trace = function(aString)
{
  aTextField = aTextField + aString + newline;
}

aLocalConnection.allowDomain = function() {
  // Any domain can invoke methods on this LocalConnection object
  return true;
}

aLocalConnection.connect("_trace");

In the following example, the receiving SWF file accepts commands only from SWF files located in thisDomain.com or thatDomain.com.

var aLocalConnection = new LocalConnection();
aLocalConnection.Trace = function(aString)
{
  aTextField = aTextField + aString + newline;
}

aLocalConnection.allowDomain = function(sendingDomain)
{
  return(sendingDomain=="thisDomain.com" || sendingDomain=="thatDomain.com");
}

aLocalConnection.connect("_trace");

See also

LocalConnection.connect(), LocalConnection.domain(), LocalConnection.send(), MovieClip._url, MovieClipLoader.onLoadComplete(), _parent


LocalConnection.allowInsecureDomain

Availability

Flash Player 7.

Usage

receiving_lc.allowInsecureDomain = function([sendingDomain]) {
  // Your statements here return true or false
}

Parameters

sendingDomain An optional parameter specifying the domain of the SWF file containing the sending LocalConnection object.

Returns

Nothing.

Description

Event handler; invoked whenever receiving_lc, which is in a SWF file hosted at a domain using a secure protocol (HTTPS), receives a request to invoke a method from a sending LocalConnection object that is in a SWF file that is hosted at a nonsecure protocol. Flash expects the code you implement in this handler to return a Boolean value of true or false. If the handler doesn't return true, the request from the sending object is ignored, and the method is not invoked.

By default, SWF files hosted using the HTTPS protocol can be accessed only by other SWF files hosted using the HTTPS protocol. This implementation maintains the integrity provided by the HTTPS protocol.

Using this method to override the default behavior is not recommended, as it compromises HTTPS security. However, you may need to do so, for example, if you need to permit access to HTTPS files published for Flash Player 7 or later from HTTP files published for Flash Player 6.

A SWF file published for Flash Player 6 can use the LocalConnection.allowDomain event handler to permit HTTP to HTTPS access. However, because security is implemented differently in Flash Player 7, you must use the LocalConnection.allowInsecureDomain() method to permit such access in SWF files published for Flash Player 7 or later.

See also

LocalConnection.allowDomain, LocalConnection.connect()


LocalConnection.close()

Availability

Flash Player 6.

Usage

receiving_lc.close

Parameters

None.

Returns

Nothing.

Description

Method; closes (disconnects) a LocalConnection object. Issue this command when you no longer want the object to accept commands—for example, when you want to issue a LocalConnection.connect() command using the same connectionName parameter in another SWF file.

See also

LocalConnection.connect()


LocalConnection.connect()

Availability

Flash Player 6.

Usage

receiving_lc.connect(connectionName)

Parameters

connectionName A string that corresponds to the connection name specified in the LocalConnection.send() command that wants to communicate with receiving_lc.

Returns

A Boolean value of true if no other process running on the same client machine has already issued this command using the same value for the connectionName parameter, false otherwise.

Description

Method; prepares a LocalConnection object to receive commands from a LocalConnection.send() command (called the "sending LocalConnection object"). The object used with this command is called the "receiving LocalConnection object." The receiving and sending objects must be running on the same client machine.

Be sure to define the methods attached to receiving_lc before calling this method, as shown in all the examples in this section.

By default, the Flash Player resolves connectionName into a value of "superdomain:connectionName", where superdomain is the superdomain of the SWF file containing the LocalConnection.connect() command. For example, if the SWF file containing the receiving LocalConnection object is located at www.someDomain.com, connectionName resolves to "someDomain.com:connectionName". (If a SWF file is located on the client machine, the value assigned to superdomain is "localhost".)

Also by default, the Flash Player lets the receiving LocalConnection object accept commands only from sending LocalConnection objects whose connection name also resolves into a value of "superdomain:connectionName". In this way, Flash makes it very simple for SWF files located in the same domain to communicate with each other.

If you are implementing communication only between SWF files in the same domain, specify a string for connectionName that does not begin with an underscore (_) and that does not specify a domain name (for example, "myDomain:connectionName"). Use the same string in the LocalConnection.connect(connectionName) command.

If you are implementing communication between SWF files located in different domains, see the discussion of connectionName in LocalConnection.send(), and also the LocalConnection.allowDomain and LocalConnection.domain() entries.

Example

The following example shows how a SWF file in a particular domain can invoke a method named Trace in a receiving SWF file in the same domain. The receiving SWF file functions as a trace window for the sending SWF file; it contains two methods that other SWF files can call—Trace and Clear. Buttons pressed in the sending SWF files call these methods with specified parameters.

// Receiving SWF
var aLocalConnection = new LocalConnection();
aLocalConnection.Trace = function(aString)
{
  aTextField = aTextField + aString + newline;
}
aLocalConnection.Clear = function()
{
  aTextField = "";
}
aLocalConnection.connect("trace");
stop();

SWF 1 contains the following code attached to a button labeled PushMe. When you push the button, you see the sentence "The button was pushed." in the receiving SWF file.

on (press)
{
  var lc = new LocalConnection();
  lc.send("trace", "Trace", "The button was pushed.");
  delete lc;
}

SWF 2 contains an input text box with a var name of myText, and the following code attached to a button labeled Copy. When you type some text and then push the button, you see the text you typed in the receiving SWF file.

on (press)
{
  _parent.lc.send("trace", "Trace", _parent.myText);
  _parent.myText = "";
}

SWF 3 contains the following code attached to a button labeled Clear. When you push the button, the contents of the trace window in the receiving SWF file are cleared (erased).

on (press)
{
  var lc = new LocalConnection();
  lc.send("trace", "Clear");
  delete lc;
}

See also

LocalConnection.send()


LocalConnection.domain()

Availability

Flash Player 6; behavior changed in Flash Player 7.

Usage

my_lc.domain()

Parameters

None.

Returns

A string representing the domain of the location of the current SWF file; for details, see "Description," below.

Description

Method; returns a string representing the domain of the location of the current SWF file.

In SWF files published for Flash Player 6, the returned string is the superdomain of the current SWF file. For example, if the SWF file is located at www.macromedia.com, this command returns "macromedia.com".

In SWF files published for Flash Player 7 or later, the returned string is the exact domain of the current SWF file. For example, if the SWF file is located at www.macromedia.com, this command returns "www.macromedia.com".

If the current SWF file is a local file residing on the client machine, this command returns "localhost".

The most common way to use this command is to include the domain name of the sending LocalConnection object as a parameter to the method you plan to invoke in the receiving LocalConnection object, or in conjunction with LocalConnection.allowDomain to accept commands from a specified domain. If you are enabling communication only between LocalConnection objects that are located in the same domain, you probably don't need to use this command.

Example

In the following example, a receiving SWF file accepts commands only from SWF files located in the same domain or at macromedia.com.

my_lc = new LocalConnection();
my_lc.allowDomain = function(sendingDomain)
{
  return (sendingDomain==this.domain() || sendingDomain=="macromedia.com");
}

In the following example, a sending SWF file located at yourdomain.com invokes a method in a receiving SWF file located at mydomain.com. The sending SWF file includes its domain name as a parameter to the method it invokes, so the receiving SWF file can return a reply value to a LocalConnection object in the correct domain. The sending SWF file also specifies that it will accept commands only from SWF files at mydomain.com.

Line numbers are included for reference purposes. The sequence of events is as follows:

  • The receiving SWF file prepares to receive commands on a connection named "sum" (line 11). The Flash Player resolves the name of this connection to "mydomain.com:sum" (see LocalConnection.connect()).
  • The sending SWF file prepares to receive a reply on the LocalConnection object named "result" (line 58). It also specifies that it will accept commands only from SWF files at mydomain.com (lines 51 to 53).
  • The sending SWF file invokes the aSum method of a connection named "mydomain.com:sum" (line 59), and passes the following parameters: its domain (lc.domain()), the name of the connection to receive the reply ("result"), and the values to be used by aSum (123 and 456).
  • The aSum method (line 6) is invoked with the following values: sender = "mydomain.com:result", replyMethod = "aResult", n1 = 123, and n2 = 456. It therefore executes the following line of code:
    this.send("mydomain.com:result", "aResult", (123 + 456));
  • The aResult method (line 54) displays the value returned by aSum (579).
    // The receiving SWF at http://www.mydomain.com/folder/movie.swf
// contains the following code

1     var aLocalConnection = new LocalConnection();
2     aLocalConnection.allowDomain = function()
3     {
    // Allow connections from any domain
4      return true;
5     }
6    aLocalConnection.aSum = function(sender, replyMethod, n1, n2)
7    {
8      this.send(sender, replyMethod, (n1 + n2));
9    }
10
11    aLocalConnection.connect("sum");

// The sending SWF at http://www.yourdomain.com/folder/movie.swf
// contains the following code

50    var lc = new LocalConnection();
51    lc.allowDomain = function(aDomain) {
      // Allow connections only from mydomain.com
52      return (aDomain == "mydomain.com");
53    }
54    lc.aResult = function(aParam) {
55      trace("The sum is " + aParam);
56    }
57
58    lc.connect("result");
59    lc.send("mydomain.com:sum", "aSum", lc.domain() + ':' + "result",      "aResult", 123, 456);

See also

LocalConnection.allowDomain


LocalConnection.onStatus

Availability

Flash Player 6.

Usage

sending_lc.onStatus = function(infoObject) {
  // your statements here
}

Parameters

infoObject A parameter defined according to the status message. For details about this parameter, see "Description," below.

Returns

Nothing.

Description

Event handler; invoked after a sending LocalConnection object tries to send a command to a receiving LocalConnection object. If you want to respond to this event handler, you must create a function to process the information object sent by the LocalConnection object.

If the information object returned by this event handler contains a level value of "Status", Flash successfully sent the command to a receiving LocalConnection object. This does not mean that Flash successfully invoked the specified method of the receiving LocalConnection object, only that Flash was able to send the command. For example, the method is not invoked if the receiving LocalConnection object doesn't allow connections from the sending domain, or if the method does not exist. The only way to know for sure if the method was invoked is to have the receiving object send a reply to the sending object.

If the information object returned by this event handler contains a level value of "Error", Flash was unable to send the command to a receiving LocalConnection object, most likely because there is no receiving LocalConnection object connected whose name corresponds to the name specified in the sending_lc.send() command that invoked this handler.

In addition to this onStatus handler, Flash also provides a "super" function called System.onStatus. If onStatus is invoked for a particular object and there is no function assigned to respond to it, Flash processes a function assigned to System.onStatus if it exists.

In most cases, you will implement this handler only to respond to error conditions, as shown in the following example.

Example

The following example displays information about a failed connection in the Output panel:

sending_lc = new LocalConnection();
sending_lc.onStatus = function(infoObject)
{
  if (infoObject.level == "Error")
  {
    trace("Connection failed.");
  }
}
sending_lc.send("receiving_lc", "methodName");

See also

LocalConnection.send(), System.onStatus


LocalConnection.send()

Availability

Flash Player 6.

Usage

sending_lc.send (connectionName, method [, p1,...,pN])

Parameters

connectionName A string that corresponds to the connection name specified in the LocalConnection.connect() command that wants to communicate with sending_lc.

method A string specifying the name of the method to be invoked in the receiving LocalConnection object. The following method names cause the command to fail: send, connect, close, domain, onStatus, and allowDomain.

p1,...pN Optional parameters to be passed to the specified method.

Returns

A Boolean value of true if Flash can carry out the request, false otherwise.

Note: A return value of true does not necessarily mean that Flash successfully connected to a receiving LocalConnection object, only that the command is syntactically correct. To determine whether the connection succeeded, see LocalConnection.onStatus.

Description

Method; invokes the method named method on a connection opened with the LocalConnection.connect(connectionName) command (called the "receiving LocalConnection object"). The object used with this command is called the "sending LocalConnection object". The SWF files that contain the sending and receiving objects must be running on the same client machine.

There is a limit to the amount of data you can pass as parameters to this command. If the command returns false but your syntax is correct, try breaking up the LocalConnection.send() requests into multiple commands.

As discussed in the entry LocalConnection.connect(), Flash adds the current superdomain to connectionName by default. If you are implementing communication between different domains, you need to define connectionName in both the sending and receiving LocalConnection objects in such a way that Flash does not add the current superdomain to connectionName. There are two ways you can do so:

  • Use an underscore (_) at the beginning of connectionName in both the sending and receiving LocalConnection objects. In the SWF file containing the receiving object, use LocalConnection.allowDomain to specify that connections from any domain will be accepted. This implementation lets you store your sending and receiving SWF files in any domain.
  • Include the superdomain in connectionName in the sending LocalConnection object—for example, myDomain.com:myConnectionName. In the receiving object, use LocalConnection.allowDomain to specify that connections from the specified superdomain will be accepted (in this case, myDomain.com), or that connections from any domain will be accepted.

Note: You cannot specify a superdomain in connectionName in the receiving LocalConnection object, only in the sending LocalConnection object.

Example

For an example of communicating between LocalConnection objects located in the same domain, see LocalConnection.connect(). For an example of communicating between LocalConnection objects located in any domain, see LocalConnection.allowDomain. For an example of communicating between LocalConnection objects located in specified domains, see LocalConnection.allowDomain and LocalConnection.domain().

See also

LocalConnection.allowDomain, LocalConnection.connect(), LocalConnection.domain(), LocalConnection.onStatus


lt (less than — string specific)

Availability

Flash Player 4. This operator was deprecated in Flash 5 in favor of the new < (less than) operator.

Usage

expression1 lt expression2

Parameters

expression1, expression2 Numbers, strings, or variables.

Description

Operator (comparison); compares expression1 to expression2 and returns true if expression1 is less than expression2; otherwise, it returns false.

See also

< (less than)


Math class

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Description

The Math class is a top-level class whose methods and properties you can use without using a constructor.

Use the methods and properties of this class to access and manipulate mathematical constants and functions. All of the properties and methods of the Math class are static, and must be called using the syntax Math.method(parameter) or Math.constant. In ActionScript, constants are defined with the maximum precision of double-precision IEEE-754 floating-point numbers.

Several of the Math class methods take the radian of an angle as an parameter. You can use the equation below to calculate radian values, or simply pass the equation (entering a value for degrees) for the radian parameter.

To calculate a radian value, use this formula:

radian = Math.PI/180 * degree

The following is an example of passing the equation as an parameter to calculate the sine of a 45-degree angle:

Math.SIN(Math.PI/180 * 45) is the same as Math.SIN(.7854)

The Math class is fully supported in Flash Player 5. In Flash Player 4, you can use methods of the Math class, but they are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Method summary for the Math class

Method | Description
Math.abs() | Computes an absolute value.
Math.acos() | Computes an arc cosine.
Math.asin() | Computes an arc sine.
Math.atan() | Computes an arc tangent.
Math.atan2() | Computes an angle from the x-axis to the point.
Math.ceil() | Rounds a number up to the nearest integer.
Math.cos() | Computes a cosine.
Math.exp() | Computes an exponential value.
Math.floor() | Rounds a number down to the nearest integer.
Math.log() | Computes a natural logarithm.
Math.max() | Returns the larger of the two integers.
Math.min() | Returns the smaller of the two integers.
Math.pow() | Computes x raised to the power of the y.
Math.random() | Returns a pseudo-random number between 0.0 and 1.0.
Math.round() | Rounds to the nearest integer.
Math.sin() | Computes a sine.
Math.sqrt() | Computes a square root.
Math.tan() | Computes a tangent.

Property summary for the Math class

All of the properties for the Math class are constants.

Property | Description
Math.E | Euler's constant and the base of natural logarithms (approximately 2.718).
Math.LN2 | The natural logarithm of 2 (approximately 0.693).
Math.LOG2E | The base 2 logarithm of e (approximately 1.442).
Math.LN2 | The natural logarithm of 10 (approximately 2.302).
Math.LOG10E | The base 10 logarithm of e (approximately 0.434).
Math.PI | The ratio of the circumference of a circle to its diameter (approximately 3.14159).
Math.SQRT1_2 | The reciprocal of the square root of 1/2 (approximately 0.707).
Math.SQRT2 | The square root of 2 (approximately 1.414).


Math.abs()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.abs(x)

Parameters

x A number.

Returns

A number.

Description

Method; computes and returns an absolute value for the number specified by the parameter x.


Math.acos()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.acos(x)

Parameters

x A number from -1.0 to 1.0.

Returns

Nothing.

Description

Method; computes and returns the arc cosine of the number specified in the parameter x, in radians.


Math.asin()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.asin(x);

Parameters

x A number from -1.0 to 1.0.

Returns

A number.

Description

Method; computes and returns the arc sine for the number specified in the parameter x, in radians.


Math.atan()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.atan(tangent)

Parameters

tangent A number that represents the tangent of an angle.

Returns

A number.

Description

Method; computes and returns the value, in radians, of the angle whose tangent is specified in the parameter tangent. The return value is between negative pi divided by 2 and positive pi divided by 2.

See also

Math.atan2(), Math.tan()


Math.atan2()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.atan2(y, x)

Parameters

y A number specifying the y coordinate of the point.

x A number specifying the x coordinate of the point.

Returns

A number.

Description

Method; computes and returns the angle of the point y/x in radians, when measured counterclockwise from a circle's x axis (where 0,0 represents the center of the circle). The return value is between positive pi and negative pi.

See also

Math.atan(), Math.tan()


Math.ceil()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.ceil(x)

Parameters

x A number or expression.

Returns

A number.

Description

Method; returns the ceiling of the specified number or expression. The ceiling of a number is the closest integer that is greater than or equal to the number.


Math.cos()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.cos(x)

Parameters

x An angle measured in radians.

Returns

A number.

Description

Method; returns the cosine (a value from -1.0 to 1.0) of the angle specified by the parameter x. The angle x must be specified in radians. Use the information outlined in the Math class entry to calculate a radian.


Math.E

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.E

Parameters

None.

Returns

Nothing.

Description

Constant; a mathematical constant for the base of natural logarithms, expressed as e. The approximate value of e is 2.71828.


Math.exp()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.exp(x)

Parameters

x The exponent; a number or expression.

Returns

A number.

Description

Method; returns the value of the base of the natural logarithm (e), to the power of the exponent specified in the parameter x. The constant Math.E can provide the value of e.


Math.floor()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.floor(x)

Parameters

x A number or expression.

Returns

A number.

Description

Method; returns the floor of the number or expression specified in the parameter x. The floor is the closest integer that is less than or equal to the specified number or expression.

Example

The following code returns a value of 12:

Math.floor(12.5);


Math.log()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.log(x)

Parameters

x A number or expression with a value greater than 0.

Returns

A number.

Description

Method; returns the logarithm of parameter x.


Math.LN2

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.LN2

Parameters

None.

Returns

Nothing.

Description

Constant; a mathematical constant for the natural logarithm of 2, expressed as loge2, with an approximate value of 0.69314718055994528623.


Math.LN10

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.LN10

Parameters

None.

Returns

Nothing.

Description

Constant; a mathematical constant for the natural logarithm of 10, expressed as loge10, with an approximate value of 2.3025850929940459011.


Math.LOG2E

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.LOG2E

Parameters

None.

Returns

Nothing.

Description

Constant; a mathematical constant for the base-2 logarithm of the constant e (Math.E), expressed as log2e, with an approximate value of 1.442695040888963387.


Math.LOG10E

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.LOG10E

Parameters

None.

Returns

Nothing.

Description

Constant; a mathematical constant for the base-10 logarithm of the constant e (Math.E), expressed as log10e, with an approximate value of 0.43429448190325181667.


Math.max()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.max(x , y)

Parameters

x A number or expression.

y A number or expression.

Returns

A number.

Description

Method; evaluates x and y and returns the larger value.


Math.min()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.min(x , y)

Parameters

x A number or expression.

y A number or expression.

Returns

A number.

Description

Method; evaluates x and y and returns the smaller value.


Math.PI

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.PI

Parameters

None.

Returns

Nothing.

Description

Constant; a mathematical constant for the ratio of the circumference of a circle to its diameter, expressed as pi, with a value of 3.14159265358979.


Math.pow()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.pow(x , y)

Parameters

x A number to be raised to a power.

y A number specifying a power the parameter x is raised to.

Returns

A number.

Description

Method; computes and returns x to the power of y: xy.


Math.random()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.random()

Parameters

None.

Returns

A number.

Description

Method; returns n, where 0 <= n < 1.

See also

random


Math.round()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.round(x)

Parameters

x A number.

Returns

A number.

Description

Method; rounds the value of the parameter x up or down to the nearest integer and returns the value.


Math.sin()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.sin(x)

Parameters

x An angle measured in radians.

Returns

Number; the sine of the specified angle (between -1.0 and 1.0).

Description

Method; computes and returns the sine of the specified angle in radians. Use the information outlined in the Math class entry to calculate a radian.


Math.sqrt()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.sqrt(x)

Parameters

x A number or expression greater than or equal to 0.

Returns

A number.

Description

Method; computes and returns the square root of the specified number.


Math.SQRT1_2

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.SQRT1_2

Parameters

None.

Returns

Nothing.

Description

Constant; a mathematical constant for the square root of one-half.


Math.SQRT2

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.SQRT2

Parameters

None.

Returns

Nothing.

Description

Constant; a mathematical constant for the square root of 2, with an approximate value of 1.414213562373.


Math.tan()

Availability

Flash Player 5. In Flash Player 4, the methods and properties of the Math class are emulated using approximations and may not be as accurate as the non-emulated math functions supported by Flash Player 5.

Usage

Math.tan(x)

Parameters

x An angle measured in radians.

Returns

A number.

Description

Method; computes and returns the tangent of the specified angle. To calculate a radian, use the information outlined in the introduction to the Math class.

See also

Math.atan()


maxscroll

Availability

Flash Player 4. This function has been deprecated in favor of the TextField.maxscroll property.

Usage

variable_name.maxscroll

Description

Property (read-only); a deprecated property that indicates the line number of the topmost visible line of text in a text field when the bottommost line in the field is also visible. The maxscroll property works with the scroll property to control the display of information in a text field. This property can be retrieved, but not modified.

See also

TextField.maxscroll, TextField.scroll


mbchr

Availability

Flash Player 4. This function has been deprecated in favor of the String.fromCharCode() method.

Usage

mbchr(number)

Parameters

number The number to convert to a multibyte character.

Returns

A string.

Description

String function; converts an ASCII code number to a multibyte character.

See also

String.fromCharCode()


mblength

Availability

Flash Player 4. This function has been deprecated in favor of the String class.

Usage

mblength(string)

Parameters

string A string.

Returns

A number.

Description

String function; returns the length of the multibyte character string.


mbord

Availability

Flash Player 4. This function was deprecated in Flash 5 in favor of String.charCodeAt().

Usage

mbord(character)

Parameters

character The character to convert to a multibyte number.

Returns

A number.

Description

String function; converts the specified character to a multibyte number.

See also

String.fromCharCode()


mbsubstring

Availability

Flash Player 4. This function was deprecated in Flash 5 in favor of String.substr().

Usage

mbsubstring(value, index, count)

Parameters

value The multibyte string from which to extract a new multibyte string.

index The number of the first character to extract.

count The number of characters to include in the extracted string, not including the index character.

Returns

A string.

Description

String function; extracts a new multibyte character string from a multibyte character string.

See also

String.substr()


Microphone class

Availability

Flash Player 6.

Description

The Microphone class lets you capture audio from a microphone attached to the computer that is running Flash Player.

The Microphone class is primarily for use with Flash Communication Server, but can be used in a limited fashion without the server—for example, to transmit sound from your microphone through the speakers on your local system.

To create or reference a Microphone object, use the Microphone.get() method.

Method summary for the Microphone class

Method | Description
Microphone.get() | Returns a default or specified Microphone object, or null if the microphone is not available.
Microphone.setGain() | Specifies the amount by which the microphone should boost the signal.
Microphone.setRate() | Specifies the rate at which the microphone should capture sound, in kHz.
Microphone.setSilenceLevel() | Specifies the amount of sound required to activate the microphone.
Microphone.setUseEchoSuppression() | Specifies whether to use the echo suppression feature of the audio codec.

Property summary for the Microphone class

Property (read-only) | Description
Microphone.activityLevel | The amount of sound the microphone is detecting.
Microphone.gain | The amount by which the microphone boosts the signal before transmitting it.
Microphone.index | The index of the current microphone.
Microphone.muted | A Boolean value that specifies whether the user has allowed or denied access to the microphone.
Microphone.name | The name of the current sound capture device, as returned by the sound capture hardware.
Microphone.names | Class property: an array of strings reflecting the names of all available sound capture devices, including sound cards and microphones.
Microphone.rate | The sound capture rate, in kHz.
Microphone.silenceLevel() | The amount of sound required to activate the microphone.
Microphone.silenceTimeout() | The number of milliseconds between the time the microphone stops detecting sound and the time Microphone.onActivity(false) is called.
Microphone.useEchoSuppression | A Boolean value that specifies whether echo suppression is being used.

Event handler summary for the Microphone class

Event handler | Description
Microphone.onActivity | Invoked when the microphone starts or stops detecting sound.
Microphone.onStatus | Invoked when the user allows or denies access to the microphone.

Constructor for the Microphone class

See Microphone.get().


Microphone.activityLevel

Availability

Flash Player 6.

Usage

active_mic.activityLevel

Description

Read-only property; a numeric value that specifies the amount of sound the microphone is detecting. Values range from 0 (no sound is being detected) to 100 (very loud sound is being detected). The value of this property can help you determine a good value to pass to the Microphone.setSilenceLevel() method.

If the microphone is available but is not yet being used because Microphone.get() has not been called, this property is set to -1.

Example

The following example sets the variable level to the activity level of the current microphone, active_mic.activityLevel.

var level = active_mic.activityLevel;

See also

Microphone.setGain()


Microphone.gain

Availability

Flash Player 6.

Usage

active_mic.gain

Description

Read-only property; the amount by which the microphone boosts the signal. Valid values are 0 to 100. The default value is 50.

Example

The following example is attached to the nib of a slide bar. When this clip is loaded, Flash checks for the value active_mic.gain and provides a default value if this value is undefined. The _x position is then used to set the gain on the microphone to the user's preference.

onClipEvent (load) {
  if (_root.active_mic.gain == undefined) {
    _root.active_mic.setGain = 75;
  }

  this._x = _root.active_mic.gain;
  _root.txt_micgain = this._x;

  left = this._x;
  right = left+50;
  top = this._y;
  bottom = top;
}

on (press) {
  startDrag(this, false, left, top, right, bottom);
  this._xscale = 100;
  this._yscale = 100;
}

on (release, releaseOutside) {
  stopDrag();
  g = (this._x-50)*2;
  _root.active_mic.setGain(g);
  _root.txt_micgain = g;
  this._xscale = 100;
  this._yscale = 100;
}

See also

Microphone.setGain()


Microphone.get()

Availability

Flash Player 6.

Usage

Microphone.get([index])

Note: The correct syntax is Microphone.get(). To assign the Microphone object to a variable, use syntax like active_mic = Microphone.get().

Parameters

index An optional zero-based integer that specifies which microphone to get, as determined from the array that Microphone.names contains. To get the default microphone (which is recommended for most applications), omit this parameter.

Returns

  • If index is not specified, this method returns a reference to the default microphone or, if it is not available, to the first available microphone. If no microphones are available or installed, the method returns null.
  • If index is specified, this method returns a reference to the requested microphone, or null if it is not available.

Description

Method; returns a reference to a Microphone object for capturing audio. To actually begin capturing the audio, you must attach the Microphone object to a MovieClip object (see MovieClip.attachAudio()).

Unlike objects that you create using the new constructor, multiple calls to Microphone.get() reference the same microphone. Thus, if your script contains the lines mic1 = Microphone.get() and mic2 = Microphone.get(), both mic1 and mic2 reference the same (default) microphone.

In general, you shouldn't pass a value for index; simply use the Microphone.get() method to return a reference to the default microphone. By means of the Microphone settings panel (discussed later in this section), the user can specify the default microphone Flash should use. If you pass a value for index, you might be trying to reference a microphone other than the one the user prefers. You might use index in rare cases—for example, if your application is capturing audio from two microphones at the same time.

When a SWF file tries to access the microphone returned by the Microphone.get() method—for example, when you issue MovieClip.attachAudio()— Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access to the microphone. (Make sure your Stage size is at least 215 x 138 pixels; this is the minimum size Flash requires to display the dialog box.)

When the user responds to this dialog box, the Microphone.onStatus event handler returns an information object that indicates the user's response. To determine whether the user has denied or allowed access to the camera without processing this event handler, use Microphone.muted.

The user can also specify permanent privacy settings for a particular domain by right-clicking (Windows) or Control-clicking (Macintosh) while a SWF file is playing, choosing Settings, opening the Privacy panel, and selecting Remember.

You can't use ActionScript to set the Allow or Deny value for a user, but you can display the Privacy panel for the user by using System.showSettings(0). If the user selects Remember, Flash Player no longer displays the Privacy dialog box for SWF files from this domain.

If Microphone.get() returns null, either the microphone is in use by another application, or there are no microphones installed on the system. To determine whether any microphones are installed, use Microphones.names.length. To display the Flash Player Microphone Settings panel, which lets the user choose the microphone to be referenced by Microphone.get(), use System.showSettings(2).

Example

The following example lets the user specify the default microphone, then captures audio and plays it back locally. To avoid feedback, you may want to test this code while wearing headphones.

System.showSettings(2);
active_mic = Microphone.get();
_root.attachAudio(active_mic);

See also

Microphone.index, Microphone.muted, Microphone.names, Microphone.onStatus, MovieClip.attachAudio(), System.showSettings()


Microphone.index

Availability

Flash Player 6.

Usage

active_mic.index

Description

Read-only property; a zero-based integer that specifies the index of the microphone, as reflected in the array returned by Microphone.names.

See also

Microphone.get(), Microphone.names


Microphone.muted

Availability

Flash Player 6.

Usage

active_mic.muted

Description

Read-only property; a Boolean value that specifies whether the user has denied access to the microphone (true) or allowed access (false). When this value changes, Microphone.onStatus is invoked. For more information, see Microphone.get().

See also

Microphone.get(), Microphone.onStatus


Microphone.name

Availability

Flash Player 6.

Usage

active_mic.name

Description

Read-only property; a string that specifies the name of the current sound capture device, as returned by the sound capture hardware.

Example

The following example displays the name of the default microphone in the Output panel.

active_mic = Microphone.get();
trace("The microphone name is: " + active_mic.name);

See also

Microphone.get(), Microphone.names


Microphone.names

Availability

Flash Player 6.

Usage

Microphone.names

Note: The correct syntax is Microphone.names. To assign the return value to a variable, use syntax like mic_array = Microphone.names. To determine the name of the current microphone, use active_mic.name.

Description

Read-only class property; retrieves an array of strings reflecting the names of all available sound capture devices without displaying the Flash Player Privacy Settings panel. This array behaves the same as any other ActionScript array, implicitly providing the zero-based index of each sound capture device and the number of sound capture devices on the system (by means of Microphone.names.length). For more information, see the Array class entry.

Calling Microphone.names requires an extensive examination of the hardware, and it may take several seconds to build the array. In most cases, you can just use the default microphone.

Example

The following code returns information on the array of audio devices.

allMicNames_array = Microphone.names;
_root.debugWindow += "Microphone.names located these device(s):" + newline;
for(i=0; i < allMicNames_array.length; i++){
  debugWindow += "[" + i + "]: " + allMicNames[i] + newline;
}

For example, the following information could be displayed.

Microphone.names located these device(s):
[0]: Crystal SoundFusion(tm)
[1]: USB Audio Device

See also

Array class, Microphone.name


Microphone.onActivity

Availability

Flash Player 6.

Usage

active_mic.onActivity = function(activity) {
  // your statements here
}

Parameters

activity A Boolean value set to true when the microphone starts detecting sound, false when it stops.

Returns

Nothing.

Description

Event handler; invoked when the microphone starts or stops detecting sound. If you want to respond to this event handler, you must create a function to process its activity value.

To specify the amount of sound required to invoke Microphone.onActivity(true), and the amount of time that must elapse without sound before Microphone.onActivity(false) is invoked, use Microphone.setSilenceLevel().

Example

The following example displays true or false in the Output panel when the microphone starts or stops detecting sound.

active_mic = Microphone.get();
_root.attachAudio(active_mic);
active_mic.onActivity = function(mode)
{
  trace(mode);
};

See also

Microphone.setSilenceLevel()


Microphone.onStatus

Availability

Flash Player 6.

Usage

active_mic.onStatus = function(infoObject) {
  // your statements here
}

Parameters

infoObject A parameter defined according to the status message.

Returns

Nothing.

Description

Event handler; invoked when the user allows or denies access to the microphone. If you want to respond to this event handler, you must create a function to process the information object generated by the microphone.

When a SWF file tries to access the microphone, Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access.

  • If the user allows access, the Microphone.muted property is set to false, and this event handler is invoked with an information object whose code property is "Microphone.Unmuted" and whose level property is "Status".
  • If the user denies access, the Microphone.muted property is set to true, and this event handler is invoked with an information object whose code property is "Microphone.Muted" and whose level property is "Status".

To determine whether the user has denied or allowed access to the microphone without processing this event handler, use Microphone.muted.

Note: If the user chooses to permanently allow or deny access for all SWF files from a specified domain, this method is not invoked for SWF files from that domain unless the user later changes the privacy setting. For more information, see Microphone.get().

Example

See the example for Camera.onStatus.

See also

Microphone.get(), Microphone.muted


Microphone.rate

Availability

Flash Player 6.

Usage

active_mic.rate

Description

Read-only property; the rate at which the microphone is capturing sound, in kHz. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz.

To set this value, use Microphone.setRate().

Example

The following example saves the current rate to the variable original.

original = active_mic.rate;

See also

Microphone.setRate()


Microphone.setGain()

Availability

Flash Player 6.

Usage

active_mic.setGain(gain)

Parameters

gain An integer that specifies the amount by which the microphone should boost the signal. Valid values are 0 to 100. The default value is 50; however, the user may change this value in the Flash Player Microphone Settings panel.

Returns

Nothing.

Description

Method; sets the microphone gain—that is, the amount by which the microphone should multiply the signal before transmitting it. A value of 0 tells Flash to multiply by 0; that is, the microphone transmits no sound.

You can think of this setting like a volume knob on a stereo: 0 is no volume and 50 is normal volume; numbers below 50 specify lower than normal volume, while numbers above 50 specify higher than normal volume.

Example

The following example ensures that the microphone gain setting is less than or equal to 55.

var active_mic = Microphone.get();
if (active_mic.gain > 55){
  active_mic.setGain(55);
}

See also

Microphone.gain, Microphone.setUseEchoSuppression()


Microphone.setRate()

Availability

Flash Player 6.

Usage

active_mic.setRate(kHz)

Parameters

kHz The rate at which the microphone should capture sound, in kHz. Acceptable values are 5, 8, 11, 22, and 44. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz.

Returns

Nothing.

Description

Method; sets the rate, in kHz, at which the microphone should capture sound.

Example

The following example sets the microphone rate to the user's preference (which you have assigned to the userRate variable) if it is one of the following values: 5, 8, 11, 22, or 44. If it is not, the value is rounded to the nearest acceptable value that the sound capture device supports.

active_mic.setRate(userRate);

See also

Microphone.rate


Microphone.setSilenceLevel()

Availability

Flash Player 6.

Usage

active_mic.setSilenceLevel(level [, timeout])

Parameters

level An integer that specifies the amount of sound required to activate the microphone and invoke Microphone.onActivity(true). Acceptable values range from 0 to 100. The default value is 10.

timeout An optional integer parameter that specifies how many milliseconds must elapse without activity before Flash considers sound to have stopped and invokes Microphone.onActivity(false). The default value is 2000 (2 seconds).

Returns

Nothing.

Description

Method; sets the minimum input level that should be considered sound and (optionally) the amount of silent time signifying that silence has actually begun.

  • To prevent the microphone from detecting sound at all, pass a value of 100 for level; Microphone.onActivity is never invoked.
  • To determine the amount of sound the microphone is currently detecting, use Microphone.activityLevel.

Activity detection is the ability to detect when audio levels suggest that a person is talking. When someone is not talking, bandwidth can be saved because there is no need to send the associated audio stream. This information can also be used for visual feedback so that users know they (or others) are silent.

Silence values correspond directly to activity values. Complete silence is an activity value of 0. Constant loud noise (as loud as can be registered based on the current gain setting) is an activity value of 100. After gain is appropriately adjusted, your activity value is less than your silence value when you're not talking; when you are talking, the activity value exceeds your silence value.

This method is similar in purpose to Camera.setMotionLevel(); both methods are used to specify when the onActivity event handler should be invoked. However, these methods have a significantly different impact on publishing streams:

  • Camera.setMotionLevel() is designed to detect motion and does not affect bandwidth usage. Even if a video stream does not detect motion, video is still sent.
  • Microphone.setSilenceLevel() is designed to optimize bandwidth. When an audio stream is considered silent, no audio data is sent. Instead, a single message is sent, indicating that silence has started.

Example

The following example changes the silence level based on the user's input. The button has the following code attached:

on (press)
{
  this.makeSilenceLevel(this.silenceLevel);
}

The makeSilenceLevel() function called by the button continues:

function makeSilenceLevel(s)
{
  this.obj.setSilenceLevel(s);
  this.SyncMode();
  this.silenceLevel= s;
}

For more information, see the example for Camera.setMotionLevel().

See also

Microphone.activityLevel, Microphone.onActivity, Microphone.setGain(), Microphone.silenceLevel(), Microphone.silenceTimeout()


Microphone.setUseEchoSuppression()

Availability

Flash Player 6.

Usage

active_mic.setUseEchoSuppression(suppress)

Parameters

suppress A Boolean value indicating whether echo suppression should be used (true) or not (false).

Returns

Nothing.

Description

Method; specifies whether to use the echo suppression feature of the audio codec. The default value is false unless the user has selected Reduce Echo in the Flash Player Microphone Settings panel.

Echo suppression is an effort to reduce the effects of audio feedback, which is caused when sound going out the speaker is picked up by the microphone on the same computer. (This is different from echo cancellation, which completely removes the feedback.)

Generally, echo suppression is advisable when the sound being captured is played through speakers—instead of a headset—on the same computer. If your SWF file allows users to specify the sound output device, you may want to call Microphone.setUseEchoSuppression(true) if they indicate they are using speakers and will be using the microphone as well.

Users can also adjust these settings in the Flash Player Microphone Settings panel.

Example

The following example turns on echo suppression.

active_mic.setUseEchoSuppression(true);

See also

Microphone.setGain(), Microphone.useEchoSuppression


Microphone.silenceLevel()

Availability

Flash Player 6.

Usage

active_mic.silenceLevel

Description

Read-only property; an integer that specifies the amount of sound required to activate the microphone and invoke Microphone.onActivity(true). The default value is 10.

Example

See the example for Microphone.silenceTimeout().

See also

Microphone.gain, Microphone.setSilenceLevel()


Microphone.silenceTimeout()

Availability

Flash Player 6.

Usage

active_mic.silenceTimeout

Description

Read-only property; a numeric value representing the number of milliseconds between the time the microphone stops detecting sound and the time Microphone.onActivity(false) is invoked. The default value is 2000 (2 seconds).

To set this value, use Microphone.setSilenceLevel().

Example

The following example sets the timeout to two times its current value.

active_mic.setSilenceLevel(active_mic.silenceLevel,
  active_mic.silenceTimeOut * 2);

See also

Microphone.setSilenceLevel()


Microphone.useEchoSuppression

Availability

Flash Player 6.

Usage

active_mic.useEchoSuppression

Description

Read-only property; a Boolean value of true if echo suppression is enabled, false otherwise. The default value is false unless the user has selected Reduce Echo in the Flash Player Microphone Settings panel.

Example

The following example checks for echo suppression and turns it on if it is off.

_root.active_mic.onActivity = function(active) {
  if (active == true) {
    if (_root.active_mic.useEchoSuppression == false) {
      _root.active_mic.setUseEchoSuppression(true);
    }
  }
}

See also

Microphone.setUseEchoSuppression()


MMExecute()

Availability

Flash Player 7.

Usage

MMExecute("Flash JavaScript API command;")

Parameters

Flash JavaScript API command Any command that you can use in a Flash JavaScript (JSFL) file.

Returns

The result, if any, sent by the JavaScript statement.

Description

Function; lets you issue Flash JavaScript API commands from ActionScript.

The Flash JavaScript API (JSAPI) provides several objects, methods, and properties to duplicate or emulate commands that a user can enter in the authoring environment. Using the JSAPI, you can write scripts that extend Flash in several ways: adding commands to menus, manipulating objects on the Stage, repeating sequences of commands, and so on.

In general, a user runs a JSAPI script by selecting Commands > Run Command. However, you can use this function in an ActionScript script to call a JSAPI command directly. If you use MMExecute() in a script on Frame 1 of your file, the command executes when the SWF file is loaded.

For more information on the JSAPI, see www.macromedia.com/go/jsapi_info_en.

Example

The following command returns an array of objects in the library:

var libe:Array = MMExecute("fl.getDocumentDOM().library.items;");
trace(libe.length + " items in library");


Mouse class

Availability

Flash Player 5.

Description

The Mouse class is a top-level class whose properties and methods you can access without using a constructor. You can use the methods of the Mouse class to hide and show the mouse pointer (cursor) in the SWF file. The mouse pointer is visible by default, but you can hide it and implement a custom pointer that you create using a movie clip (see Creating a custom mouse pointer).

Method summary for the Mouse class

Method | Description
Mouse.addListener() | Registers an object to receive onMouseDown, onMouseMove, and onMouseUp notification.
Mouse.hide() | Hides the mouse pointer in the SWF file.
Mouse.removeListener() | Removes an object that was registered with addListener().
Mouse.show() | Displays the mouse pointer in the SWF file.

Listener summary for the Mouse class

Method | Description
Mouse.onMouseDown | Notified when the mouse button is pressed down.
Mouse.onMouseMove | Notified when the mouse button is moved.
Mouse.onMouseUp | Notified when the mouse button is released.
Mouse.onMouseWheel | Notified when the user rolls the mouse wheel.


Mouse.addListener()

Availability

Flash Player 6.

Usage

Mouse.addListener (newListener)

Parameters

newListener An object.

Returns

Nothing.

Description

Method; registers an object to receive notifications of the onMouseDown, onMouseMove, and onMouseUp listeners.

The newListener parameter should contain an object with defined methods for the onMouseDown, onMouseMove, and onMouseUp listeners.

When the mouse is pressed, moved, or released, regardless of the input focus, all listening objects that are registered with this method have their onMouseDown, onMouseMove, or onMouseUp method invoked. Multiple objects can listen for mouse notifications. If the listener newListener is already registered, no change occurs.

See also

Mouse.onMouseDown, Mouse.onMouseMove, Mouse.onMouseUp


Mouse.hide()

Availability

Flash Player 5.

Usage

Mouse.hide()

Parameters

None.

Returns

A Boolean value: true if the pointer is visible, and false if the pointer is invisible.

Description

Method; hides the pointer in a SWF file. The pointer is visible by default.

Example

The following code, attached to a movie clip on the main Timeline, hides the standard pointer, and sets the x and y positions of the customPointer_mc movie clip instance to the x and y mouse positions in the main Timeline.

onClipEvent(enterFrame){
  Mouse.hide();
  customPointer_mc._x = _root._xmouse;
  customPointer_mc._y = _root._ymouse;
}

See also

Mouse.show(), MovieClip._xmouse, MovieClip._ymouse


Mouse.onMouseDown

Availability

Flash Player 6.

Usage

someListener.onMouseDown

Parameters

None.

Returns

Nothing.

Description

Listener; notified when the mouse is pressed. To use the onMouseDown listener, you must create a listener object. You can then define a function for onMouseDown and use addListener() to register the listener with the Mouse object, as in the following code:

someListener = new Object();
someListener.onMouseDown = function () { ... };
Mouse.addListener(someListener);

Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event.

See also

Mouse.addListener()


Mouse.onMouseMove

Availability

Flash Player 6.

Usage

someListener.onMouseMove

Parameters

None.

Returns

Nothing.

Description

Listener; notified when the mouse moves. To use the onMouseMove listener, you must create a listener object. You can then define a function for onMouseMove and use addListener() to register the listener with the Mouse object, as in the following code:

someListener = new Object();
someListener.onMouseMove = function () { ... };
Mouse.addListener(someListener);

Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event.

See also

Mouse.addListener()


Mouse.onMouseUp

Availability

Flash Player 6.

Usage

someListener.onMouseUp

Parameters

None.

Returns

Nothing.

Description

Listener; notified when the mouse is released. To use the onMouseUp listener, you must create a listener object. You can then define a function for onMouseUp and use addListener() to register the listener with the Mouse object, as in the following code:

someListener = new Object();
someListener.onMouseUp = function () { ... };
Mouse.addListener(someListener);

Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event.

See also

Mouse.addListener()


Mouse.onMouseWheel

Availability

Flash Player 7 (Windows only).

Usage

someListener.onMouseWheel = function ( [ delta [, scrollTarget ] ] ) {
  // your statements here
}

Parameters

delta An optional number indicating how many lines should be scrolled for each notch the user rolls the mouse wheel. A positive delta value indicates an upward scroll; a negative value indicates a downward scroll. Typical values are from 1 to 3, whereas faster scrolling may produce larger values.

scrollTarget An optional parameter that indicates the topmost movie clip instance under the mouse when the mouse wheel was scrolled. If you want to specify a value for scrollTarget but don't want to specify a value for delta, pass null for delta.

Returns

Nothing.

Description

Listener; notified when the user rolls the mouse wheel. To use the onMouseWheel listener, you must create a listener object. You can then define a function for onMouseWheel and use addListener() to register the listener with the Mouse object.

Note: Mouse wheel event listeners are available only on Windows versions of Flash Player.

Example

The following example shows how to create a listener object that responds to mouse wheel events. In this example, the x coordinate of a movie clip object named clip_mc (not shown) is changed each time the user rolls the mouse wheel.

mouseListener = new Object();
mouseListener.onMouseWheel = function(delta) {
  clip_mc._x += delta;
}
Mouse.addListener(mouseListener);

See also

Mouse.addListener(), TextField.mouseWheelEnabled


Mouse.removeListener()

Availability

Flash Player 6.

Usage

Mouse.removeListener (listener)

Parameters

listener An object.

Returns

If the listener object was successfully removed, the method returns true; if the listener was not successfully removed (for example, if the listener was not on the Mouse object's listener list), the method returns false.

Description

Method; removes an object that was previously registered with addListener().


Mouse.show()

Availability

Flash Player 5.

Usage

Mouse.show()

Parameters

None.

Returns

Nothing.

Description

Method; displays the mouse pointer in a SWF file. The pointer is visible by default.

See also

Mouse.hide(), MovieClip._xmouse, MovieClip._ymouse


MovieClip class

Availability

Flash Player 3.

Description

The methods for the MovieClip class provide the same functionality as actions that target movie clips. There are also additional methods that do not have equivalent actions in the Actions toolbox in the Actions panel.

You do not need to use a constructor method to call the methods of the MovieClip class; instead, you reference movie clip instances by name, using the following syntax:

my_mc.play();
my_mc.gotoAndPlay(3);

Method summary for the MovieClip class

Method | Description
MovieClip.attachAudio() | Captures and plays local audio from the microphone hardware.
MovieClip.attachMovie() | Attaches a SWF file in the library.
MovieClip.createEmptyMovieClip() | Creates an empty movie clip.
MovieClip.createTextField() | Creates an empty text field.
MovieClip.duplicateMovieClip() | Duplicates the specified movie clip.
MovieClip.getBounds() | Returns the minimum and maximum x and y coordinates of a SWF file in a specified coordinate space.
MovieClip.getBytesLoaded() | Returns the number of bytes loaded for the specified movie clip.
MovieClip.getBytesTotal() | Returns the size of the movie clip, in bytes.
MovieClip.getDepth() | Returns the depth of a movie clip.
MovieClip.getInstanceAtDepth() | Specifies whether a particular depth is already occupied by a movie clip.
MovieClip.getNextHighestDepth() | Specifies a depth value that you can pass to other methods to to ensure that Flash renders the movie clip in front of all other objects in the current movie clip.
MovieClip.getSWFVersion() | Returns an integer that indicates the Flash Player version for which the movie clip was published
MovieClip.getTextSnapshot() | Returns a TextSnapshot object that contains the text in the static text fields in the specified movie clip.
MovieClip.getURL() | Retrieves a document from a URL.
MovieClip.globalToLocal() | Converts the point object from Stage coordinates to the local coordinates of the specified movie clip.
MovieClip.gotoAndPlay() | Sends the playhead to a specific frame in the movie clip and plays the SWF file.
MovieClip.gotoAndStop() | Sends the playhead to a specific frame in the movie clip and stops the SWF file.
MovieClip.hitTest() | Returns true if bounding box of the specified movie clip intersects the bounding box of the target movie clip.
MovieClip.loadMovie() | Loads the specified SWF file into the movie clip.
MovieClip.loadVariables() | Loads variables from a URL or other location into the movie clip.
MovieClip.localToGlobal() | Converts a point object from the local coordinates of the movie clip to the global Stage coordinates.
MovieClip.nextFrame() | Sends the playhead to the next frame of the movie clip.
MovieClip.play() | Plays the specified movie clip.
MovieClip.prevFrame() | Sends the playhead to the previous frame of the movie clip.
MovieClip.removeMovieClip() | Removes the movie clip from the Timeline if it was created with duplicateMovieClip(), MovieClip.duplicateMovieClip(), or MovieClip.attachMovie().
MovieClip.setMask() | Specifies a movie clip as a mask for another movie clip.
MovieClip.startDrag() | Specifies a movie clip as draggable and begins dragging the movie clip.
MovieClip.stop() | Stops the currently playing SWF file.
MovieClip.stopDrag() | Stops the dragging of any movie clip that is being dragged.
MovieClip.swapDepths() | Swaps the depth level of two SWF files.
MovieClip.unloadMovie() | Removes a SWF file that was loaded with loadMovie().

Drawing method summary for the MovieClip class

Method | Description
MovieClip.beginFill() | Begins drawing a fill on the Stage.
MovieClip.beginGradientFill() | Begins drawing a gradient fill on the Stage.
MovieClip.clear() | Removes all the drawing commands associated with a movie clip instance.
MovieClip.curveTo() | Draws a curve using the latest line style.
MovieClip.endFill() | Ends the fill specified by beginFill() or beginGradientFill().
MovieClip.lineStyle() | Defines the stroke of lines created with the lineTo() and curveTo() methods.
MovieClip.lineTo() | Draws a line using the current line style.
MovieClip.moveTo() | Moves the current drawing position to specified coordinates.

Property summary for the MovieClip class

Property | Description
MovieClip._alpha | The transparency value of a movie clip instance.
MovieClip._currentframe | The frame number in which the playhead is currently located.
MovieClip._droptarget | The absolute path in slash syntax notation of the movie clip instance on which a draggable movie clip was dropped.
MovieClip.enabled | Indicates whether a button movie clip is enabled.
MovieClip.focusEnabled | Enables a movie clip to receive focus.
MovieClip._focusrect | Indicates whether a focused movie clip has a yellow rectangle around it.
MovieClip._framesloaded | The number of frames that have been loaded from a streaming SWF file.
MovieClip._height | The height of a movie clip instance, in pixels.
MovieClip.hitArea | Designates another movie clip to serve as the hit area for a button movie clip.
MovieClip._highquality | Sets the rendering quality of a SWF file.
MovieClip.menu | Associates a ContextMenu object with a movie clip.
MovieClip._name | The instance name of a movie clip instance.
MovieClip._parent | A reference to the movie clip that encloses the movie clip.
MovieClip._rotation | The degree of rotation of a movie clip instance.
MovieClip._soundbuftime | The number of seconds before a sound starts to stream.
MovieClip.tabChildren | Indicates whether the children of a movie clip are included in automatic tab ordering.
MovieClip.tabEnabled | Indicates whether a movie clip is included in tab ordering.
MovieClip.tabIndex | Indicates the tab order of an object.
MovieClip._target | The target path of a movie clip instance.
MovieClip._totalframes | The total number of frames in a movie clip instance.
MovieClip.trackAsMenu | Indicates whether other buttons can receive mouse release events.
MovieClip._url | The URL of the SWF file from which a movie clip was downloaded.
MovieClip.useHandCursor | Determines whether the hand is displayed when a user rolls over a button movie clip.
MovieClip._visible | A Boolean value that determines whether a movie clip instance is hidden or visible.
MovieClip._width | The width of a movie clip instance, in pixels.
MovieClip._x | The x coordinate of a movie clip instance
MovieClip._xmouse | The x coordinate of the mouse pointer within a movie clip instance.
MovieClip._xscale | The value specifying the percentage for horizontally scaling a movie clip.
MovieClip._y | The y coordinate of a movie clip instance.
MovieClip._ymouse | The y coordinate of the mouse pointer within a movie clip instance.
MovieClip._yscale | The value specifying the percentage for vertically scaling a movie clip.

Event handler summary for the MovieClip class

Event handler | Description
MovieClip.onData | Invoked when all the data is loaded into a movie clip.
MovieClip.onDragOut | Invoked while the pointer is outside the button; the mouse button is pressed inside, and then rolls outside the button area.
MovieClip.onDragOver | Invoked while the pointer is over the button; the mouse button has been pressed then rolled outside the button, and then rolled back over the button.
MovieClip.onEnterFrame | Invoked continually at the frame rate of the SWF file. The actions associated with the enterFrame clip event are processed before any frame actions that are attached to the affected frames.
MovieClip.onKeyDown | Invoked when a key is pressed. Use the Key.getCode() and Key.getAscii() methods to retrieve information about the last key pressed.
MovieClip.onKeyUp | Invoked when a key is released.
MovieClip.onKillFocus | Invoked when focus is removed from a button.
MovieClip.onLoad | Invoked when the movie clip is instantiated and appears in the Timeline.
MovieClip.onMouseDown | Invoked when the left mouse button is pressed.
MovieClip.onMouseMove | Invoked every time the mouse is moved.
MovieClip.onMouseUp | Invoked when the left mouse button is released.
MovieClip.onPress | Invoked when the mouse is pressed while the pointer is over a button.
MovieClip.onRelease | Invoked when the mouse is released while the pointer is over a button.
MovieClip.onReleaseOutside | Invoked when the mouse is released while the pointer is outside the button after the button is pressed while the pointer is inside the button.
MovieClip.onRollOut | Invoked when the pointer rolls outside of a button area.
MovieClip.onRollOver | Invoked when the mouse pointer rolls over a button.
MovieClip.onSetFocus | Invoked when a button has input focus and a key is released.
MovieClip.onUnload | Invokes in the first frame after the movie clip is removed from the Timeline. The actions associated with the Unload movie clip event are processed before any actions are attached to the affected frame.


MovieClip._alpha

Availability

Flash Player 4.

Usage

my_mc._alpha

Description

Property; the alpha transparency value of the movie clip specified by my_mc. Valid values are 0 (fully transparent) to 100 (fully opaque). The default value is 100. Objects in a movie clip with _alpha set to 0 are active, even though they are invisible. For example, you can still click a button in a movie clip whose _alpha property is set to 0.

Example

The following code sets the _alpha property of a movie clip named star_mc to 30% when the button is clicked:

on(release) {
  star_mc._alpha = 30;
}

See also

Button._alpha, TextField._alpha


MovieClip.attachAudio()

Availability

Flash Player 6; the ability to attach audio from Flash Video (FLV) files was added in Flash Player 7.

Usage

my_mc.attachAudio(source)

Parameters

source The object containing the audio to play. Valid values are a Microphone object, a NetStream object that is playing an FLV file, and false (stops playing the audio).

Returns

Nothing.

Description

Method; specifies the audio source to be played. To stop playing the audio source, pass false for source.

Example

The following code attaches a microphone to a movie clip.

active_mic = Microphone.get();
this.attachAudio(active_mic);

The following example shows how you can use a Sound object to control the sound associated with an FLV file.

// Clip is the instance name of the movie clip
// that contains the video object "my_video".
_root.Clip.my_video.attachVideo(_root.myNetStream);
_root.Clip.attachAudio(_root.myNetStream);
var snd = new Sound("_root.Clip");
//To adjust the audio:
_root.snd.setVolume(100);

See also

Microphone class, NetStream.play(), Sound class, Video.attachVideo()


MovieClip.attachMovie()

Availability

Flash Player 5.

Usage

my_mc.attachMovie(idName, newName, depth [, initObject])

Parameters

idName The linkage name of the movie clip symbol in the library to attach to a movie clip on the Stage. This is the name entered in the Identifier field in the Linkage Properties dialog box.

newname A unique instance name for the movie clip being attached to the movie clip.

depth An integer specifying the depth level where the SWF file is placed.

initObject (Supported for Flash Player 6 and later) An object containing properties with which to populate the newly attached movie clip. This parameter allows dynamically created movie clips to receive clip parameters. If initObject is not an object, it is ignored. All properties of initObject are copied into the new instance. The properties specified with initObject are available to the constructor function. This parameter is optional.

Returns

A reference to the newly created instance.

Description

Method; takes a symbol from the library and attaches it to the SWF file on the Stage specified by my_mc. Use removeMovieClip() or unloadMovie() to remove a SWF file attached with attachMovie().

Example

The following example attaches the symbol with the linkage identifier "circle" to the movie clip instance, which is on the Stage in the SWF file.

on (release) {
    thing.attachMovie( "circle", "circle1", 2 );
}

See also

MovieClip.removeMovieClip(), MovieClip.unloadMovie(), Object.registerClass(), removeMovieClip()


MovieClip.beginFill()

Availability

Flash Player 6.

Usage

my_mc.beginFill([rgb[, alpha]])

Parameter

rgb A hex color value (for example, red is 0xFF0000, blue is 0x0000FF, and so on). If this value is not provided or is undefined, a fill is not created.

alpha An integer between 0-100 that specifies the alpha value of the fill. If this value is not provided, 100 (solid) is used. If the value is less than 0, Flash uses 0. If the value is greater than 100, Flash uses 100.

Returns

Nothing.

Description

Method; indicates the beginning of a new drawing path. If an open path exists (that is, if the current drawing position does not equal the previous position specified in a moveTo() method) and it has a fill associated with it, that path is closed with a line and then filled. This is similar to what happens when endFill() is called. If no fill is currently associated with the path, endFill() must be called in order to apply the fill.

See also

MovieClip.beginGradientFill(), MovieClip.endFill()


MovieClip.beginGradientFill()

Availability

Flash Player 6.

Usage

my_mc.beginGradientFill(fillType, colors, alphas, ratios, matrix)

Parameter

fillType Either the string "linear" or the string "radial".

colors An array of RGB hex color values to be used in the gradient (for example, red is 0xFF0000, blue is 0x0000FF, and so on).

alphas An array of alpha values for the corresponding colors in the colors array; valid values are 0-100. If the value is less than 0, Flash uses 0. If the value is greater than 100, Flash uses 100.

ratios An array of color distribution ratios; valid values are 0-255. This value defines the percentage of the width where the color is sampled at 100 percent.

matrix A transformation matrix that is an object with either of the following two sets of properties.

  • a, b, c, d, e, f, g, h, i, which can be used to describe a 3 x 3 matrix of the following form:
    a   b   c
d   e   f
g   h i

    The following example uses a beginGradientFill() method with a matrix parameter that is an object with these properties.

    _root.createEmptyMovieClip( "grad", 1 );
  with ( _root.grad )

  {

  colors = [ 0xFF0000, 0x0000FF ];
  alphas = [ 100, 100 ];
  ratios = [ 0, 0xFF ];
  matrix = { a:200, b:0, c:0, d:0, e:200, f:0, g:200, h:200, i:1 };
  beginGradientFill( "linear", colors, alphas, ratios, matrix );
  moveto(100,100);
  lineto(100,300);
  lineto(300,300);
  lineto(300,100);
  lineto(100,100);
  endFill();

  }

    If a matrixType property does not exist then the remaining parameters are all required; the function fails if any of them are missing. This matrix scales, translates, rotates, and skews the unit gradient, which is defined at (-1,-1) and (1,1).

  • matrixType, x, y, w, h, r.

    The properties indicate the following: matrixType is the string "box", x is the horizontal position relative to the registration point of the parent clip for the upper left corner of the gradient, y is the vertical position relative to the registration point of the parent clip for the upper left corner of the gradient, w is the width of the gradient, h is the height of the gradient, and r is the rotation in radians of the gradient.

    The following example uses a beginGradientFill() method with a matrix parameter that is an object with these properties.

    _root.createEmptyMovieClip( "grad", 1 );
              with ( _root.grad )

              {

              colors = [ 0xFF0000, 0x0000FF ];
              alphas = [ 100, 100 ];
              ratios = [ 0, 0xFF ];
              matrix = { matrixType:"box", x:100, y:100, w:200, h:200, r:(45/180)*Math.PI };
              beginGradientFill( "linear", colors, alphas, ratios, matrix );
              moveto(100,100);
              lineto(100,300);
              lineto(300,300);
              lineto(300,100);
              lineto(100,100);
              endFill();
              }

If a matrixType property exists then it must equal "box" and the remaining parameters are all required. The function fails if any of these conditions are not met.

Returns

Nothing.

Description

Method; indicates the beginning of a new drawing path. If the first parameter is undefined, or if no parameters are passed, the path has no fill. If an open path exists (that is if the current drawing position does not equal the previous position specified in a moveTo() method), and it has a fill associated with it, that path is closed with a line and then filled. This is similar to what happens when you call endFill().

This method fails if any of the following conditions exist:

  • The number of items in the colors, alphas, and ratios parameters are not equal.
  • The fillType parameter is not "linear" or "radial".
  • Any of the fields in the object for the matrix parameter are missing or invalid.

Example

The following code uses both methods to draw two stacked rectangles with a red-blue gradient fill and a 5-pt. solid green stroke.

_root.createEmptyMovieClip("goober",1);
with ( _root.goober )
{
  colors = [ 0xFF0000, 0x0000FF ];
  alphas = [ 100, 100 ];
  ratios = [ 0, 0xFF ];
  lineStyle( 5, 0x00ff00 );
  matrix = { a:500,b:0,c:0,d:0,e:200,f:0,g:350,h:200,i:1};
  beginGradientFill( "linear", colors, alphas, ratios, matrix );
  moveto(100,100);
  lineto(100,300);
  lineto(600,300);
  lineto(600,100);
  lineto(100,100);
  endFill();
  matrix = { matrixType:"box", x:100, y:310, w:500, h:200, r:(0/180)*Math.PI };
  beginGradientFill( "linear", colors, alphas, ratios, matrix );
  moveto(100,310);
  lineto(100,510);
  lineto(600,510);
  lineto(600,310);
  lineto(100,310);
  endFill();
}

See also

MovieClip.beginFill(), MovieClip.endFill(), MovieClip.lineStyle(), MovieClip.lineTo(), MovieClip.moveTo()


MovieClip.clear()

Availability

Flash Player 6.

Usage

my_mc.clear()

Parameters

None.

Returns

Nothing.

Description

Method; removes all the graphics created during runtime using the movie clip draw methods, including line styles specified with MovieClip.lineStyle(). Shapes and lines that are manually drawn during authoring time (with the Flash drawing tools) are unaffected.

See also

MovieClip.lineStyle()


MovieClip.createEmptyMovieClip()

Availability

Flash Player 6.

Usage

my_mc.createEmptyMovieClip(instanceName, depth)

Parameters

instanceName A string that identifies the instance name of the new movie clip.

depth An integer that specifies the depth of the new movie clip.

Returns

A reference to the newly created movie clip.

Description

Method; creates an empty movie clip as a child of an existing movie clip. This method behaves similarly to the attachMovie() method, but you don't need to provide an external linkage name for the new movie clip. The registration point for a newly created empty movie clip is the upper left corner. This method fails if any of the parameters are missing.

See also

MovieClip.attachMovie()


MovieClip.createTextField()

Availability

Flash Player 6.

Usage

my_mc.createTextField(instanceName, depth, x, y, width, height)

Parameters

instanceName A string that identifies the instance name of the new text field.

depth A positive integer that specifies the depth of the new text field.

x An integer that specifies the x coordinate of the new text field.

y An integer that specifies the y coordinate of the new text field.

width A positive integer that specifies the width of the new text field.

height A positive integer that specifies the height of the new text field.

Returns

Nothing.

Description

Method; creates a new, empty text field as a child of the movie clip specified by my_mc. You can use createTextField() to create text fields while a SWF file plays. The text field is positioned at (x, y) with dimensions width by height. The x and y parameters are relative to the container movie clip; these parameters correspond to the _x and _y properties of the text field. The width and height parameters correspond to the _width and _height properties of the text field.

The default properties of a text field are as follows:

type = "dynamic"
border = false
background = false
password = false
multiline = false
html = false
embedFonts = false
variable = null
maxChars = null

A text field created with createTextField() receives the following default TextFormat object:

font = "Times New Roman"
size = 12
textColor = 0x000000
bold = false
italic = false
underline = false
url = ""
target = ""
align = "left"
leftMargin = 0
rightMargin = 0
indent = 0
leading = 0
bullet = false
tabStops = [] (empty array)

Example

The following example creates a text field with a width of 300, a height of 100, an x coordinate of 100, a y coordinate of 100, no border, red, and underlined text.

_root.createTextField("mytext",1,100,100,300,100);
mytext.multiline = true;
mytext.wordWrap = true;
mytext.border = false;

myformat = new TextFormat();
myformat.color = 0xff0000;
myformat.bullet = false;
myformat.underline = true;

mytext.text = "this is my first test field object text";
mytext.setTextFormat(myformat);

See also

TextFormat class


MovieClip._currentframe

Availability

Flash Player 4.

Usage

my_mc._currentframe

Description

Property (read-only); returns the number of the frame in which the playhead is located in the Timeline specified by my_mc.

Example

The following example uses the _currentframe property to direct the playhead of the movie clip actionClip_mc to advance five frames ahead of its current location.

actionClip_mc.gotoAndStop(_currentframe + 5);


MovieClip.curveTo()

Availability

Flash Player 6.

Usage

my_mc.curveTo(controlX, controlY, anchorX, anchorY)

Parameters

controlX An integer that specifies a horizontal position relative to the registration point of the parent movie clip of the control point.

controlY An integer that specifies a vertical position relative to the registration point of the parent movie clip of the control point.

anchorX An integer that specifies a horizontal position relative to the registration point of the parent movie clip of the next anchor point.

anchorY An integer that specifies a vertical position relative to the registration point of the parent movie clip of the next anchor point.

Returns

Nothing.

Description

Method; draws a curve using the current line style from the current drawing position to (anchorX, anchorY) using the control point specified by (controlX, controlY). The current drawing position is then set to (anchorX, anchorY). If the movie clip you are drawing in contains content created with the Flash drawing tools, calls to curveTo() are drawn underneath this content. If you call curveTo() before any calls to moveTo(), the current drawing position defaults to (0, 0). If any of the parameters are missing, this method fails and the current drawing position is not changed.

Example

The following example draws a circle with a hairline point, solid blue line, and a solid red fill.

_root.createEmptyMovieClip( "circle", 1 );
with ( _root.circle )
{
  lineStyle( 0, 0x0000FF, 100 );
  beginFill( 0xFF0000 );
  moveTo( 500, 500 );
  curveTo( 600, 500, 600, 400 );
  curveTo( 600, 300, 500, 300 );
  curveTo( 400, 300, 400, 400 );
  curveTo( 400, 500, 500, 500 );
  endFill();
}

See also

MovieClip.beginFill(), MovieClip.createEmptyMovieClip(), MovieClip.endFill(), MovieClip.lineStyle(), MovieClip.lineTo(), MovieClip.moveTo()


MovieClip._droptarget

Availability

Flash Player 4.

Usage

my_mc._droptarget

Description

Property (read-only); returns the absolute path in slash syntax notation of the movie clip instance on which my_mc was dropped. The _droptarget property always returns a path that starts with a slash (/). To compare the _droptarget property of an instance to a reference, use the eval() function to convert the returned value from slash syntax to a dot syntax reference.

Note: You must perform this conversion if you are using ActionScript 2.0, which does not support slash syntax.

Example

The following example evaluates the _droptarget property of the garbage movie clip instance and uses eval() to convert it from slash syntax to a dot syntax reference. The garbage reference is then compared to the reference to the trash movie clip instance. If the two references are equivalent, the visibility of garbage is set to false. If they are not equivalent, the garbage instance is reset to its original position.

if (eval(garbage._droptarget) == _root.trash) {
  garbage._visible = false;
} else {
  garbage._x = x_pos;
  garbage._y = y_pos;
}

The variables x_pos and y_pos are set on Frame 1 of the SWF file with the following script:

x_pos = garbage._x;
y_pos = garbage._y;

See also

startDrag()


MovieClip.duplicateMovieClip()

Availability

Flash Player 5.

Usage

my_mc.duplicateMovieClip(newname, depth [,initObject])

Parameters

newname A unique identifier for the duplicate movie clip.

depth A unique number specifying the depth at which the SWF file specified is to be placed.

initObject (Supported for Flash Player 6 and later.) An object containing properties with which to populate the duplicated movie clip. This parameter allows dynamically created movie clips to receive clip parameters. If initObject is not an object, it is ignored. All properties of initObject are copied into the new instance. The properties specified with initObject are available to the constructor function. This parameter is optional.

Returns

A reference to the duplicated movie clip.

Description

Method; creates an instance of the specified movie clip while the SWF file is playing. Duplicated movie clips always start playing at Frame 1, no matter what frame the original movie clip is on when the duplicateMovieClip() method is called. Variables in the parent movie clip are not copied into the duplicate movie clip. Movie clips that have been created using duplicateMovieClip() are not duplicated if you call duplicateMovieClip() on their parent. If the parent movie clip is deleted, the duplicate movie clip is also deleted. .

See also

duplicateMovieClip(), MovieClip.removeMovieClip()


MovieClip.enabled

Availability

Flash Player 6.

Usage

my_mc.enabled

Description

Property; a Boolean value that indicates whether a button movie clip is enabled. The default value of enabled is true. If enabled is set to false, the button movie clip's callback methods and on action event handlers are no longer invoked, and the Over, Down, and Up frames are disabled. The enabled property does not affect the Timeline of the button movie clip; if a movie clip is playing, it continues to play. The movie clip continues to receive movie clip events (for example, mouseDown, mouseUp, keyDown, and keyUp).

The enabled property only governs the button-like properties of a button movie clip. You can change the enabled property at any time; the modified button movie clip is immediately enabled or disabled. The enabled property can be read out of a prototype object. If enabled is set to false, the object is not included in automatic tab ordering.


MovieClip.endFill()

Availability

Flash Player 6.

Usage

my_mc.endFill()

Parameters

None.

Returns

Nothing.

Description

Method; applies a fill to the lines and curves added since the last call to beginFill() or beginGradientFill(). Flash uses the fill that was specified in the previous call to beginFill() or beginGradientFill(). If the current drawing position does not equal the previous position specified in a moveTo() method and a fill is defined, the path is closed with a line and then filled.


MovieClip.focusEnabled

Availability

Flash Player 6.

Usage

my_mc.focusEnabled

Description

Property; if the value is undefined or false, a movie clip cannot receive input focus unless it is a button movie clip. If the focusEnabled property value is true, a movie clip can receive input focus even if it is not a button movie clip.


MovieClip._focusrect

Availability

Flash Player 6.

Usage

my_mc._focusrect

Description

Property; a Boolean value that specifies whether a movie clip has a yellow rectangle around it when it has keyboard focus. This property can override the global _focusrect property.


MovieClip._framesloaded

Availability

Flash Player 4.

Usage

my_mc._framesloaded

Description

Property (read-only); the number of frames that have been loaded from a streaming SWF file. This property is useful for determining whether the contents of a specific frame, and all the frames before it, have loaded and are available locally in the browser. This property is useful for monitoring the downloading of large SWF files. For example, you might want to display a message to users indicating that the SWF file is loading until a specified frame in the SWF file has finished loading.

Example

The following example uses the _framesloaded property to start a SWF file when all the frames are loaded. If all the frames aren't loaded, the _xscale property of the movie clip instance loader is increased proportionally to create a progress bar.

if (_framesloaded >= _totalframes) {
  gotoAndPlay ("Scene 1", "start");
} else {
  _root.loader._xscale = (_framesloaded/_totalframes)*100;
}

See also

MovieClipLoader class


MovieClip.getBounds()

Availability

Flash Player 5.

Usage

my_mc.getBounds(targetCoordinateSpace)

Parameters

targetCoordinateSpace The target path of the Timeline whose coordinate system you want to use as a reference point.

Returns

An object with the properties xMin, xMax, yMin, and yMax.

Description

Method; returns properties that are the minimum and maximum x and y coordinate values of the instance specified by my_mc for the targetCoordinateSpace parameter.

Note: Use MovieClip.localToGlobal() and MovieClip.globalToLocal() to convert the movie clip's local coordinates to Stage coordinates, or Stage coordinates to local coordinates, respectively.

Example

In the following example, the object that getBounds() returns is assigned to the identifier clipBounds. You can then access the values of each property and use them in a script. In this script, another movie clip instance, clip2, is placed alongside clip.

clipBounds = clip.getBounds(_root);
clip2._x = clipBounds.xMax;

See also

MovieClip.globalToLocal(), MovieClip.localToGlobal()


MovieClip.getBytesLoaded()

Availability

Flash Player 5.

Usage

my_mc.getBytesLoaded()

Parameters

None.

Returns

An integer indicating the number of bytes loaded.

Description

Method; returns the number of bytes that have already loaded (streamed) for the movie clip specified by my_mc. You can compare this value with the value returned by MovieClip.getBytesTotal() to determine what percentage of a movie clip has loaded.

See also

MovieClip.getBytesTotal()


MovieClip.getBytesTotal()

Availability

Flash Player 5.

Usage

my_mc.getBytesTotal()

Parameters

None.

Returns

An integer indicating the total size, in bytes, of my_mc.

Description

Method; returns the size, in bytes, of the movie clip specified by my_mc. For movie clips that are external (the root SWF file or a movie clip that is being loaded into a target or a level), the return value is the size of the SWF file.

See also

MovieClip.getBytesLoaded()


MovieClip.getDepth()

Availability

Flash Player 6.

Usage

my_mc.getDepth()

Parameters

None.

Returns

An integer.

Description

Method; returns the depth of a movie clip instance. For more information, see Managing movie clip depths.

See also

MovieClip.getInstanceAtDepth(), MovieClip.getNextHighestDepth(), MovieClip.swapDepths()


MovieClip.getInstanceAtDepth()

Availability

Flash Player 7.

Usage

my_mc.getInstanceAtDepth(depth)

Parameters

depth An integer that specifies the depth level to query.

Returns

A reference to the MovieClip instance located at the specified depth, or undefined if there is no movie clip at that depth.

Description

Method; lets you determine if a particular depth is already occupied by a movie clip. You can use this method before using MovieClip.attachMovie(), MovieClip.duplicateMovieClip(), or MovieClip.createEmptyMovieClip() to determine if the depth parameter you want to pass to any of these methods already contains a movie clip. For more information, see Managing movie clip depths.

See also

MovieClip.getDepth(), MovieClip.getNextHighestDepth(), MovieClip.swapDepths()


MovieClip.getNextHighestDepth()

Availability

Flash Player 7.

Usage

my_mc.getNextHighestDepth()

Parameters

None.

Returns

An integer that reflects the next available depth index that would render above all other objects on the same level and layer within my_mc.

Description

Method; lets you determine a depth value that you can pass to MovieClip.attachMovie(), MovieClip.duplicateMovieClip(), or MovieClip.createEmptyMovieClip() to ensure that Flash renders the movie clip in front of all other objects on the same level and layer in the current movie clip. The value returned is 0 or higher (that is, negative numbers are not returned).

For more information, see Managing movie clip depths.

See also

MovieClip.getDepth(), MovieClip.getInstanceAtDepth(), MovieClip.swapDepths()


MovieClip.getSWFVersion()

Availability

Flash Player 7.

Usage

my_mc.getSWFVersion()

Parameters

None.

Returns

An integer that specifies the Flash Player version that was targeted when the SWF file loaded into my_mc was published.

Description

Method; returns an integer that indicates the Flash Player version for which my_mc was published. If my_mc is a JPEG file, or if an error occurs and Flash can't determine the SWF version of my_mc, -1 is returned.


MovieClip.getTextSnapshot()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

my_mc.getTextSnapshot();

Parameters

None.

Returns

A TextSnapshot object that contains the static text from my_mc, or an empty string if my_mc contains no static text.

Description

Method; returns a TextSnapshot object that contains the text in all the static text fields in the specified movie clip; text in child movie clips is not included.

Flash concatenates text and places it in the TextSnapshot object in an order that reflects the tab index order of the static text fields in the movie clip. Text fields that don't have tab index values are placed in a random order in the object, and precede any text from fields that do have tab index values. No line breaks or formatting indicates where one field ends and the next begins.

Note: You can't specify a tab index value for static text in Flash. However, other products may do so; for example, Macromedia FlashPaper.

The contents of the TextSnapshot object aren't dynamic; that is, if the movie clip moves to a different frame, or is altered in some way (for example, objects in the movie clip are added or removed), the TextSnapshot object might not represent the current text in the movie clip. To ensure that the object's contents are current, reissue this command as needed.

See also

TextSnapshot object


MovieClip.getURL()

Availability

Flash Player 5.

Usage

my_mc.getURL(URL [,window, variables])

Parameters

URL The URL from which to obtain the document.

window An optional parameter specifying the name, frame, or expression that specifies the window or HTML frame that the document is loaded into. You can also use one of the following reserved target names: _self specifies the current frame in the current window, _blank specifies a new window, _parent specifies the parent of the current frame, and _top specifies the top-level frame in the current window.

variables An optional parameter specifying a method for sending variables associated with the SWF file to load. If there are no variables, omit this parameter; otherwise, specify whether to load variables using a GET or POST method. GET appends the variables to the end of the URL and is used for a small numbers of variables. POST sends the variables in a separate HTTP header and is used for long strings of variables.

Returns

Nothing.

Description

Method; loads a document from the specified URL into the specified window. The getURL method can also be used to pass variables to another application defined at the URL using a GET or POST method.

See also

getURL()


MovieClip.globalToLocal()

Availability

Flash Player 5.

Usage

my_mc.globalToLocal(point)

Parameters

point The name or identifier of an object created with the generic Object class. The object specifies the x and y coordinates as properties.

Returns

Nothing.

Description

Method; converts the point object from Stage (global) coordinates to the movie clip's (local) coordinates.

Example

The following example converts the global x and y coordinates of the point object to the local coordinates of the movie clip.

onClipEvent(mouseMove) {
  point = new object();
  point.x = _root._xmouse;
  point.y = _root._ymouse;
  globalToLocal(point);
  trace(_root._xmouse + " " + _root._ymouse);
  trace(point.x + " " + point.y);
  updateAfterEvent();
}

See also

MovieClip.getBounds(), MovieClip.localToGlobal()


MovieClip.gotoAndPlay()

Availability

Flash Player 5.

Usage

my_mc.gotoAndPlay(frame)

Parameters

frame A number representing the frame number, or a string representing the label of the frame, to which the playhead is sent.

Returns

Nothing.

Description

Method; starts playing the SWF file at the specified frame. If you want to specify a scene as well as a frame, use gotoAndPlay().

See also

gotoAndPlay(), play()


MovieClip.gotoAndStop()

Availability

Flash Player 5.

Usage

my_mc.gotoAndStop(frame)

Parameters

frame The frame number to which the playhead is sent.

Returns

Nothing.

Description

Method; brings the playhead to the specified frame of the movie clip and stops it there. If you want to specify a scene in addition to a frame, use gotoAndStop().

See also

gotoAndStop(), stop()


MovieClip._height

Availability

Flash Player 4.

Usage

my_mc._height

Description

Property; the height of the movie clip, in pixels.

Example

The following code example sets the height and width of a movie clip when the user clicks the mouse button.

onClipEvent(mouseDown) {
  _width=200;
  _height=200;
}


MovieClip._highquality

Availability

Flash Player 6.

Usage

my_mc._highquality

Description

Property (global); specifies the level of anti-aliasing applied to the current SWF file. Specify 2 (best quality) to apply high quality with bitmap smoothing always on. Specify 1 (high quality) to apply anti-aliasing; this will smooth bitmaps if the SWF file does not contain animation. Specify 0 (low quality) to prevent anti-aliasing. This property can overwrite the global _highquality property.

Example

my_mc._highquality = 2;

See also

_quality


MovieClip.hitArea

Availability

Flash Player 6.

Usage

my_mc.hitArea

Returns

A reference to a movie clip.

Description

Property; designates another movie clip to serve as the hit area for a button movie clip. If the hitArea property does not exist or is null or undefined, the button movie clip itself is used as the hit area. The value of the hitArea property may be a reference to a movie clip object.

You can change the hitArea property at any time; the modified button movie clip immediately takes on the new hit area behavior. The movie clip designated as the hit area does not need to be visible; its graphical shape, although not visible, is hit-tested. The hitArea property can be read out of a prototype object.


MovieClip.hitTest()

Availability

Flash Player 5.

Usage

my_mc.hitTest(x, y, shapeFlag)
my_mc.hitTest(target)

Parameters

x The x coordinate of the hit area on the Stage.

y The y coordinate of the hit area on the Stage.

The x and y coordinates are defined in the global coordinate space.

target The target path of the hit area that may intersect or overlap with the instance specified by my_mc. The target parameter usually represents a button or text-entry field.

shapeFlag A Boolean value specifying whether to evaluate the entire shape of the specified instance (true), or just the bounding box (false). This parameter can be specified only if the hit area is identified using x and y coordinate parameters.

Returns

A Boolean value of true if my_mc overlaps with the specified hit area, false otherwise.

Description

Method; evaluates the instance specified by my_mc to see if it overlaps or intersects with the hit area identified by the target or x and y coordinate parameters.

Usage 1: Compares the x and y coordinates to the shape or bounding box of the specified instance, according to the shapeFlag setting. If shapeFlag is set to true, only the area actually occupied by the instance on the Stage is evaluated, and if x and y overlap at any point, a value of true is returned. This is useful for determining if the movie clip is within a specified hit or hotspot area.

Usage 2: Evaluates the bounding boxes of the target and specified instance, and returns true if they overlap or intersect at any point.

Example

The following example uses hitTest() with the _xmouse and _ymouse properties to determine whether the mouse pointer is over the target's bounding box:

if (hitTest( _root._xmouse, _root._ymouse, false));

The following example uses hitTest() to determine if the movie clip ball overlaps or intersects the movie clip square:

if(_root.ball.hitTest(_root.square)){
  trace("ball intersects square");
}

See also

MovieClip.getBounds(), MovieClip.globalToLocal(), MovieClip.localToGlobal()


MovieClip.lineStyle()

Availability

Flash Player 6.

Usage

my_mc.lineStyle([thickness[, rgb[, alpha]]])

Parameters

thickness An integer that indicates the thickness of the line in points; valid values are 0 to 255. If a number is not specified, or if the parameter is undefined, a line is not drawn. If a value of less than 0 is passed, Flash uses 0. The value 0 indicates hairline thickness; the maximum thickness is 255. If a value greater than 255 is passed, the Flash interpreter uses 255.

rgb A hex color value (for example, red is 0xFF0000, blue is 0x0000FF, and so on) of the line. If a value isn't indicated, Flash uses 0x000000 (black).

alpha An integer that indicates the alpha value of the line's color; valid values are 0-100. If a value isn't indicated, Flash uses 100 (solid). If the value is less than 0, Flash uses 0; if the value is greater than 100, Flash uses 100.

Returns

Nothing.

Description

Method; specifies a line style that Flash uses for subsequent calls to lineTo() and curveTo() until you call lineStyle() with different parameters. You can call lineStyle() in the middle of drawing a path to specify different styles for different line segments within a path.

Note: Calls to clear reset lineStyle() back to undefined.

Example

The following code draws a triangle with a 5-point, solid magenta line and no fill.

_root.createEmptyMovieClip( "triangle", 1 );
with ( _root.triangle )
{
lineStyle( 5, 0xff00ff, 100 );
moveTo( 200, 200 );
lineTo( 300,300 );
lineTo( 100, 300 );
lineTo( 200, 200 );
}

See also

MovieClip.beginFill(), MovieClip.beginGradientFill(), MovieClip.clear(), MovieClip.curveTo(), MovieClip.lineTo(), MovieClip.moveTo()


MovieClip.lineTo()

Availability

Flash Player 6.

Usage

my_mc.lineTo(x, y)

Parameters

x An integer indicating the horizontal position relative to the registration point of the parent movie clip.

y An integer indicating the vertical position relative to the registration point of the parent movie clip.

Returns

Nothing.

Description

Method; draws a line using the current line style from the current drawing position to (x, y); the current drawing position is then set to (x, y). If the movie clip that you are drawing in contains content that was created with the Flash drawing tools, calls to lineTo() are drawn underneath the content. If you call lineTo() before any calls to the moveTo() method, the current drawing position defaults to (0, 0). If any of the parameters are missing, this method fails and the current drawing position is not changed.

Example

The following example draws a triangle with no lines and a partially transparent blue fill.

_root.createEmptyMovieClip ("triangle", 1);
  with (_root.triangle){
    beginFill (0x0000FF, 50);
    lineStyle (5, 0xFF00FF, 100);
    moveTo (200, 200);
    lineTo (300, 300);
    lineTo (100, 300);
    lineTo (200, 200);
    endFill();
}

See also

MovieClip.beginFill(), MovieClip.createEmptyMovieClip(), MovieClip.endFill(), MovieClip.lineStyle(), MovieClip.moveTo()


MovieClip.loadMovie()

Availability

Flash Player 5.

Usage

my_mc.loadMovie("url" [,variables])

Parameters

url The absolute or relative URL of the SWF file or JPEG file to be loaded. A relative path must be relative to the SWF file at level 0. Absolute URLs must include the protocol reference, such as http:// or file:///.

variables An optional parameter specifying an HTTP method for sending or loading variables. The parameter must be the string GET or POST. If there are no variables to be sent, omit this parameter. The GET method appends the variables to the end of the URL and is used for small numbers of variables. The POST method sends the variables in a separate HTTP header and is used for long strings of variables.

Returns

Nothing.

Description

Method; loads SWF or JPEG files into a movie clip in Flash Player while the original SWF file is playing.

Tip: If you want to monitor the progress of the download, use MovieClipLoader.loadClip() instead of this function.

Without the loadMovie() method, Flash Player displays a single SWF file and then closes. The loadMovie() method lets you display several SWF files at once and switch between SWF files without loading another HTML document.

A SWF file or image loaded into a movie clip inherits the position, rotation, and scale properties of the movie clip. You can use the target path of the movie clip to target the loaded SWF file.

Use the unloadMovie() method to remove SWF files or images loaded with the loadMovie() method. Use the loadVariables() method to keep the active SWF file, and update the variables with new values.

See also

loadMovie(), loadMovieNum(), MovieClip.loadVariables(), MovieClip.unloadMovie(), unloadMovie(), unloadMovieNum()


MovieClip.loadVariables()

Availability

Flash Player 5; behavior changed in Flash Player 7.

Usage

my_mc.loadVariables("url", variables)

Parameters

url The absolute or relative URL for the external file that contains the variables to be loaded. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see "Description," below.

variables An optional parameter specifying an HTTP method for sending variables. The parameter must be the string GET or POST. If there are no variables to be sent, omit this parameter. The GET method appends the variables to the end of the URL and is used for small numbers of variables. The POST method sends the variables in a separate HTTP header and is used for long strings of variables.

Returns

Nothing.

Description

Method; reads data from an external file and sets the values for variables in my_mc. The external file can be a text file generated by a CGI script, Active Server Page (ASP), or PHP script and can contain any number of variables.

This method can also be used to update variables in the active movie clip with new values.

This method requires that the text of the URL be in the standard MIME format: application/x-www-form-urlencoded (CGI script format).

In SWF files running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.com can load variables from a SWF file at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

In SWF files of any version running in Flash Player 7 or later, url must be in exactly the same domain (see Flash Player security features). For example, a SWF file at www.someDomain.com can load variables only from SWF files that are also at www.someDomain.com. If you want to load variables from a different domain, you can place a cross-domain policy file on the server hosting the SWF file that is being accessed. For more information, see About allowing cross-domain data loading.

See also

loadMovie(), loadVariables(), loadVariablesNum(), MovieClip.unloadMovie()


MovieClip.localToGlobal()

Availability

Flash Player 5.

Usage

my_mc.localToGlobal(point)

Parameters

point The name or identifier of an object created with the Object class, specifying the x and y coordinates as properties.

Returns

Nothing.

Description

Method; converts the point object from the movie clip's (local) coordinates to the Stage (global) coordinates.

Example

The following example converts x and y coordinates of the point object, from the movie clip's (local) coordinates to the Stage (global) coordinates. The local x and y coordinates are specified using the _xmouse and _ymouse properties to retrieve the x and y coordinates of the mouse pointer position.

onClipEvent(mouseMove) {
  point = new object();
  point.x = _xmouse;
  point.y = _ymouse;
  _root.out3 = point.x + " === " + point.y;
  _root.out = _root._xmouse + " === " + _root._ymouse;
  localToGlobal(point);
  _root.out2 = point.x + " === " + point.y;
  updateAfterEvent();
}

See also

MovieClip.globalToLocal()


MovieClip._lockroot

Availability

Flash Player 7.

Usage

my_mc._lockroot

Description

Property; specifies what _root refers to when a SWF file is loaded into a movie clip. The _lockroot property is undefined by default. You can set this property within the SWF file that is being loaded or in the handler that is loading the movie clip.

For example, suppose you have a document called Games.fla that lets a user choose a game to play, and loads the game (for example, Chess.swf) into the game_mc movie clip. You want to make sure that, if _root is used in Chess.swf, it still refers to _root in Chess.swf after being loaded into Games.swf. If you have access to Chess.fla and publish it to Flash Player 7 or later, you can add this statement to it:

this._lockroot = true;

If you don't have access to Chess.fla (for example, if you are loading Chess.swf from someone else's site), you can set its _lockroot property when you load it, as shown below. In this case, Chess.swf can be published for any version of Flash Player, as long as Games.swf is published for Flash Player 7 or later.

  onClipEvent (load)
  {
    this._lockroot = true;
  }
  game_mc.loadMovie ("Chess.swf");

If you didn't use the this._lockroot = true statement in either of the SWF files, _root in Chess.swf would refer to _root in Games.swf after Chess.swf is loaded into Games.swf.

See also

MovieClip.attachMovie(), MovieClip.loadMovie(), MovieClipLoader.onLoadInit(), _root


MovieClip.menu

Availability

Flash Player 7.

Usage

my_mc.menu = contextMenu

Parameters

contextMenu A ContextMenu object.

Description

Property; associates the specified ContextMenu object with the movie clip my_mc. The ContextMenu class lets you modify the context menu that appears when the user right-clicks (Windows) or Control-clicks (Macintosh) in Flash Player.

Example

The following example assigns the ContextMenu object menu_cm to the movie clip content_mc. The ContextMenu object contains a custom menu item labeled "Print..." that has an associated callback handler named doPrint().

var menu_cm = new ContextMenu();
menu_cm.customItems.push(new ContextMenuItem("Print...", doPrint));
function doPrint(menu, obj) {
  // "Print" code here
}
content_mc.menu = menu_cm;

See also

Button.menu, ContextMenu class, ContextMenuItem class, TextField.menu


MovieClip.moveTo()

Availability

Flash Player 6.

Usage

my_mc.moveTo(x, y)

Parameters

x An integer indicating the horizontal position relative to the registration point of the parent movie clip.

y An integer indicating the vertical position relative to the registration point of the parent movie clip.

Returns

Nothing.

Description

Method; moves the current drawing position to (x, y). If any of the parameters are missing, this method fails and the current drawing position is not changed.

Example

This example draws a triangle with 5-point, solid magenta lines and no fill. The first line creates an empty movie clip to draw with. Inside the with statement, a line type is defined; then the starting drawing position is indicated by the moveTo() method.

_root.createEmptyMovieClip( "triangle", 1 );
with ( _root.triangle )
{
lineStyle( 5, 0xff00ff, 100 );
moveTo( 200, 200 );
lineTo( 300,300 );
lineTo( 100, 300 );
lineTo( 200, 200 );
}

See also

MovieClip.createEmptyMovieClip(), MovieClip.lineStyle(), MovieClip.lineTo()


MovieClip._name

Availability

Flash Player 4.

Usage

my_mc._name

Description

Property; the instance name of the movie clip specified by my_mc.


MovieClip.nextFrame()

Availability

Flash Player 5.

Usage

my_mc.nextFrame()

Parameters

None.

Returns

Nothing.

Description

Method; sends the playhead to the next frame and stops it.

See also

nextFrame()


MovieClip.onData

Availability

Flash Player 6.

Usage

my_mc.onData = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when a movie clip receives data from a loadVariables() or loadMovie() call. You must define a function that executes when the event handler is invoked.

This handler can be used only with movie clips for which you have a symbol in the library that is associated with a class. If you want an event handler to be invoked when a specific movie clip receives data, you must use onClipEvent(data) instead of this handler. The latter handler is invoked when any movie clip receives data.

Example

The following example illustrates the correct use of MovieClip.onData() and onClipEvent(data).

// symbol_mc is a movie clip symbol in the library.
// It is linked to the MovieClip class.
// The following function is triggered for each instance of symbol_mc
//   when it receives data.
symbol_mc.onData = function() {
   trace("The movie clip has received data");
}
// dynamic_mc is a movie clip that is being loaded with MovieClip.loadMovie().
//   This code attempts to call a function when the clip is loaded,
//   but it will not work, because the loaded SWF is not a symbol
//   in the library associated with the MovieClip class.
function output()
{
    trace("Will never be called.");
}
dynamic_mc.onData = output;
dynamic_mc.loadMovie("replacement.swf");
// The following function is invoked for any movie clip that
// receives data, whether it is in the library or not.
// Therefore, this function is invoked when symbol_mc is instantiated
//    and also when replacement.swf is loaded.
OnClipEvent( data ) {
   trace("The movie clip has received data");
}

See also

onClipEvent()


MovieClip.onDragOut

Availability

Flash Player 6.

Usage

my_mc.onDragOut = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the mouse button is pressed and the pointer rolls outside the object. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onDragOut method that sends a trace() action to the Output panel.

my_mc.onDragOut = function () {
  trace ("onDragOut called");
};

See also

MovieClip.onDragOver


MovieClip.onDragOver

Availability

Flash Player 6.

Usage

my_mc.onDragOver = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the pointer is dragged outside and then over the movie clip. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onDragOver method that sends a trace() action to the Output panel.

my_mc.onDragOver = function () {
  trace ("onDragOver called");
};

See also

MovieClip.onDragOut


MovieClip.onEnterFrame

Availability

Flash Player 6.

Usage

my_mc.onEnterFrame = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked continually at the frame rate of the SWF file. The actions associated with the enterFrame clip event are processed before any frame actions that are attached to the affected frames.

You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onEnterFrame method that sends a trace() action to the Output panel.

my_mc.onEnterFrame = function () {
  trace ("onEnterFrame called");
};


MovieClip.onKeyDown

Availability

Flash Player 6.

Usage

my_mc.onKeyDown = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when a movie clip has input focus and a key is pressed. The onKeyDown event handler is invoked with no parameters. You can use the Key.getAscii() and Key.getCode() methods to determine which key was pressed. You must define a function that executes when the event handler is invoked.

The onKeyDown event handler works only if the movie clip has input focus enabled and set. First, the focusEnabled property must be set to true for the movie clip. Then, the clip must be given focus. This can be done either by using Selection.setFocus() or by setting the tab key to navigate to the clip.

If Selection.setFocus() is used, the path for the movie clip must be passed to Selection.setFocus(). It is very easy for other elements to take the focus back once the mouse is moved.

Example

The following example defines a function for the onKeyDown() method that sends a trace() action to the Output panel.

my_mc.onKeyDown = function () {
  trace ("onKeyDown called");
};

The following example sets input focus.

my_mc.focusEnabled = true;
Selection.setFocus(my_mc);

See also

MovieClip.onKeyUp


MovieClip.onKeyUp

Availability

Flash Player 6.

Usage

my_mc.onKeyUp = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when a key is released. The onKeyUp event handler is invoked with no parameters. You can use the Key.getAscii() and Key.getCode() methods to determine which key was pressed. You must define a function that executes when the event handler is invoked.

The onKeyUp event handler works only if the movie clip has input focus enabled and set. First, the focusEnabled property must be set to true for the movie clip. Then, the clip must be given focus. This can be done either by using Selection.setFocus() or by setting the tab key to navigate to the clip.

If Selection.setFocus() is used, the path for the movie clip must be passed to Selection.setFocus(). It is very easy for other elements to take the focus back once the mouse is moved.

Example

The following example defines a function for the onKeyUp method that sends a trace() action to the Output panel.

my_mc.onKeyUp = function () {
  trace ("onKeyUp called");
};

The following example sets input focus:

MovieClip.focusEnabled = true;
Selection.setFocus(MovieClip);


MovieClip.onKillFocus

Availability

Flash Player 6.

Usage

my_mc.onKillFocus = function (newFocus) {
  // your statements here
}

Parameters

newFocus The object that is receiving the keyboard focus.

Returns

Nothing.

Description

Event handler; invoked when a movie clip loses keyboard focus. The onKillFocus method receives one parameter, newFocus, which is an object representing the new object receiving the focus. If no object receives the focus, newFocus contains the value null.


MovieClip.onLoad

Availability

Flash Player 6.

Usage

my_mc.onLoad = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the movie clip is instantiated and appears in the Timeline. You must define a function that executes when the event handler is invoked.

This handler can be used only with movie clips for which you have a symbol in the library that is associated with a class. If you want an event handler to be invoked when a specific movie clip loads, for example when you use MovieClip.loadMovie() to load a SWF file dynamically, you must use onClipEvent(load) instead of this handler. The latter handler is invoked when any movie clip loads.

Example

The following example illustrates the correct use of MovieClip.onLoad() and onClipEvent(load).

// symbol_mc is a movie clip symbol in the library.
// It is linked to the MovieClip class.
// The following function is triggered for each instance of symbol_mc
//   as it is instantiated and appears on the Timeline.
symbol_mc.onLoad = function() {
   trace("The movie clip is loaded");
}
// dynamic_mc is a movie clip that is being loaded with MovieClip.loadMovie().
//   This code attempts to call a function when the clip is loaded,
//   but it will not work, because the loaded SWF is not a symbol
//   in the library associated with the MovieClip class.
function output()
{
    trace("Will never be called.");
}
dynamic_mc.onLoad = output;
dynamic_mc.loadMovie("replacement.swf");
// The following function is invoked for any movie clip that
// appears on the Timeline, whether it is in the library or not.
// Therefore, this function is invoked when symbol_mc is instantiated
//    and also when replacement.swf is loaded.
OnClipEvent( load ) {
   trace("The movie clip is loaded");
}

See also

onClipEvent()


MovieClip.onMouseDown

Availability

Flash Player 6.

Usage

my_mc.onMouseDown = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the mouse button is pressed. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onMouseDown method that sends a trace() action to the Output panel.

my_mc.onMouseDown = function () {
  trace ("onMouseDown called");
}


MovieClip.onMouseMove

Availability

Flash Player 6.

Usage

my_mc.onMouseMove = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the mouse moves. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onMouseMove method that sends a trace() action to the Output panel.

my_mc.onMouseMove = function () {
  trace ("onMouseMove called");
};


MovieClip.onMouseUp

Availability

Flash Player 6.

Usage

my_mc.onMouseUp = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the mouse button is released. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onMouseUp method that sends a trace() action to the Output panel.

my_mc.onMouseUp = function () {
  trace ("onMouseUp called");
};


MovieClip.onPress

Availability

Flash Player 6.

Usage

my_mc.onPress = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the user clicks the mouse while the pointer is over a movie clip. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onPress method that sends a trace() action to the Output panel.

my_mc.onPress = function () {
  trace ("onPress called");
};


MovieClip.onRelease

Availability

Flash Player 6.

Usage

my_mc.onRelease = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when a button movie clip is released. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onPress method that sends a trace() action to the Output panel.

my_mc.onRelease = function () {
  trace ("onRelease called");
};


MovieClip.onReleaseOutside

Availability

Flash Player 6.

Usage

my_mc.onReleaseOutside = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the mouse is released while the pointer is outside the movie clip after the mouse button is pressed inside the movie clip.

You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onReleaseOutside method that sends a trace() action to the Output panel.

my_mc.onReleaseOutside = function () {
  trace ("onReleaseOutside called");
};


MovieClip.onRollOut

Availability

Flash Player 6.

Usage

my_mc.onRollOut = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the pointer moves outside a movie clip area. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onRollOut method that sends a trace() action to the Output panel.

my_mc.onRollOut = function () {
  trace ("onRollOut called");
};


MovieClip.onRollOver

Availability

Flash Player 6.

Usage

my_mc.onRollOver = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the pointer moves over a movie clip area. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the onRollOver method that sends a trace() to the Output panel.

my_mc.onRollOver = function () {
  trace ("onRollOver called");
};


MovieClip.onSetFocus

Availability

Flash Player 6.

Usage

my_mc.onSetFocus = function(oldFocus){
  // your statements here
}

Parameters

oldFocus The object to lose focus.

Returns

Nothing.

Description

Event handler; invoked when a movie clip receives keyboard focus. The oldFocus parameter is the object that loses the focus. For example, if the user presses the Tab key to move the input focus from a movie clip to a text field, oldFocus contains the movie clip instance.

If there is no previously focused object, oldFocus contains a null value.


MovieClip.onUnload

Availability

Flash Player 6.

Usage

my_mc.onUnload = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked in the first frame after the movie clip is removed from the Timeline. Flash processes the actions associated with the onUnload event handler before attaching any actions to the affected frame. You must define a function that executes when the event handler is invoked.

Example

The following example defines a function for the MovieClip.onUnload method that sends a trace() action to the Output panel.

my_mc.onUnload = function () {
  trace ("onUnload called");
};


MovieClip._parent

Availability

Flash Player 5.

Usage

my_mc._parent.property
_parent.property

Description

Property; a reference to the movie clip or object that contains the current movie clip or object. The current object is the object containing the ActionScript code that references _parent. Use the _parent property to specify a relative path to movie clips or objects that are above the current movie clip or object.

You can use _parent to climb up multiple levels in the display list as in the following:

_parent._parent._alpha = 20;

See also

Button._parent, _root, targetPath, TextField._parent


MovieClip.play()

Availability

Flash Player 5.

Usage

my_mc.play()

Parameters

None.

Returns

Nothing.

Description

Method; moves the playhead in the Timeline of the movie clip.

See also

play()


MovieClip.prevFrame()

Availability

Flash Player 5.

Usage

my_mc.prevFrame()

Parameters

None.

Returns

Nothing.

Description

Method; sends the playhead to the previous frame and stops it.

See also

prevFrame()


MovieClip.removeMovieClip()

Availability

Flash Player 5.

Usage

my_mc.removeMovieClip()

Parameters

None.

Returns

Nothing.

Description

Method; removes a movie clip instance created with duplicateMovieClip(), MovieClip.duplicateMovieClip() , or MovieClip.attachMovie().


MovieClip._rotation

Availability

Flash Player 4.

Usage

my_mc._rotation

Description

Property; the rotation of the movie clip, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement my_mc._rotation = 450 is the same as my_mc._rotation = 90.

See also

Button._rotation, TextField._rotation


MovieClip.setMask()

Availability

Flash Player 6.

Usage

my_mc.setMask(mask_mc)

Parameters

my_mc The instance name of a movie clip to be masked.

mask_mc The instance name of a movie clip to be a mask.

Returns

Nothing.

Description

Method; makes the movie clip in the parameter mask_mc a mask that reveals the movie clip specified by the my_mc parameter.

This method allows multiple-frame movie clips with complex, multilayered content to act as masks. You can shut masks on and off at runtime. However, you can't use the same mask for multiple masks (which is possible by using mask layers). If you have device fonts in a masked movie clip, they are drawn but not masked. You can't set a movie clip to be its own mask—for example, my_mc.setMask(my_mc).

If you create a mask layer that contains a movie clip, and then apply the setMask() method to it, the setMask() call takes priority and this is not reversible. For example, you could have a movie clip in a mask layer called UIMask that masks another layer containing another movie clip called UIMaskee. If, as the SWF file plays, you call UIMask.setMask(UIMaskee), from that point on, UIMask is masked by UIMaskee.

To cancel a mask created with ActionScript, pass the value null to the setMask() method. The following code cancels the mask without affecting the mask layer in the Timeline.

UIMask.setMask(null);

Example

The following code uses the movie clip circleMask_mc to mask the movie clip theMaskee_mc.

theMaskee_mc.setMask(circleMask_mc);


MovieClip._soundbuftime

Availability

Flash Player 6.

Usage

my_mc._soundbuftime

Description

Property (global); an integer that specifies the number of seconds a sound prebuffers before it starts to stream.


MovieClip.startDrag()

Availability

Flash Player 5.

Usage

my_mc.startDrag([lock, [left, top, right, bottom]])

Parameters

lock A Boolean value specifying whether the draggable movie clip is locked to the center of the mouse position (true), or locked to the point where the user first clicked on the movie clip (false). This parameter is optional.

left, top, right, bottom Values relative to the coordinates of the movie clip's parent that specify a constraint rectangle for the movie clip. These parameters are optional.

Returns

Nothing.

Description

Method; lets the user drag the specified movie clip. The movie clip remains draggable until explicitly stopped through a call to MovieClip.stopDrag(), or until another movie clip is made draggable. Only one movie clip is draggable at a time.

See also

MovieClip._droptarget, startDrag(), MovieClip.stopDrag()


MovieClip.stop()

Availability

Flash Player 5.

Usage

my_mc.stop()

Parameters

None.

Returns

Nothing.

Description

Method; stops the movie clip currently playing.

See also

stop()


MovieClip.stopDrag()

Availability

Flash Player 5.

Usage

my_mc.stopDrag()

Parameters

None.

Returns

Nothing.

Description

Method; ends a MovieClip.startDrag() method. A movie clip that was made draggable with that method remains draggable until a stopDrag() method is added, or until another movie clip becomes draggable. Only one movie clip is draggable at a time.

See also

MovieClip._droptarget, MovieClip.startDrag(), stopDrag()


MovieClip.swapDepths()

Availability

Flash Player 5.

Usage

my_mc.swapDepths(depth)
my_mc.swapDepths(target)

Parameters

depth A number specifying the depth level where my_mc is to be placed.

target A string specifying the movie clip instance whose depth is swapped by the instance specified by my_mc. Both instances must have the same parent movie clip.

Returns

Nothing.

Description

Method; swaps the stacking, or z-order (depth level), of the specified instance (my_mc) with the movie clip specified by the target parameter, or with the movie clip that currently occupies the depth level specified in the depth parameter. Both movie clips must have the same parent movie clip. Swapping the depth level of movie clips has the effect of moving one movie clip in front of or behind the other. If a movie clip is tweening when this method is called, the tweening is stopped. For more information, see Managing movie clip depths.

See also

_level, MovieClip.getDepth(), MovieClip.getInstanceAtDepth(), MovieClip.getNextHighestDepth()


MovieClip.tabChildren

Availability

Flash Player 6.

Usage

my_mc.tabChildren

Description

Property; undefined by default. If tabChildren is undefined or true, the children of a movie clip are included in automatic tab ordering. If the value of tabChildren is false, the children of a movie clip are not included in automatic tab ordering.

Example

A list box UI widget built as a movie clip contains several items. The user can click each item to select it, so each item is a button. However, only the list box itself should be a tab stop. The items inside the list box should be excluded from tab ordering. To do this, the tabChildren property of the list box should be set to false.

The tabChildren property has no effect if the tabIndex property is used; the tabChildren property affects only automatic tab ordering.

See also

Button.tabIndex, MovieClip.tabEnabled, MovieClip.tabIndex, TextField.tabIndex


MovieClip.tabEnabled

Availability

Flash Player 6.

Usage

my_mc.tabEnabled

Description

Property; specifies whether my_mc is included in automatic tab ordering. It is undefined by default.

If tabEnabled is undefined, the object is included in automatic tab ordering only if it defines at least one button handler, such as MovieClip.onRelease. If tabEnabled is true, the object is included in automatic tab ordering. If the tabIndex property is also set to a value, the object is included in custom tab ordering as well.

If tabEnabled is false, the object is not included in automatic or custom tab ordering, even if the tabIndex property is set. However, if MovieClip.tabChildren is true, the movie clip's children can still be included in automatic tab ordering, even if tabEnabled is false.

See also

Button.tabEnabled, MovieClip.tabChildren, MovieClip.tabIndex, TextField.tabEnabled


MovieClip.tabIndex

Availability

Flash Player 6.

Usage

my_mc.tabIndex

Description

Property; lets you customize the tab ordering of objects in a movie. The tabIndex property is undefined by default. You can set tabIndex on a button, movie clip, or text field instance.

If an object in a SWF file contains a tabIndex property, automatic tab ordering is disabled, and the tab ordering is calculated from the tabIndex properties of objects in the SWF file. The custom tab ordering includes only objects that have tabIndex properties.

The tabIndex property must be a positive integer. The objects are ordered according to their tabIndex properties, in ascending order. An object with a tabIndex value of 1 precedes an object with a tabIndex value of 2. The custom tab ordering disregards the hierarchical relationships of objects in a SWF file. All objects in the SWF file with tabIndex properties are placed in the tab order. You shouldn't use the same tabIndex value for multiple objects.

See also

Button.tabIndex, TextField.tabIndex


MovieClip._target

Availability

Flash Player 4.

Usage

my_mc._target

Description

Property (read-only); returns the target path of the movie clip instance specified by my_mc.


MovieClip._totalframes

Availability

Flash Player 4.

Usage

my_mc._totalframes

Description

Property (read-only); returns the total number of frames in the movie clip instance specified in the MovieClip parameter.


MovieClip.trackAsMenu

Availability

Flash Player 6.

Usage

my_mc.trackAsMenu

Description

Property; a Boolean property that indicates whether or not other buttons or movie clips can receive mouse release events. This allows you to create menus. You can set the trackAsMenu property on any button or movie clip object. If the trackAsMenu property does not exist, the default behavior is false.

You can change the trackAsMenu property at any time; the modified button movie clip immediately takes on the new behavior.

See also

Button.trackAsMenu


MovieClip.unloadMovie()

Availability

Flash Player 5.

Usage

my_mc.unloadMovie()

Parameters

None.

Returns

Nothing.

Description

Method; removes the contents of a movie clip instance. The instance properties and clip handlers remain.

To remove the instance, including its properties and clip handlers, use MovieClip.removeMovieClip().

See also

MovieClip.attachMovie(), MovieClip.loadMovie(), unloadMovie(), unloadMovieNum()


MovieClip._url

Availability

Flash Player 4.

Usage

my_mc._url

Description

Property (read only); retrieves the URL of the SWF file from which the movie clip was downloaded.


MovieClip.useHandCursor

Availability

Flash Player 6.

Usage

my_mc.useHandCursor

Description

Property; a Boolean value that indicates whether the hand cursor (pointing hand) appears when the mouse rolls over a button movie clip. The default value of useHandCursor is true. If useHandCursor is set to true, the pointing hand used for buttons is displayed when the mouse rolls over a button movie clip. If useHandCursor is false, the arrow cursor is used instead.

You can change the useHandCursor property at any time; the modified button movie clip immediately takes on the new cursor behavior. The useHandCursor property can be read out of a prototype object.


MovieClip._visible

Availability

Flash Player 4.

Usage

my_mc._visible

Description

Property; a Boolean value that indicates whether the movie clip specified by my_mc is visible. Movie clips that are not visible (_visible property set to false) are disabled. For example, a button in a movie clip with _visible set to false cannot be clicked.

See also

Button._visible, TextField._visible


MovieClip._width

Availability

Flash Player 4 as a read-only property.

Usage

my_mc._width

Description

Property; the width of the movie clip, in pixels.

Example

The following example sets the height and width properties of a movie clip when the user clicks the mouse.

onclipEvent(mouseDown) {
  _width=200;
  _height=200;
}

See also

MovieClip._height


MovieClip._x

Availability

Flash Player 3.

Usage

my_mc._x

Description

Property; an integer that sets the x coordinate of a movie clip relative to the local coordinates of the parent movie clip. If a movie clip is in the main Timeline, then its coordinate system refers to the upper left corner of the Stage as (0, 0). If the move clip is inside another movie clip that has transformations, the movie clip is in the local coordinate system of the enclosing movie clip. Thus, for a movie clip rotated 90 degrees counterclockwise, the movie clip's children inherit a coordinate system that is rotated 90 degrees counterclockwise. The movie clip's coordinates refer to the registration point position.

See also

MovieClip._xscale, MovieClip._y, MovieClip._yscale


MovieClip._xmouse

Availability

Flash Player 5.

Usage

my_mc._xmouse

Description

Property (read-only); returns the x coordinate of the mouse position.

See also

Mouse class, MovieClip._ymouse


MovieClip._xscale

Availability

Flash Player 4.

Usage

my_mc._xscale

Description

Property; determines the horizontal scale (percentage) of the movie clip as applied from the registration point of the movie clip. The default registration point is (0,0).

Scaling the local coordinate system affects the _x and _y property settings, which are defined in whole pixels. For example, if the parent movie clip is scaled to 50%, setting the _x property moves an object in the movie clip by half the number of pixels as it would if the movie were set at 100%.

See also

MovieClip._x, MovieClip._y, MovieClip._yscale


MovieClip._y

Availability

Flash Player 3.

Usage

my_mc._y

Description

Property; sets the y coordinate of a movie clip relative to the local coordinates of the parent movie clip. If a movie clip is in the main Timeline, then its coordinate system refers to the upper left corner of the Stage as (0, 0). If the move clip is inside another movie clip that has transformations, the movie clip is in the local coordinate system of the enclosing movie clip. Thus, for a movie clip rotated 90 degrees counterclockwise, the movie clip's children inherit a coordinate system that is rotated 90 degrees counterclockwise. The movie clip's coordinates refer to the registration point position.

See also

MovieClip._x, MovieClip._xscale, MovieClip._yscale


MovieClip._ymouse

Availability

Flash Player 5.

Usage

my_mc._ymouse

Description

Property (read-only); indicates the y coordinate of the mouse position.

See also

Mouse class, MovieClip._xmouse


MovieClip._yscale

Availability

Flash Player 4.

Usage

my_mc._yscale

Description

Property; sets the vertical scale (percentage) of the movie clip as applied from the registration point of the movie clip. The default registration point is (0,0).

Scaling the local coordinate system affects the _x and _y property settings, which are defined in whole pixels. For example, if the parent movie clip is scaled to 50%, setting the _x property moves an object in the movie clip by half the number of pixels as it would if the movie were at 100%.

See also

MovieClip._x, MovieClip._xscale, MovieClip._y


MovieClipLoader class

Availability

Flash Player 7.

Description

This class lets you implement listener callbacks that provide status information while SWF or JPEG files are being loaded (downloaded) into movie clips. To use MovieClipLoader features, use MovieClipLoader.loadClip() instead of loadMovie() or MovieClip.loadMovie() to load SWF files.

After you issue the MovieClipLoader.loadClip() command, the following events take place in the order listed:

  • When the first bytes of the downloaded file have been written to disk, the MovieClipLoader.onLoadStart() listener is invoked.
  • If you have implemented the MovieClipLoader.onLoadProgress() listener, it is invoked during the loading process.

    Note: You can call MovieClipLoader.getProgress() at any time during the load process.

  • When the entire downloaded file has been written to disk, the MovieClipLoader.onLoadComplete() listener is invoked.
  • After the downloaded file's first frame actions have been executed, the MovieClipLoader.onLoadInit() listener is invoked.

After MovieClipLoader.onLoadInit()has been invoked, you can set properties, use methods, and otherwise interact with the loaded movie.

If the file fails to load completely, the MovieClipLoader.onLoadError() listener is invoked.

Method summary for the MovieClipLoader class

Method | Description
MovieClipLoader.addListener() | Registers an object to receive notification when a MovieClipLoader event handler is invoked.
MovieClipLoader.getProgress() | Returns the number of bytes loaded and total number of bytes for a file that is being loaded using MovieClipLoader.loadClip().
MovieClipLoader.loadClip() | Loads a SWF or JPEG file into a movie clip in Flash Player while the original movie is playing.
MovieClipLoader.removeListener() | Deletes an object that was registered using MovieClipLoader.addListener().
MovieClipLoader.unloadClip() | Removes a movie clip that was loaded by means of MovieClipLoader.loadClip().

Listener summary for the MovieClipLoader class

Listener | Description
MovieClipLoader.onLoadComplete() | Invoked when a file loaded with MovieClipLoader.loadClip() has completely downloaded.
MovieClipLoader.onLoadError() | Invoked when a file loaded with MovieClipLoader.loadClip() has failed to load.
MovieClipLoader.onLoadInit() | Invoked when the actions on the first frame of the loaded clip have been executed.
MovieClipLoader.onLoadProgress() | Invoked every time the loading content is written to disk during the loading process.
MovieClipLoader.onLoadStart() | Invoked when a call to MovieClipLoader.loadClip() has successfully begun to download a file.

Constructor for the MovieClipLoader class

Availability

Flash Player 7.

Usage

new MovieClipLoader()

Parameters

None.

Returns

A reference to a MovieClipLoader object.

Description

Constructor; creates a MovieClipLoader object that you can use to implement a number of listeners to respond to events while a SWF or JPEG file is downloading.

Example

See MovieClipLoader.loadClip().

See also

MovieClipLoader.addListener()


MovieClipLoader.addListener()

Availability

Flash Player 7.

Usage

my_mcl.addListener(listenerObject)

Parameters

listenerObject An object that listens for a callback notification from the MovieClipLoader event handlers.

Returns

Nothing.

Description

Method; registers an object to receive notification when a MovieClipLoader event handler is invoked.

Example

See MovieClipLoader.loadClip().

See also

MovieClipLoader.onLoadComplete(), MovieClipLoader.onLoadError(), MovieClipLoader.onLoadInit(), MovieClipLoader.onLoadProgress(), MovieClipLoader.onLoadStart(), MovieClipLoader.removeListener()


MovieClipLoader.getProgress()

Availability

Flash Player 7.

Usage

my_mcl.getProgress(target_mc)

Parameters

target_mc A SWF or JPEG file that is loaded using MovieClipLoader.loadClip().

Returns

An object that has two integer properties: bytesLoaded and bytesTotal.

Description

Method; returns the number of bytes loaded and total number of bytes for a file that is being loaded using MovieClipLoader.loadClip(); for compressed movies, it reflects the number of compressed bytes. This method lets you explicitly request this information, instead of (or in addition to) writing a MovieClipLoader.onLoadProgress() listener function.

Example

See MovieClipLoader.loadClip().

See also

MovieClipLoader.onLoadProgress()


MovieClipLoader.loadClip()

Availability

Flash Player 7.

Usage

my_mcl.loadClip("url", target )

Parameters

url The absolute or relative URL of the SWF file or JPEG file to be loaded. A relative path must be relative to the SWF file at level 0. Absolute URLs must include the protocol reference, such as http:// or file:///. Filenames cannot include disk drive specifications.

target The target path of a movie clip, or an integer specifying the level in Flash Player into which the movie will be loaded. The target movie clip will be replaced by the loaded movie or image.

Returns

Nothing.

Description

Method; loads a SWF or JPEG file into a movie clip in Flash Player while the original movie is playing. Using this method lets you display several movies at once and switch between movies without loading another HTML document.

Using this method instead of loadMovie() or MovieClip.loadMovie() has a number of advantages:

  • The MovieClipLoader.onLoadStart() handler is invoked when loading begins.
  • The MovieClipLoader.onLoadError() handler is invoked if the clip cannot be loaded.
  • The MovieClipLoader.onLoadProgress() handler is invoked as the loading process progresses.
  • The MovieClipLoader.onLoadInit() handler is invoked after the actions in the first frame of the clip have executed, so you can being manipulating the loaded clip.

A movie or image loaded into a movie clip inherits the position, rotation, and scale properties of the movie clip. You can use the target path of the movie clip to target the loaded movie.

You can use this method to load one or more files into a single movie clip or level; MovieClipLoader listener objects are passed the loading target movie clip instance as a parameter. Alternately, you can create a different MovieClipLoader object for each file you load.

Use MovieClipLoader.unloadClip() to remove movies or images loaded with this method or to cancel a load operation that is in progress.

Example

The following example illustrates the use of many of the MovieClipLoader methods and listeners.

// first set of listeners
var my_mcl = new MovieClipLoader();
myListener = new Object();
myListener.onLoadStart = function (target_mc)
{
myTrace ("*********First my_mcl instance*********");
myTrace ("Your load has begun on movie clip . = " + target_mc);
var loadProgress = my_mcl.getProgress(target_mc);
myTrace(loadProgress.bytesLoaded + " = bytes loaded at start");
myTrace(loadProgress.bytesTotal + " = bytes total at start");
}
myListener.onLoadProgress = function (target_mc, loadedBytes, totalBytes)
{
myTrace ("*********First my_mcl instance Progress*********");
myTrace ("onLoadProgress() called back on movie clip " + target_mc);
myTrace(loadedBytes + " = bytes loaded at progress callback " );
myTrace(totalBytes + " = bytes total at progress callback \n");
}
myListener.onLoadComplete = function (target_mc)
{
myTrace ("*********First my_mcl instance*********");
myTrace ("Your load is done on movie clip = " + target_mc);
var loadProgress = my_mcl.getProgress(target_mc);
myTrace(loadProgress.bytesLoaded + " = bytes loaded at end" );
myTrace(loadProgress.bytesTotal + " = bytes total at end=");
}
myListener.onLoadInit = function (target_mc)
{
myTrace ("*********First my_mcl instance*********");
myTrace ("Movie clip = " + target_mc + " is now initialized");
// you can now do any setup required, for example:
target_mc._width = 100;
target_mc._width = 100;
}
myListener.onLoadError = function (target_mc, errorCode)
{
myTrace ("*********First my_mcl instance*********");
myTrace ("ERROR CODE = " + errorCode);
myTrace ("Your load failed on movie clip = " + target_mc + "\n");
 }
my_mcl.addListener(myListener);
//Now load the files into their targets.
// loads into movie clips - strings used as target
my_mcl.loadClip("http://www.somedomain.somewhere.com/someFile.swf","_root.myMC");
my_mcl.loadClip("http://www.somedomain.somewhere.com/someOtherFile.swf", "_level0.myMC2");
//failed load
my_mcl.loadClip("http://www.somedomain.somewhere.com/someFile.jpg", _root.myMC5);

// loads into movie clips - movie clip instances used as target.
my_mcl.loadClip("http://www.somedomain.somewhere.com/someOtherFile.jpg", _level0.myMC3);

// loads into _level1
my_mcl.loadClip("file:///C:/media/images/somePicture.jpg", 1);

//Second set of listeners
var another_mcl = new MovieClipLoader();
myListener2 = new Object();
myListener2.onLoadStart = function (target_mc)
{
myTrace("*********Second my_mcl instance*********");
myTrace ("Your load has begun on movie clip22 . = " + target_mc);
var loadProgress = my_mcl.getProgress(target_mc);
myTrace(loadProgress.bytesLoaded + " = bytes loaded at start" );
myTrace(loadProgress.bytesTotal + " = bytes total at start");
}
myListener2.onLoadComplete = function (target_mc)
{
myTrace ("*********Second my_mcl instance*********");
myTrace ("Your load is done on movie clip = " + target_mc);
var loadProgress = my_mcl.getProgress(target_mc);
myTrace(loadProgress.bytesLoaded + " = bytes loaded at end");
myTrace(loadProgress.bytesTotal + " = bytes total at end" );
}
myListener2.onLoadError = function (target_mc, errorCode)
{
myTrace ("*********Second my_mcl instance*********");
myTrace ("ERROR CODE = " + errorCode);
myTrace ("Your load failed on movie clip = " + target_mc + "\n");
 }
another_mcl.addListener(myListener2);
//Now load the files into their targets (using the second instance of MovieClipLoader)
another_mcl.loadClip("http://www.somedomain.somewhere.com/yetAnotherFile.jpg", _root.myMC4);
// Issue the following statements after the download is complete,
// and after my_mcl.onLoadInit has been called.
// my_mcl.removeListener(myListener)
// my_mcl.removeListener(myListener2)

See also

MovieClipLoader.unloadClip()


MovieClipLoader.onLoadComplete()

Availability

Flash Player 7.

Usage

listenerObject.onLoadComplete() = function([target_mc]) {
  // your statements here
}

Parameters

listenerObject A listener object that was added using MovieClipLoader.addListener().

target_mc A movie clip loaded by a MovieClipLoader.loadClip() method. This parameter is optional.

Returns

Nothing.

Description

Listener; invoked when a file loaded with MovieClipLoader.loadClip() has completely downloaded. To specify that the listener should be invoked only for a particular clip, and not for every clip, pass a value for target_mc.

Example

See MovieClipLoader.loadClip().

See also

MovieClipLoader.addListener(), MovieClipLoader.onLoadStart(), MovieClipLoader.onLoadError()


MovieClipLoader.onLoadError()

Availability

Flash Player 7.

Usage

listenerObject.onLoadError() = function([target_mc,] errorCode) {
  // your statements here
}

Parameters

listenerObject A listener object that was added using MovieClipLoader.addListener().

target_mc A movie clip loaded by a MovieClipLoader.loadClip() method. This parameter is optional.

errorCode A string that explains the reason for the failure.

Returns

One of two strings: "URLNotFound" or "LoadNeverCompleted".

Description

Listener; invoked when a file loaded with MovieClipLoader.loadClip() has failed to load.

The string "URLNotFound" is returned if neither the MovieClipLoader.onLoadStart() or MovieClipLoader.onLoadComplete() listener has been called. For example, if a server is down or the file is not found, these listeners are not called.

The string "LoadNeverCompleted" is returned if MovieClipLoader.onLoadStart() was called but MovieClipLoader.onLoadComplete() was not called. For example, if MovieClipLoader.onLoadStart() is called but the download is interrupted due to server overload, server crash, and so on, MovieClipLoader.onLoadComplete() will not be called.

To specify that the listener should be invoked only for a particular clip, and not for every clip, pass a value for target_mc.

Example

See MovieClipLoader.loadClip().


MovieClipLoader.onLoadInit()

Availability

Flash Player 7.

Usage

listenerObject.onLoadInit() = function([target_mc]) {
  // your statements here
}

Parameters

listenerObject A listener object that was added using MovieClipLoader.addListener().

target_mc A movie clip loaded by a MovieClipLoader.loadClip() method. This parameter is optional.

Returns

Nothing.

Description

Listener; invoked when the actions on the first frame of the loaded clip have been executed. After this listener has been invoked, you can set properties, use methods, and otherwise interact with the loaded movie.

To specify that the listener should be invoked only for a particular clip, and not for every clip, pass a value for target_mc.

Example

See MovieClipLoader.loadClip().

See also

MovieClipLoader.onLoadStart()


MovieClipLoader.onLoadProgress()

Availability

Flash Player 7.

Usage

listenerObject.onLoadProgress() =
  function([target_mc [, loadedBytes [, totalBytes ] ] ] ) {
  // your statements here
}

Parameters

listenerObject A listener object that was added using MovieClipLoader.addListener().

target_mc A movie clip loaded by a MovieClipLoader.loadClip() method. This parameter is optional.

loadedBytes The number of bytes that had been loaded when the listener was invoked.

totalBytes The total number of bytes in the file being loaded.

Returns

Nothing.

Description

Listener; invoked every time the loading content is written to disk during the loading process (that is, between MovieClipLoader.onLoadStart() and MovieClipLoader.onLoadComplete()). You can use this method to display information about the progress of the download, using the loadedBytes and totalBytes parameters.

To specify that the listener should be invoked only for a particular clip, and not for every clip, pass a value for target_mc.

Example

See MovieClipLoader.loadClip().

See also

MovieClipLoader.getProgress()


MovieClipLoader.onLoadStart()

Availability

Flash Player 7.

Usage

listenerObject.onLoadStart() = function([target_mc]) {
  // your statements here
}

Parameters

listenerObject A listener object that was added using MovieClipLoader.addListener().

target_mc A movie clip loaded by a MovieClipLoader.loadClip() method. This parameter is optional.

Returns

Nothing.

Description

Listener; invoked when a call to MovieClipLoader.loadClip() has successfully begun to download a file. To specify that the listener should be invoked only for a particular clip, and not for every clip, pass a value for target_mc.

Example

See MovieClipLoader.loadClip().

See also

MovieClipLoader.onLoadError(), MovieClipLoader.onLoadInit(), MovieClipLoader.onLoadComplete()


MovieClipLoader.removeListener()

Availability

Flash Player 7.

Usage

my_mcl.removeListener(listenerObject)

Parameters

listenerObject A listener object that was added using MovieClipLoader.addListener().

Returns

Nothing.

Description

Method; deletes an object that was used to receive notification when a MovieClipLoader event handler was invoked.

Example

See MovieClipLoader.loadClip().


MovieClipLoader.unloadClip()

Availability

Flash Player 7.

Usage

my_mcl.unloadClip(target)

Parameters

target The string or integer passed to the corresponding call to my_mcl.loadClip().

Returns

Nothing.

Description

Method; removes a movie clip that was loaded by means of MovieClipLoader.loadClip(). If you issue this command while a movie is loading, MovieClipLoader.onLoadError() is invoked.

See also

MovieClipLoader.loadClip()


NaN

Availability

Flash Player 5.

Usage

NaN

Description

Variable; a predefined variable with the IEEE-754 value for NaN (Not a Number). To determine if a number is NaN, use isNaN().

See also

isNaN(), Number.NaN


ne (not equal — string specific)

Availability

Flash Player 4. This operator has been deprecated in favor of the != (inequality) operator.

Usage

expression1 ne expression2

Parameters

expression1, expression2 Numbers, strings, or variables.

Returns

A Boolean value.

Description

Operator (comparison); compares expression1 to expression2 and returns true if expression1 is not equal to expression2; otherwise, returns false.

See also

!= (inequality)


NetConnection class

Availability

Flash Player 7.

Note: This class is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Description

The NetConnection class provides the means to play back streaming FLV files from a local drive or HTTP address. For more information on video playback, see Playing back external FLV files dynamically.

Method summary for the NetConnection class

Method | Description
NetConnection.connect() | Opens a local connection through which you can play back video (FLV) files from an HTTP address or from the local file system.

Constructor for the NetConnection class

Availability

Flash Player 7.

Note: This class is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

new NetConnection()

Parameters

None.

Returns

A reference to a NetConnection object.

Description

Constructor; creates a NetConnection object that you can use in conjunction with a NetStream object to play back local streaming video (FLV) files. After creating the NetConnection object, use NetConnection.connect() to make the actual connection.

Playing external FLV files provides several advantages over embedding video in a Flash document, such as better performance and memory management, and independent video and Flash frame rates. For more information, see Playing back external FLV files dynamically.

See also

NetStream class, Video.attachVideo()


NetConnection.connect()

Availability

Flash Player 7.

Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_nc.connect(null);

Parameters

None (you must pass null).

Returns

Nothing.

Description

Constructor; opens a local connection through which you can play back video (FLV) files from an HTTP address or from the local file system.

See also

NetStream class


NetStream class

Availability

Flash Player 7.

Note: This class is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Description

The NetStream class provides methods and properties for playing Flash Video (FLV) files from the local file system or an HTTP address. You use a NetStream object to stream video through a NetConnection object. Playing external FLV files provides several advantages over embedding video in a Flash document, such as better performance and memory management, and independent video and Flash frame rates. This class provides a number of methods and properties you can use to track the progress of the file as it loads and plays, and to give the user control over playback (stopping, pausing, and so on).

For more information on video playback, see Playing back external FLV files dynamically.

Method summary for the NetStream class

The following methods and properties of the NetConnection and NetStream classes are used to control FLV playback.

Method | Purpose
NetStream.close() | Closes the stream but does not clear the video object.
NetStream.pause() | Pauses or resumes playback of a stream.
NetStream.play() | Begins playback of an external video (FLV) file.
NetStream.seek() | Seeks a specific position in the FLV file.
NetStream.setBufferTime() | Specifies how long to buffer data before starting to display the stream.

Property summary for the NetStream class

Property | Description
NetStream.bufferLength | The number of seconds of data currently in the buffer.
NetStream.bufferTime | Read-only: the number of seconds assigned to the buffer by NetStream.setBufferTime().
NetStream.bytesLoaded | Read-only; the number of bytes of data that have been loaded into the player.
NetStream.bytesTotal | Read-only; the total size in bytes of the file being loaded into the player.
NetStream.currentFps | The number of frames per second being displayed.
NetStream.time | Read-only; the position of the playhead, in seconds.

Event handler summary for the NetStream class

Event handler | Description
NetStream.onStatus | Invoked every time a status change or error is posted for the NetStream object.

Constructor for the NetStream class

Availability

Flash Player 7.

Note: This class is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

new NetStream(my_nc)

Parameters

my_nc A NetConnection object.

Returns

A reference to a NetStream object.

Description

Constructor; creates a stream that can be used for playing FLV files through the specified NetConnection object.

Example

The following code first constructs a new NetConnection object, my_nc, and uses it to construct a new NetStream object called videoStream_ns.

my_nc = new NetConnection();
my_nc.connect(null);
videoStream_ns = new NetStream(my_nc);

See also

NetConnection class, NetStream class, Video.attachVideo()


NetStream.bufferLength

Availability

Flash Player 7.

Note: This property is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.bufferLength

Description

Read-only property; the number of seconds of data currently in the buffer. You can use this property in conjunction with NetStream.bufferTime to estimate how close the buffer is to being full—for example, to display feedback to a user who is waiting for data to be loaded into the buffer.

See also

NetStream.bytesLoaded


NetStream.bufferTime

Availability

Flash Player 7.

Note: This property is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.bufferTime

Description

Read-only property; the number of seconds assigned to the buffer by NetStream.setBufferTime(). The default value is .1(one-tenth of a second). To determine the number of seconds currently in the buffer, use NetStream.bufferLength.

See also

NetStream.time


NetStream.bytesLoaded

Availability

Flash Player 7.

Usage

my_ns.bytesLoaded

Description

Read-only property; the number of bytes of data that have been loaded into the player. You can use this method in conjunction with NetStream.bytesTotal to estimate how close the buffer is to being full—for example, to display feedback to a user who is waiting for data to be loaded into the buffer

See also

NetStream.bufferLength


NetStream.bytesTotal

Availability

Flash Player 7.

Usage

my_ns.bytesLoaded

Description

Read-only property; the total size in bytes of the file being loaded into the player.

See also

NetStream.bytesLoaded, NetStream.bufferTime


NetStream.close()

Availability

Flash Player 7.

Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.close()

Parameters

None.

Returns

Nothing.

Description

Method; stops playing all data on the stream, sets the NetStream.time property to 0, and makes the stream available for another use. This command also deletes the local copy of an FLV file that was downloaded using HTTP.

Example

The following onDisconnect() function closes a connection and deletes the temporary copy of someFile.flv that was stored on the local disk.

my_nc = new NetConnection();
my_nc.connect(null);
my_ns = new NetStream(my_nc);
my_ns.play("http://www.someDomain.com/videos/someFile.flv");

function onDisconnect() {
  my_ns.close();
}

See also

NetStream.pause(), NetStream.play()


NetStream.currentFps

Availability

Flash Player 7.

Note: This property is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.currentFps

Description

Read-only property; the number of frames per second being displayed. If you are exporting FLV files to be played back on a number of systems, you can check this value during testing to help you determine how much compression to apply when exporting the file.


NetStream.onStatus

Availability

Flash Player 7.

Note: This handler is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.onStatus = function(infoObject) {
  // Your code here
}

Parameters

infoObject A parameter defined according to the status or error message. For more information about this parameter, see "Description," below.

Returns

Nothing.

Description

Event handler; invoked every time a status change or error is posted for the NetStream object. If you want to respond to this event handler, you must create a function to process the information object.

The information object has a code property containing a string that describes the result of the onStatus handler, and a level property containing a string that is either "Status" or "Error".

In addition to this onStatus handler, Flash also provides a "super" function called System.onStatus. If onStatus is invoked for a particular object and there is no function assigned to respond to it, Flash processes a function assigned to System.onStatus if it exists.

The following events notify you when certain NetStream activities occur.

Code property | Level property | Meaning
NetStream.Buffer.Empty | Status | Data is not being received quickly enough to fill the buffer. Data flow will be interrupted until the buffer refills, at which time a NetStream.Buffer.Full message will be sent and the stream will begin playing again.
NetStream.Buffer.Full | Status | The buffer is full and the stream will begin playing.
NetStream.Play.Start | Status | Playback has started.
NetStream.Play.Stop | Status | Playback has stopped.
NetStream.Play.StreamNotFound | Error | The FLV passed to the play() method can't be found.

Example

The following example writes data about the stream to a log file.

my_ns.onStatus = function(info)
{
  _root.log_stream += "Stream status.\n";
  _root.log_stream += "Event: " + info.code + "\n";
  _root.log_stream += "Type: " + info.level + "\n";
}

See also

System.onStatus


NetStream.pause()

Availability

Flash Player 7.

Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.pause( [ pauseResume ] )

Parameters

pauseResume Optional: a Boolean value specifying whether to pause play (true) or resume play (false). If you omit this parameter, NetStream.pause() acts as a toggle: the first time it is called on a specified stream, it pauses play, and the next time it is called, it resumes play.

Returns

Nothing.

Description

Method; pauses or resumes playback of a stream.

The first time you call this method (without sending a parameter), it pauses play; the next time, it resumes play. You might want to attach this method to a button that the user presses to pause or resume playback.

Example

The following examples illustrate some uses of this method.

my_ns.pause(); // pauses play first time issued
my_ns.pause(); // resumes play
my_ns.pause(false); // no effect, play continues
my_ns.pause(); // pauses play

See also

NetStream.close(), NetStream.play()


NetStream.play()

Availability

Flash Player 7.

Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.play("fileName");

Parameters

fileName The name of an FLV file to play, in quotation marks. Both http:// and file:// formats are supported; the file:// location is always relative to the location of the SWF file.

Returns

Nothing.

Description

Method; begins playback of an external video (FLV) file. To view video data, you must call a Video.attachVideo() method; audio being streamed with the video, or an FLV file that contains only audio, is played automatically.

If you want to control the audio associated with an FLV file, you can use MovieClip.attachAudio() to route the audio to a movie clip; you can then create a Sound object to control some aspects of the audio. For more information, see MovieClip.attachAudio().

If the FLV file can't be found, the NetStream.onStatus event handler is invoked. If you want to stop a stream that is currently playing, use NetStream.close().

You can play local FLV files that are stored in the same directory as the SWF file or in a subdirectory; you can't navigate to a higher-level directory. For example, if the SWF file is located in a directory named /training, and you want to play a video stored in the /training/videos directory, you would use the following syntax:

my_ns.play("file://videos/videoName.flv");

To play a video stored in the /training directory, you would use the following syntax:

my_ns.play("file://videoName.flv");

Example

The following example illustrates some ways to use the NetStream.play() command.

// Play a file that is on the user's computer
// The joe_user directory is a subdirectory of the directory
//     in which the SWF is stored
my_ns.play("file://joe_user/flash/videos/lectureJune26.flv");

// Play a file on a server
my_ns.play("http://someServer.someDomain.com/flash/video/orientation.flv");

See also

MovieClip.attachAudio(), NetStream.close(), NetStream.pause(), Video.attachVideo()


NetStream.seek()

Availability

Flash Player 7.

Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.seek(numberOfSeconds)

Parameters

numberOfSeconds The approximate time value, in seconds, to move to in an FLV file. The playhead moves to the keyframe closest to numberOfSeconds.

  • To return to the beginning of the stream, pass 0 for numberOfSeconds.
  • To seek forward from the beginning of the stream, pass the number of seconds you want to advance. For example, to position the playhead at 15 seconds from the beginning, use my_ns.seek(15).
  • To seek relative to the current position, pass my_ns.time + n or my_ns.time - n to seek n seconds forward or backward, respectively, from the current position. For example, to rewind 20 seconds from the current position, use my_ns.seek(my_ns.time - 20).

Returns

Nothing.

Description

Method; seeks the keyframe closest to the specified number of seconds from the beginning of the stream. The stream resumes playing when it reaches the specified location in the stream.

Example

The following example illustrates some ways to use the NetStream.seek() command.

// Return to the beginning of the stream
my_ns.seek(0);

// Move to a location 30 seconds from the beginning of the stream
my_ns.seek(30);

//Move backwards three minutes from current location
my_ns.seek(my_ns.time - 180);

See also

NetStream.play(), NetStream.time


NetStream.setBufferTime()

Availability

Flash Player 7.

Note: This method is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.setBufferTime(numberOfSeconds)

Parameters

numberOfSeconds The number of seconds of data to be buffered before Flash begins displaying data. The default value is .1 (one-tenth of a second).

Description

Method; specifies how long to buffer messages before starting to display the stream. For example, if you want to make sure that the first 15 seconds of the stream play without interruption, set numberOfSeconds to 15; Flash begins playing the stream only after 15 seconds of data are buffered.

See also

NetStream.bufferTime


NetStream.time

Availability

Flash Player 7.

Note: This property is also supported in Flash Player 6 when used with Flash Communication Server. For more information, see your Flash Communication Server documentation.

Usage

my_ns.time

Description

Read-only property; the position of the playhead, in seconds.

See also

NetStream.bufferLength, NetStream.bytesLoaded


new

Availability

Flash Player 5.

Usage

new constructor()

Parameters

constructor A function followed by any optional parameters in parentheses. The function is usually the name of the object type (for example, Array, Number, or Object) to be constructed.

Returns

Nothing.

Description

Operator; creates a new, initially anonymous, object and calls the function identified by the constructor parameter. The new operator passes to the function any optional parameters in parentheses, as well as the newly created object, which is referenced using the keyword this. The constructor function can then use this to set the variables of the object.

Example

The following example creates the Book() function and then uses the new operator to create the objects book1 and book2.

function Book(name, price){
  this.name = name;
  this.price = price;
}

book1 = new Book("Confederacy of Dunces", 19.95);
book2 = new Book("The Floating Opera", 10.95);

Example

The following example uses the new operator to create an Array object with 18 elements:

golfCourse_array = new Array(18);

See also

[] (array access), {} (object initializer)


newline

Availability

Flash Player 4.

Usage

newline

Parameters

None.

Returns

Nothing.

Description

Constant; inserts a carriage return character (\n) that generates a blank line in text output generated by your code. Use newline to make space for information that is retrieved by a function or action in your code.

Example

The following example shows how newline displays output from the trace() action on multiple lines.

var myName:String = "Lisa", myAge:Number = 30;
trace(myName + myAge);
trace(myName + newline + myAge);


nextFrame()

Availability

Flash 2.

Usage

nextFrame()

Parameters

None.

Returns

Nothing.

Description

Function; sends the playhead to the next frame and stops it.

Example

In this example, when the user clicks the button, the playhead goes to the next frame and stops.

on (release) {
  nextFrame();
}


nextScene()

Availability

Flash 2.

Usage

nextScene()

Parameters

None.

Returns

Nothing.

Description

Function; sends the playhead to Frame 1 of the next scene and stops it.

Example

In this example, when a user releases the button, the playhead is sent to Frame 1 of the next scene.

on(release) {
  nextScene();
}

See also

prevScene()


not

Availability

Flash Player 4. This operator has been deprecated in favor of the ! (logical NOT) operator.

Usage

not expression

Parameters

expression A variable or other expression that converts to a Boolean value.

Description

Operator; performs a logical NOT operation in Flash Player 4.

See also

! (logical NOT)


null

Availability

Flash Player 5.

Usage

null

Parameters

None.

Returns

Nothing.

Description

Constant; a special value that can be assigned to variables, or returned by a function if no data was provided. You can use null to represent values that are missing or do not have a defined data type.

Example

In a numeric context, null evaluates to 0. Equality tests can be performed with null. In this statement, a binary tree node has no left child, so the field for its left child could be set to null.

if (tree.left == null) {
  tree.left = new TreeNode();
}


Number class

Availability

Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly).

Description

The Number class is a simple wrapper object for the Number data type. You can manipulate primitive numeric values by using the methods and properties associated with the Number class. This class is identical to the JavaScript Number class.

You must use a constructor when calling the methods of a Number object, but you do not need to use the constructor when calling the properties of a Number object. The following examples specify the syntax for calling the methods and properties of a Number object.

The following example calls the toString() method of a Number object, which returns the string "1234".

myNumber = new Number(1234);
myNumber.toString();

This example calls the MIN_VALUE property (also called a constant) of a Number object:

smallest = Number.MIN_VALUE

Method summary for the Number class

Method | Description
Number.toString() | Returns the string representation of a Number object.
Number.valueOf() | Returns the primitive value of a Number object.

Property summary for the Number class

Property | Description
Number.MAX_VALUE | Constant representing the largest representable number (double-precision IEEE-754). This number is approximately 1.79E+308.
Number.MIN_VALUE | Constant representing the smallest representable number (double-precision IEEE-754). This number is approximately 5e-324.
Number.NaN | Constant representing the value for Not a Number (NaN).
Number.NEGATIVE_INFINITY | Constant representing the value for negative infinity.
Number.POSITIVE_INFINITY | Constant representing the value for positive infinity. This value is the same as the global variable Infinity.

Constructor for the Number class

Availability

Flash Player 5.

Usage

new Number(value)

Parameters

value The numeric value of the Number object being created, or a value to be converted to a number.

Returns

A reference to a Number object.

Description

Constructor; creates a new Number object. You must use the Number constructor when using Number.toString() and Number.valueOf(). You do not use a constructor when using the properties of a Number object. The new Number constructor is primarily used as a placeholder. A Number object is not the same as the Number() function that converts a parameter to a primitive value.

Example

The following code constructs new Number objects.

n1 = new Number(3.4);
n2 = new Number(-10);

See also

Number()


Number.MAX_VALUE

Availability

Flash Player 5.

Usage

Number.MAX_VALUE

Description

Property; the largest representable number (double-precision IEEE-754). This number is approximately 1.79E+308.


Number.MIN_VALUE

Availability

Flash Player 5.

Usage

Number.MIN_VALUE

Description

Property; the smallest representable number (double-precision IEEE-754). This number is approximately 5e-324.


Number.NaN

Availability

Flash Player 5.

Usage

Number.NaN

Description

Property; the IEEE-754 value representing Not A Number (NaN).

See also

isNaN(), NaN


Number.NEGATIVE_INFINITY

Availability

Flash Player 5.

Usage

Number.NEGATIVE_INFINITY

Description

Property; specifies the IEEE-754 value representing negative infinity. The value of this property is the same as that of the constant -Infinity.

Negative infinity is a special numeric value that is returned when a mathematical operation or function returns a negative value larger than can be represented.


Number.POSITIVE_INFINITY

Availability

Flash Player 5.

Usage

Number.POSITIVE_INFINITY

Description

Property; specifies the IEEE-754 value representing positive infinity. The value of this property is the same as that of the constant Infinity.

Positive infinity is a special numeric value that is returned when a mathematical operation or function returns a value larger than can be represented.


Number.toString()

Availability

Flash Player 5; behavior changed in Flash Player 7.

Usage

myNumber.toString(radix)

Parameters

radix Specifies the numeric base (from 2 to 36) to use for the number-to-string conversion. If you do not specify the radix parameter, the default value is 10.

Returns

A string.

Description

Method; returns the string representation of the specified Number object (myNumber).

If myNumber is undefined, the return value is as follows:

  • In files published for Flash Player 6 or earlier, the result is 0.
  • In files published for Flash Player 7 or later, the result is NaN.

Example

The following example uses 2 and 8 for the radix parameter and returns a string that contains the corresponding representation of the number 9.

myNumber = new Number (9);
trace(myNumber.toString(2)); / 1001
trace(myNumber.toString(8)); / 11

See also

NaN


Number.valueOf()

Availability

Flash Player 5.

Usage

myNumber.valueOf()

Parameters

None.

Returns

A number.

Description

Method; returns the primitive value type of the specified Number object.


Number()

Availability

Flash Player 4; behavior changed in Flash Player 7.

Usage

Number(expression)

Parameters

expression An expression to convert to a number.

Returns

A number or NaN.

Description

Function; converts the parameter expression to a number and returns a value as follows:

  • If expression is a number, the return value is expression.
  • If expression is a Boolean value, the return value is 1 if expression is true, 0 if expression is false.
  • If expression is a string, the function attempts to parse expression as a decimal number with an optional trailing exponent, that is, 1.57505e-3.
  • If expression is undefined, the return value is as follows:
    • In files published for Flash Player 6 or earlier, the result is 0.
    • In files published for Flash Player 7 or later, the result is NaN.

This function is used to convert Flash 4 files containing deprecated operators that are imported into the Flash 5 or later authoring environment. For more information, see & (bitwise AND operator).

See also

NaN, Number class


Object class

Availability

Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly).

Description

The Object class is at the root of the ActionScript class hierarchy. This class contains a small subset of the features provided by the JavaScript Object class.

Method summary for the Object class

Method | Description
Object.addProperty() | Creates a getter/setter property on an object.
Object.registerClass() | Associates a movie clip symbol with an ActionScript object class.
Object.toString() | Converts the specified object to a string and returns it.
Object.unwatch() | Removes the watchpoint that Object.watch() created.
Object.valueOf() | Returns the primitive value of an object.
Object.watch() | Registers an event handler to be invoked when a specified property of an ActionScript object changes.

Property summary for the Object class

Property | Description
Object.__proto__ | A reference to the prototype property of the object's constructor function.

Constructor for the Object class

Availability

Flash Player 5.

Usage

new Object([value])

Parameters

value A number, Boolean value, or string to be converted to an object. This parameter is optional. If you do not specify value, the constructor creates a new object with no defined properties.

Returns

A reference to an Object object.

Description

Constructor; creates a new Object object.


Object.addProperty()

Availability

Flash Player 6. In external class files, you can use get or set instead of this method.

Usage

myObject.addProperty(prop, getFunc, setFunc)

Parameters

prop The name of the object property to create.

getFunc The function that is invoked to retrieve the value of the property; this parameter is a function object.

setFunc The function that is invoked to set the value of the property; this parameter is a function object. If you pass the value null for this parameter, the property is read-only.

Returns

Returns a value of true if the property is successfully created; otherwise, returns false.

Description

Method; creates a getter/setter property. When Flash reads a getter/setter property, it invokes the get function and the function's return value becomes a value of prop. When Flash writes a getter/setter property, it invokes the set function and passes it the new value as a parameter. If a property with the given name already exists, the new property overwrites it.

A "get" function is a function with no parameters. Its return value can be of any type. Its type can change between invocations. The return value is treated as the current value of the property.

A "set" function is a function that takes one parameter, which is the new value of the property. For example, if property x is assigned by the statement x = 1, the set function is passed the parameter 1 of type number. The return value of the set function is ignored.

You can add getter/setter properties to prototype objects. If you add a getter/setter property to a prototype object, all object instances that inherit the prototype object inherit the getter/setter property. This makes it possible to add a getter/setter property in one location, the prototype object, and have it propagate to all instances of a class (much like adding methods to prototype objects). If a get/set function is invoked for a getter/setter property in an inherited prototype object, the reference passed to the get/set function will be the originally referenced object, not the prototype object.

If invoked incorrectly, Object.addProperty() may fail with an error. The following table describes errors that may occur:

Error condition | What happens
prop is not a valid property name; for instance, an empty string. | Returns false and the property is not added.
getFunc is not a valid function object. | Returns false and the property is not added.
setFunc is not a valid function object. | Returns false and the property is not added.

Example

Usage 1: An object has two internal methods, setQuantity() and getQuantity(). A property, bookcount, can be used to invoke these methods when it is either set or retrieved. A third internal method, getTitle(), returns a read-only value that is associated with the property bookname:

function Book() {

this.setQuantity = function(numBooks) {

    this.books = numBooks;
  }

this.getQuantity = function() {
  return this.books;

  }
  this.getTitle = function() {
    return "Catcher in the Rye";
  }
  this.addProperty("bookcount", this.getQuantity, this.setQuantity);
  this.addProperty("bookname", this.getTitle, null);
}
myBook = new Book();
myBook.bookcount = 5;
order = "You ordered " + myBook.bookcount + " copies of " + myBook.bookname;

When a script retrieves the value of myBook.bookcount, the ActionScript interpreter automatically invokes myBook.getQuantity(). When a script modifies the value of myBook.bookcount, the interpreter invokes myObject.setQuantity(). The bookname property does not specify a set function, so attempts to modify bookname are ignored.

Usage 2: The above example of bookcount and bookname works, but the properties bookcount and bookname are added to every instance of the Book object. That means that the cost of having the properties is two property slots for every instance of the object. If there are many properties like bookcount and bookname in a class, they could consume a great deal of memory. Instead, you can add the properties to Book.prototype:

function Book () {}
Book.prototype.setQuantity = function(numBooks) {
  this.books = numBooks;
}
Book.prototype.getQuantity = function() {
  return this.books;
}
Book.prototype.getTitle = function() {
  return "Catcher in the Rye";
}
Book.prototype.addProperty("bookcount", Book.prototype.getQuantity, Book.prototype.setQuantity);
Book.prototype.addProperty("bookname", Book.prototype.getTitle, null);
myBook = new Book();
myBook.bookcount = 5;
order = "You ordered "+myBook.bookcount+" copies of "+myBook.bookname;

Now, the bookcount and bookname properties exist only in one place: the Book.prototype object. The effect, however, is the same as that of the code in Usage 1, which added bookcount and bookname directly to every instance. If bookcount or bookname is accessed in a Book instance, the prototype chain is ascended and the getter/setter property in Book.prototype is found.

Usage 3: The built-in properties TextField.scroll and TextField.maxscroll are getter/setter properties. The TextField object has internal methods getScroll(), setScroll(), and getMaxScroll(). The TextField constructor creates the getter/setter properties and points them to the internal get/set methods, as in the following:

this.addProperty("scroll", this.getScroll, this.setScroll);
this.addProperty("maxscroll", this.getMaxScroll, null);

When a script retrieves the value of myTextField.scroll, the ActionScript interpreter automatically invokes myTextField.getScroll(). When a script modifies the value of myTextField.scroll, the interpreter invokes myTextField.setScroll(). The maxscroll property does not specify a set function, so attempts to modify maxscroll are ignored.

Usage 4: Although the built-in TextField.scroll and TextField.maxscroll properties work in the Usage 3 example, the properties scroll and maxscroll are added to every instance of the TextField object. That means the cost of having the properties is two property slots for every instance of the object. If there are many properties like scroll and maxscroll in a class, they could consume a great deal of memory. Instead, you can add the scroll and maxscroll properties to TextField.prototype:

TextField.prototype.addProperty("scroll", this.getScroll, this.setScroll);
TextField.prototype.addProperty("maxscroll", this.getMaxScroll, null);

Now, the scroll and maxscroll properties only exist in one place: the TextField.prototype object. The effect, however, is the same as the above code that added scroll and maxscroll directly to every instance. If scroll or maxscroll is accessed in a TextField instance, the prototype chain is ascended and the getter/setter property in TextField.prototype is found.


Object.__proto__

Availability

Flash Player 5.

Usage

myObject.__proto__

Parameters

None.

Description

Property; refers to the prototype property of the constructor function that created myObject. The __proto__ property is automatically assigned to all objects when they are created. The ActionScript interpreter uses the __proto__ property to access the prototype property of the object's constructor function to find out what properties and methods the object inherits from its class.


Object.registerClass()

Availability

Flash Player 6. If you are using external class files, you can use the ActionScript 2.0 Class field in the Linkage Properties or Symbol Properties dialog box to associate an object with a class instead of using this method.

Usage

Object.registerClass(symbolID, theClass)

Parameters

symbolID The linkage identifier of the movie clip symbol, or the string identifier for the ActionScript class.

theClass A reference to the constructor function of the ActionScript class, or null to unregister the symbol.

Returns

If the class registration succeeds, a value of true is returned; otherwise, false is returned.

Description

Method; associates a movie clip symbol with an ActionScript object class. If a symbol doesn't exist, Flash creates an association between a string identifier and an object class.

When an instance of the specified movie clip symbol is placed by the Timeline, it is registered to the class specified by the theClass parameter rather than to class MovieClip.

When an instance of the specified movie clip symbol is created by means of MovieClip.attachMovie() or MovieClip.duplicateMovieClip(), it is registered to the class specified by theClass rather than to the MovieClip class. If theClass is null, this method removes any ActionScript class definition associated with the specified movie clip symbol or class identifier. For movie clip symbols, any existing instances of the movie clip remain unchanged, but new instances of the symbol are associated with the default class MovieClip.

If a symbol is already registered to a class, this method replaces it with the new registration.

When a movie clip instance is placed by the Timeline or created using attachMovie() or duplicateMovieClip(), ActionScript invokes the constructor for the appropriate class with the keyword this pointing to the object. The constructor function is invoked with no parameters.

If you use this method to register a movie clip with an ActionScript class other than MovieClip, the movie clip symbol doesn't inherit the methods, properties, and events of the built-in MovieClip class unless you include the MovieClip class in the prototype chain of the new class. The following code creates a new ActionScript class called theClass that inherits the properties of the MovieClip class:

theClass.prototype = new MovieClip();

See also

MovieClip.attachMovie(), MovieClip.duplicateMovieClip()


Object.toString()

Availability

Flash Player 5.

Usage

myObject.toString()

Parameters

None.

Returns

A string.

Description

Method; converts the specified object to a string and returns it.


Object.unwatch()

Availability

Flash Player 6.

Usage

myObject.unwatch (prop)

Parameters

prop The name of the object property that should no longer be watched, as a string.

Returns

A Boolean value.

Description

Method; removes a watchpoint that Object.watch() created. This method returns a value of true if the watchpoint was successfully removed; otherwise, it returns a false value.


Object.valueOf()

Availability

Flash Player 5.

Usage

myObject.valueOf()

Parameters

None.

Returns

The primitive value of the specified object, or the object itself.

Description

Method; returns the primitive value of the specified object. If the object does not have a primitive value, the object itself is returned.


Object.watch()

Availability

Flash Player 6.

Usage

myObject.watch( prop, callback [, userData] )

Parameters

prop A string indicating the name of the object property to watch.

callback The function to invoke when the watched property changes. This parameter is a function object, not a function name as a string. The form of callback is callback(prop, oldval, newval, userData).

userData An arbitrary piece of ActionScript data that is passed to the callback method. If the userData parameter is omitted, undefined is passed to the callback method. This parameter is optional.

Returns

A value of true if the watchpoint is created successfully; otherwise, returns a false value.

Description

Method; registers an event handler to be invoked when a specified property of an ActionScript object changes. When the property changes, the event handler is invoked with myObject as the containing object. You must return the new value from the Object.watch() method, or the watched object property is assigned a value of undefined.

A watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or oldval). If you delete a property for which a watchpoint has been set, that watchpoint does not disappear. If you later recreate the property, the watchpoint is still in effect. To remove a watchpoint, use the Object.unwatch method.

Only a single watchpoint may be registered on a property. Subsequent calls to Object.watch() on the same property replace the original watchpoint.

The Object.watch() method behaves similarly to the Object.watch() function in Netscape JavaScript 1.2 and later. The primary difference is the userData parameter, which is a Flash addition to Object.watch() that Netscape Navigator does not support. You can pass the userData parameter to the event handler and use it in the event handler.

The Object.watch() method cannot watch getter/setter properties. Getter/setter properties operate through "lazy evaluation"— the value of the property is not determined until the property is actually queried. "Lazy evaluation" is often efficient because the property is not constantly updated; it is, rather, evaluated when needed. However, Object.watch() needs to evaluate a property in order to fire watchpoints on it. To work with a getter/setter property, Object.watch() needs to evaluate the property constantly, which is inefficient.

Generally, predefined ActionScript properties, such as _x, _y, _width and _height, are getter/setter properties, and thus cannot be watched with Object.watch().

See also

Object.addProperty(), Object.unwatch()


Object()

Availability

Flash Player 5 .

Usage

Object( [ value ] )

Parameters

value A number, string, or Boolean value.

Returns

An object.

Description

Conversion function; creates a new, empty object or converts the specified number, string, or Boolean value to an object. This command is equivalent to creating an object using the Object constructor (see Constructor for the Object class).


on()

Availability

Flash 2. Not all events are supported in Flash 2.

Usage

on(mouseEvent) {
  // your statements here
}

Parameters

statement(s) The instructions to execute when the mouseEvent takes place.

A mouseEvent is a trigger called an "event." When the event takes place, the statements following it within curly braces execute. Any of the following values can be specified for the mouseEvent parameter:

  • press The mouse button is pressed while the pointer is over the button.
  • release The mouse button is released while the pointer is over the button.
  • releaseOutside The mouse button is released while the pointer is outside the button after the button is pressed while the pointer is inside the button.
  • rollOut The pointer rolls outside of the button area.
  • rollOver The mouse pointer rolls over the button.
  • dragOut While the pointer is over the button, the mouse button is pressed and then rolls outside the button area.
  • dragOver While the pointer is over the button, the mouse button has been pressed then rolled outside the button and then rolled back over the button.
  • keyPress ("key") The specified key is pressed. For the key portion of the parameter, specify a key code or key constant. For a list of key codes associated with the keys on a standard keyboard, see Keyboard Keys and Key Code Values; for a list of key constants, see Property summary for the Key class.

Description

Event handler; specifies the mouse event or keypress that triggers an action.

Example

In the following script, the startDrag() action executes when the mouse is pressed and the conditional script is executed when the mouse is released and the object is dropped.

on(press) {
  startDrag("rabbit");
}
on(release) {
  trace(_root.rabbit._y);
  trace(_root.rabbit._x);
  stopDrag();
}

See also

onClipEvent()


onClipEvent()

Availability

Flash Player 5.

Usage

onClipEvent(movieEvent){
  // your statements here
}

Parameters

A movieEvent is a trigger called an event. When the event takes place, the statements following it within curly braces are executed. Any of the following values can be specified for the movieEvent parameter:

  • load The action is initiated as soon as the movie clip is instantiated and appears in the Timeline.
  • unload The action is initiated in the first frame after the movie clip is removed from the Timeline. The actions associated with the Unload movie clip event are processed before any actions are attached to the affected frame.
  • enterFrame The action is triggered continually at the frame rate of the movie clip. The actions associated with the enterFrame clip event are processed before any frame actions that are attached to the affected frames.
  • mouseMove The action is initiated every time the mouse is moved. Use the _xmouse and _ymouse properties to determine the current mouse position.
  • mouseDown The action is initiated when the left mouse button is pressed.
  • mouseUp The action is initiated when the left mouse button is released.
  • keyDown The action is initiated when a key is pressed. Use Key.getCode() to retrieve information about the last key pressed.
  • keyUp The action is initiated when a key is released. Use the Key.getCode() method to retrieve information about the last key pressed.
  • data The action is initiated when data is received in a loadVariables() or loadMovie() action. When specified with a loadVariables() action, the data event occurs only once, when the last variable is loaded. When specified with a loadMovie() action, the data event occurs repeatedly, as each section of data is retrieved.

Description

Event handler; triggers actions defined for a specific instance of a movie clip.

Example

The following statement includes the script from an external file when the SWF file is exported; the actions in the included script are run when the movie clip they are attached to loads:

onClipEvent(load) {
  #include "myScript.as"
}

The following example uses onClipEvent() with the keyDown movie event. The keyDown movie event is usually used in conjunction with one or more methods and properties of the Key object. The following script uses Key.getCode() to find out which key the user has pressed; if the pressed key matches the Key.RIGHT property, the movie is sent to the next frame; if the pressed key matches the Key.LEFT property, the movie is sent to the previous frame.

onClipEvent(keyDown) {
  if (Key.getCode() == Key.RIGHT) {
    _parent.nextFrame();
  } else if (Key.getCode() == Key.LEFT){
    _parent.prevFrame();
  }
}

The following example uses onClipEvent() with the mouseMove movie event. The _xmouse and _ymouse properties track the position of the mouse each time the mouse moves.

onClipEvent(mouseMove) {
  stageX=_root._xmouse;
  stageY=_root._ymouse;
}

See also

Key class, MovieClip._xmouse, MovieClip._ymouse, on(), updateAfterEvent()


onUpdate

Availability

Flash Player 6.

Usage

function onUpdate() {
   ...statements...;
}

Parameters

None.

Returns

Nothing.

Description

Event handler; onUpdate is defined for a Live Preview movie used with a component. When an instance of a component on the Stage has a Live Preview movie, the authoring tool invokes the Live Preview movie's onUpdate function whenever the component parameters of the component instance change. The onUpdate function is invoked by the authoring tool with no parameters, and its return value is ignored. The onUpdate function should be declared on the main Timeline of the Live Preview movie.

Defining an onUpdate function in a Live Preview movie is optional.

For more information on Live Preview movies, see Using Components.

Example

The onUpdate function gives the Live Preview movie an opportunity to update its visual appearance to match the new values of the component parameters. When the user changes a parameter value in the components Property inspector or Component Parameters panel, onUpdate is invoked. The onUpdate function will do something to update itself. For instance, if the component includes a color parameter, the onUpdate function might alter the color of a movie clip inside the Live Preview to reflect the new parameter value. In addition, it might store the new color in an internal variable.

Here is an example of using the onUpdate function to pass parameter values through an empty movie clip in the Live Preview movie. Suppose you have a labeled button component with a variable labelColor, which specifies the color of the text label color. The following code is in the first frame of the main Timeline of the component movie:

//Define the textColor parameter variable to specify the color of the button label text.
buttonLabel.textColor = labelColor;

In the Live Preview movie, place an empty movie clip named "xch" in the Live Preview movie. Then place the following code in the first frame of the Live Preview movie. Add "xch" to the labelColor variable path, to pass the variable through the my_mc movie clip:

//Write an onUpdate function, adding "my_mc." to the parameter variable names:
function onUpdate (){
  buttonLabel.textColor = my_mc.labelColor;
}


or

Availability

Flash 4. This operator has been deprecated in favor of the || (logical OR) operator.

Usage

condition1 or condition2

Parameters

condition1,2 An expression that evaluates to true or false.

Returns

Nothing.

Description

Operator; evaluates condition1 and condition2, and if either expression is true, then the whole expression is true.

See also

|| (logical OR), | (bitwise OR)


ord

Availability

Flash Player 4. This function has been deprecated in favor of the methods and properties of the String class.

Usage

ord(character)

Parameters

character The character to convert to an ASCII code number.

Returns

Nothing.

Description

String function; converts characters to ASCII code numbers.

See also

String class


_parent

Availability

Flash Player 5.

Usage

_parent.property
_parent._parent.property

Description

Identifier; specifies or returns a reference to the movie clip or object that contains the current movie clip or object. The current object is the object containing the ActionScript code that references _parent. Use _parent to specify a relative path to movie clips or objects that are above the current movie clip or object.

Example

In the following example, the movie clip desk is a child of the movie clip classroom. When the following script executes inside the movie clip desk, the playhead will jump to Frame 10 in the Timeline of the movie clip classroom.

_parent.gotoAndStop(10);

See also

_root, targetPath


parseFloat()

Availability

Flash Player 5.

Usage

parseFloat(string)

Parameters

string The string to read and convert to a floating-point number.

Returns

A number or Nan.

Description

Function; converts a string to a floating-point number. The function reads, or "parses," and returns the numbers in a string until it reaches a character that is not a part of the initial number. If the string does not begin with a number that can be parsed, parseFloat returns NaN. White space preceding valid integers is ignored, as are trailing nonnumeric characters.

Example

The following examples use the parseFloat function to evaluate various types of numbers.

parseFloat("-2") returns -2

parseFloat("2.5") returns 2.5

parseFloat("3.5e6") returns 3.5e6, or 3500000

parseFloat("foobar") returns NaN

parseFloat(" 5.1") returns 5.1

parseFloat("3.75math") returns 3.75

parseFloat("0garbage") returns 0

See also

NaN


parseInt

Availability

Flash Player 5.

Usage

parseInt(expression [, radix])

Parameters

expression A string to convert to a integer.

radix Optional; an integer representing the radix (base) of the number to parse. Legal values are from 2 to 36.

Returns

A number or NaN.

Description

Function; converts a string to an integer. If the specified string in the parameters cannot be converted to a number, the function returns NaN. Strings beginning with 0x are interpreted as hexadecimal numbers. Integers beginning with 0 or specifying a radix of 8 are interpreted as octal numbers. White space preceding valid integers is ignored, as are trailing nonnumeric characters.

Example

The following examples use the parseInt function to evaluate various types of numbers.

parseInt("3.5")

// returns 3

parseInt("bar")
// returns NaN

parseInt("4foo")
// returns 4

The following are examples of hexadecimal conversions:

parseInt("0x3F8")
// returns 1016

parseInt("3E8", 16)
// returns 1000

The following is an example of a binary conversion:

parseInt("1010", 2)
// returns 10 (the decimal representation of the binary 1010)

The following are examples of octal number parsing:

parseInt("0777")
parseInt("777", 8)
// returns 511 (the decimal representation of the octal 777)


play()

Availability

Flash 2.

Usage

play()

Parameters

None.

Returns

Nothing.

Description

Function; moves the playhead forward in the Timeline.

Example

The following code uses an if statement to check the value of a name the user enters. If the user enters Steve, the play() action is called and the playhead moves forward in the Timeline. If the user enters anything other than Steve, the SWF file does not play and a text field with the variable name alert is displayed.

stop();
if (name == "Steve") {
  play();
} else {
  alert="You are not Steve!";
}

See also

gotoAndPlay(), MovieClip.gotoAndPlay()


prevFrame()

Availability

Flash 2.

Usage

prevFrame()

Parameters

None.

Returns

Nothing.

Description

Function; sends the playhead to the previous frame and stops it. If the current frame is Frame 1, the playhead does not move.

Example

When the user clicks a button that has the following handler attached to it, the playhead is sent to the previous frame.

on(release) {
  prevFrame();
}

See also

MovieClip.prevFrame()


prevScene()

Availability

Flash 2.

Usage

prevScene()

Parameters

None.

Returns

Nothing.

Description

Function; sends the playhead to Frame 1 of the previous scene and stops it.

See also

nextScene()


print()

Availability

Flash Player 4.20.

Note: If you are authoring for Flash Player 7 or later, you can create a PrintJob object, which gives you (and the user) more control over the printing process. For more information, see the PrintJob class entry.

Usage

print(target, "Bounding box")

Parameters

target The instance name of a movie clip to print. By default, all of the frames in the target instance print. If you want to print specific frames in the movie clip, assign a #p frame label to those frames.

Bounding box A modifier that sets the print area of the movie clip. Enclose this parameter in quotation marks, and specify one of the following values:

  • bmovie Designates the bounding box of a specific frame in a movie as the print area for all printable frames in the movie. Assign a #b frame label to the frame whose bounding box you want to use as the print area.
  • bmax Designates a composite of all of the bounding boxes of all the printable frames as the print area. Specify bmax when the printable frames in your movie vary in size.
  • bframe Indicates that the bounding box of each printable frame should be used as the print area for that frame. This changes the print area for each frame and scales the objects to fit the print area. Use bframe if you have objects of different sizes in each frame and want each object to fill the printed page.

Returns

None.

Description

Function; prints the target movie clip according to the boundaries specified in the parameter (bmovie, bmax, or bframe). If you want to print specific frames in the target movie clip, attach a #p frame label to those frames. Although print() results in higher quality prints than printAsBitmap(), it cannot be used to print movie clips that use alpha transparencies or special color effects.

If you use bmovie for the Bounding box parameter but do not assign a #b label to a frame, the print area is determined by the Stage size of the loaded movie. (The loaded movie does not inherit the main movie's Stage size.)

All of the printable elements in a movie must be fully loaded before printing can begin.

The Flash Player printing feature supports PostScript and non-PostScript printers. Non-PostScript printers convert vectors to bitmaps.

Example

The following example prints all of the printable frames in the movie clip my_mc with the print area defined by the bounding box of the frame with the #b frame label attached:

print(my_mc,"bmovie");

The following example prints all of the printable frames in my_mc with a print area defined by the bounding box of each frame:

print(my_mc,"bframe");

See also

printAsBitmap(), printAsBitmapNum(), PrintJob class, printNum()


printAsBitmap()

Availability

Flash Player 4.20.

Note: If you are authoring for Flash Player 7 or later, you can create a PrintJob object, which gives you (and the user) more control over the printing process. For more information, see the PrintJob class entry.

Usage

printAsBitmap(target, "Bounding box")

Parameters

target The instance name of movie clip to print. By default, all of the frames in the movie are printed. If you want to print specific frames in the movie, attach a #p frame label to those frames.

Bounding box A modifier that sets the print area of the movie. Enclose this parameter in quotation marks, and specify one of the following values:

  • bmovie Designates the bounding box of a specific frame in a movie as the print area for all printable frames in the movie. Assign a #b frame label to the frame whose bounding box you want to use as the print area.
  • bmax Designates a composite of all of the bounding boxes of all the printable frames as the print area. Specify the bmax parameter when the printable frames in your movie vary in size.
  • bframe Indicates that the bounding box of each printable frame should be used as the print area for that frame. This changes the print area for each frame and scales the objects to fit the print area. Use bframe if you have objects of different sizes in each frame and want each object to fill the printed page.

Returns

Nothing.

Description

Function; prints the target movie clip as a bitmap according to the boundaries specified in the parameter (bmovie, bmax, or bframe). Use printAsBitmap() to print movies that contain frames with objects that use transparency or color effects. The printAsBitmap() action prints at the highest available resolution of the printer in order to maintain as much definition and quality as possible.

If your movie does not contain alpha transparencies or color effects, Macromedia recommends that you use print() for better quality results.

If you use bmovie for the Bounding box parameter but do not assign a #b label to a frame, the print area is determined by the Stage size of the loaded movie. (The loaded movie does not inherit the main movie's Stage size.)

All of the printable elements in a movie must be fully loaded before printing can begin.

The Flash Player printing feature supports PostScript and non-PostScript printers. Non-PostScript printers convert vectors to bitmaps.

See also

print(), printAsBitmapNum(), PrintJob class, printNum()


printAsBitmapNum()

Availability

Flash Player 5.

Note: If you are authoring for Flash Player 7 or later, you can create a PrintJob object, which gives you (and the user) more control over the printing process. For more information, see the PrintJob class entry.

Usage

printAsBitmapNum(level, "Bounding box")

Parameters

level The level in Flash Player to print. By default, all of the frames in the level print. If you want to print specific frames in the level, assign a #p frame label to those frames.

Bounding box A modifier that sets the print area of the movie. Enclose this parameter in quotation marks, and specify one of the following values:

  • bmovie Designates the bounding box of a specific frame in a movie as the print area for all printable frames in the movie. Assign a #b frame label to the frame whose bounding box you want to use as the print area.
  • bmax Designates a composite of all of the bounding boxes of all the printable frames as the print area. Specify the bmax parameter when the printable frames in your movie vary in size.
  • bframe Indicates that the bounding box of each printable frame should be used as the print area for that frame. This changes the print area for each frame and scales the objects to fit the print area. Use bframe if you have objects of different sizes in each frame and want each object to fill the printed page.

Returns

None.

Description

Function; prints a level in Flash Player as a bitmap according to the boundaries specified in the parameter (bmovie, bmax, or bframe). Use printAsBitmapNum() to print movies that contain frames with objects that use transparency or color effects. The printAsBitmapNum() action prints at the highest available resolution of the printer in order to maintain the highest possible definition and quality. To calculate the printable file size of a frame designated to print as a bitmap, multiply pixel width by pixel height by printer resolution.

If your movie does not contain alpha transparencies or color effects, it is recommended that you use printNum() for better quality results.

If you use bmovie for the Bounding box parameter but do not assign a #b label to a frame, the print area is determined by the Stage size of the loaded movie. (The loaded movie does not inherit the main movie's Stage size.)

All of the printable elements in a movie must be fully loaded before printing can begin.

The Flash Player printing feature supports PostScript and non-PostScript printers. Non-PostScript printers convert vectors to bitmaps.

See also

print(), printAsBitmap(), PrintJob class, printNum()


PrintJob class

Availability

Flash Player 7.

Description

The PrintJob class lets you create content and print it to one or more pages. This class, in addition to offering improvements to print functionality provided by the print() method, lets you render dynamic content offscreen, prompt users with a single print dialog box, and print an unscaled document with proportions that map to the proportions of the content. This capability is especially useful for rendering and printing external dynamic content, such as database content and dynamic text.

Additionally, with properties populated by PrintJob.start(), your document can access your user's printer settings, such as page height, width, and orientation, and you can configure your document to dynamically format Flash content that's appropriate for the printer settings.

Method summary for the PrintJob class

You must use the methods for PrintJob class in the order listed in the following table.

Method | Description
PrintJob.start() | Displays the operating system's print dialog boxes and starts spooling.
PrintJob.addPage() | Adds one page to the print spooler.
PrintJob.send() | Sends spooled pages to the printer.

Constructor for the PrintJob class

Availability

Flash Player 7.

Usage

my_pj = new PrintJob()

Parameters

None.

Returns

A reference to a PrintJob object.

Description

Constructor; creates a PrintJob object that you can use to print one or more pages.

To implement a print job, use the methods below in the sequence shown. You must place all commands relating to a specific print job on the same frame.

// create PrintJob object
my_pj = new PrintJob();                        // instantiate object

// display print dialog box
my_pj.start();                                 // initiate print job

// add specified area to print job
// repeat once for each page to be printed
my_pj.addPage([params]);                       // send page(s) to spooler
my_pj.addPage([params]);
my_pj.addPage([params]);
my_pj.addPage([params]);

// send pages from the spooler to the printer
my_pj.send();                                   // print page(s)

// clean up
delete my_pj;                                    // delete object

In your own implementation of PrintJob objects, you should check for return values from PrintJob.start() and PrintJob.addPage() before continuing to print. See the examples for PrintJob.addPage().

You cannot create a PrintJob object until any PrintJob object that you already created is no longer active (that is, it either completed successfully or failed). If you try to create a second PrintJob object (by calling new PrintJob()) while the first PrintJob object is still active, the second PrintJob object will not be created.

Example

See PrintJob.addPage().

See also

PrintJob.addPage(), PrintJob.send(), PrintJob.start()


PrintJob.addPage()

Availability

Flash Player 7.

Usage

my_pj.addPage(target [, printArea] [, options ] [, frameNumber])

Parameters

target The level or instance name of the movie clip to print. Pass a number to specify a level (for example, 0 is the _root movie), or a string (in quotation marks) to specify the instance name of a movie clip.

printArea An optional object that specifies the area to print, in the following format:

{xMin:topLeft, xMax:topRight, yMin:bottomLeft, yMax:bottomRight}

The coordinates you specify for printArea represent screen pixels relative to the registration point of the _root movie (if target = 0) or of the level or movie clip specified by target. You must provide all four coordinates. The width (xMax-xMin) and height (yMax-yMin) must each be greater than 0.

Points are print units of measurement, and pixels are screen units of measurement; one point is equal in size to one pixel. You can use the following equivalencies to convert inches or centimeters to twips, pixels or points (a twip is 1/20 of a pixel):

  • 1 pixel = 1 point = 1/72 inch = 20 twips
  • 1 inch = 72 pixels = 72 points = 1440 twips
  • 1 cm = 567 twips

Note: If you have previously used print(), printAsBitmap(), printAsBitmapNum(), or printNum() to print from Flash, you used a #b frame label to specify the area to print. When using the addPage() method, you must use the printArea parameter to specify the print area; #b frame labels are ignored.

If you omit the printArea parameter, or if it is passed incorrectly, the full Stage area of target is printed. If you don't want to specify a value for printArea but want to specify a value for options or frameNumber, pass null for printArea.

options An optional parameter that specifies whether to print as vector or bitmap, in the following format:

{printAsBitmap:Boolean}

By default, pages are printed in vector format. To print target as a bitmap, pass true for printAsBitmap. The default value is false, which represents a request for vector printing. Keep in mind the following suggestions when determining which value to use:

  • If the content that you're printing includes a bitmap image, use {printAsBitmap:true} to include any transparency and color effects.
  • If the content does not include bitmap images, omit this parameter or use {printAsBitmap:false} to print the content in higher quality vector format.

If options is omitted or passed incorrectly, vector printing is implemented. If you don't want to specify a value for options but want to specify a value for frameNumber, pass null for options.

frameNumber An optional number that lets you specify which frame to print; notice that any ActionScript on the frame is not invoked. If you omit this parameter, the current frame in target is printed.

Note: If you previously used print(), printAsBitmap(), printAsBitmapNum(), or printNum() to print from Flash, you may have used a #p frame label on multiple frames to specify which pages to print. To use PrintJob.addPage() to print multiple frames, you must issue a PrintJob.addPage() command for each frame; #p frame labels are ignored. For one way to do this programmatically, see the example later in this entry.

Returns

A Boolean value of true if the page was successfully sent to the print spooler, false otherwise.

Description

Method; sends the specified level or movie clip as a single page to the print spooler. Before using this method, you must use PrintJob.start(); after calling PrintJob.addPage() one or more times for a print job, you must use PrintJob.send() to send the spooled pages to the printer.

If this method returns false (for example, if you haven't called PrintJob.start() or the user canceled the print job), any subsequent calls to PrintJob.addPage() will fail. However, if prior calls to PrintJob.addPage() were successful, the concluding PrintJob.send() command sends the successfully spooled pages to the printer.

If you passed a value for printArea, the xMin and yMin coordinates map to the upper left corner (0,0 coordinates) of the printable area on the page; the printable area is determined by the pageHeight and pageWidth properties set by PrintJob.start(). Because the printout aligns with the upper left corner of the printable area on the page, the printout is clipped to the right and/or bottom if the area defined in printArea is bigger than the printable area on the page. If you haven't passed a value for printArea and the Stage is larger than the printable area, the same type of clipping takes place.

If you want to scale a movie clip before you print it, set its MovieClip._xscale and MovieClip._yscale properties before calling this method, then set them back to their original values afterward. The scale of a movie clip has no relation to printArea. That is, if you specify that you print an area that is 50 x 50 pixels in size, 2500 pixels are printed. If you have scaled the movie clip, the same 2500 pixels are printed, but at the scaled size.

The Flash Player printing feature supports PostScript and non-PostScript printers. Non-PostScript printers convert vectors to bitmaps.

Example

The following example illustrates several ways to issue the addPage() command.

my_btn.onRelease = function()
{
  var pageCount = 0;

  var my_pj = new PrintJob();

  if (my_pj.start())
  {
    // Print entire current frame of the _root movie in vector format
    if (my_pj.addPage(0))
    {
      pageCount++;

      // Starting at 0,0, print an area 400 pixels wide and 500 pixels high
      // of the current frame of the _root movie in vector format
      if (my_pj.addPage(0, {xMin:0,xMax:400,yMin:0,yMax:500}))
      {
        pageCount++;

        // Starting at 0,0, print an area 400 pixels wide and 500 pixels high
        // of frame 1 of the _root movie in bitmap format
        if (my_pj.addPage(0, {xMin:0,xMax:400,yMin:0,yMax:500},
            {printAsBitmap:true}, 1))
        {
          pageCount++;

          // Starting 50 pixels to the right of 0,0 and 70 pixels down,
          // print an area 500 pixels wide and 600 pixels high
          // of frame 4 of level 5 in vector format
          if (my_pj.addPage(5, {xMin:50,xMax:550,yMin:70,yMax:670},null, 4))
          {
            pageCount++;

            // Starting at 0,0, print an area 400 pixels wide
            // and 400 pixels high of frame 3 of the "dance_mc" movie clip
            // in bitmap format
            if (my_pj.addPage("dance_mc",
                {xMin:0,xMax:400,yMin:0,yMax:400},{printAsBitmap:true}, 3))
            {
              pageCount++;

              // Starting at 0,0, print an area 400 pixels wide
              // and 600 pixels high of frame 3 of the "dance_mc" movie clip
              // in vector format at 50% of its actual size
              var x = dance_mc._xscale;
              var y = dance_mc._yscale;
              dance_mc._xscale = 50;
              dance_mc._yscale = 50;

              if (my_pj.addPage("dance_mc",
                  {xMin:0,xMax:400,yMin:0,yMax:600},null, 3))
              {
                pageCount++;
              }

              dance_mc._xscale = x;
              dance_mc._yscale = y;
            }
          }
        }
      }
    }
  }

  if (pageCount)
  {
    my_pj.send();
  }
  delete my_pj;
}

The following example shows how you might use the value of the orientation property to adjust the printout.

// create PrintJob object
var my_pj = new PrintJob();

// display print dialog box
my_pj.start();

// check the user's printer orientation setting
// and add appropriate print area to print job
if (my_pj.orientation == "portrait") {
  // Here, the printArea measurements are appropriate for an 8.5" x 11"
  // portrait page.
  my_pj.addPage(this,{xMin:0,xMax:600,yMin:0,yMax:800}
}
else {
  // my_pj.orientation is "landscape".
  // Now, the printArea measurements are appropriate for an 11" x 8.5"
  // landscape page.
  my_pj.addPage(this,{xMin:0,xMax:750,yMin:0,yMax:600});
}

// send pages from the spooler to the printer
my_pj.send();

// clean up
delete my_pj;

See also

PrintJob.send(), PrintJob.start()


PrintJob.send()

Availability

Flash Player 7.

Usage

my_pj.send()

Parameters

None.

Returns

Nothing.

Description

Method; is used following PrintJob.start() and PrintJob.addPage() to send spooled pages to the printer.

Example

See PrintJob.addPage().

See also

PrintJob.addPage(), PrintJob.start()


PrintJob.start()

Availability

Flash Player 7.

Usage

my_pj.start()

Parameters

None.

Returns

A Boolean value of true if the user clicks OK when the print dialog boxes appear, or false if the user clicks Cancel or if an error occurs.

Description

Method; displays the operating system's print dialog boxes and starts spooling. The print dialog boxes give the user an opportunity to change print settings, and then populate the following read-only properties (notice that 1 point equals 1 onscreen pixel):

Property | Type | Units | Notes
PrintJob.paperHeight | Number | Points | Overall paper height
PrintJob.paperWidth | Number | Points | Overall paper width
PrintJob.pageHeight | Number | Points | Height of actual printable area on the page; any user-set margins are ignored
PrintJob.pageWidth | Number | Points | Width of actual printable area on the page; any user-set margins are ignored
PrintJob.orientation | String | n/a | "portrait" or "landscape"

After the user clicks OK in the print dialog box, the player begins spooling a print job to the operating system. You should issue any ActionScript commands that affect the printout, and then you can begin using PrintJob.addPage() commands to begin sending pages to the spooler. If you wish, use the height, width, and orientation properties this method returns to determine how to format the printout.

Because the user sees information such as "Printing page 1" immediately after clicking OK, you should call the PrintJob.addPage() and PrintJob.send() commands as soon as possible.

If this method returns false (for example, if the user clicks Cancel instead of OK), any subsequent calls to PrintJob.addPage() and PrintJob.send() will fail. However, if you test for this return value and don't send PrintJob.addPage() commands as a result, you should still delete the PrintJob object to make sure the print spooler is cleared, as shown below.

var my_pj = new PrintJob();
var myResult = my_pj.start();
  if(myResult) {
    // addPage() and send() statements here
  }
delete my_pj;

Example

See PrintJob.addPage().

See also

PrintJob.addPage(), PrintJob.send()


printNum()

Availability

Flash Player 5.

Note: If you are authoring for Flash Player 7 or later, you can create a PrintJob object, which gives you (and the user) more control over the printing process. For more information, see the PrintJob class entry.

Usage

printNum (level, "Bounding box")

Parameters

level The level in Flash Player to print. By default, all of the frames in the level print. If you want to print specific frames in the level, assign a #p frame label to those frames.

Bounding box A modifier that sets the print area of the movie. Enclose this parameter in quotation marks, and specify one of the following values:

  • bmovie Designates the bounding box of a specific frame in a movie as the print area for all printable frames in the movie. Assign a #b frame label to the frame whose bounding box you want to use as the print area.
  • bmax Designates a composite of all of the bounding boxes of all the printable frames as the print area. Specify the bmax parameter when the printable frames in your movie vary in size.
  • bframe Indicates that the bounding box of each printable frame should be used as the print area for that frame. This changes the print area for each frame and scales the objects to fit the print area. Use bframe if you have objects of different sizes in each frame and want each object to fill the printed page.

Returns

Nothing.

Description

Function; prints the level in Flash Player according to the boundaries specified in the Bounding box parameter ("bmovie", "bmax", "bframe"). If you want to print specific frames in the target movie, attach a #p frame label to those frames. Although using printNum() results in higher quality prints than using printAsBitmapNum(), you cannot use printNum() to print movies with alpha transparencies or special color effects.

If you use bmovie for the Bounding box parameter but do not assign a #b label to a frame, the print area is determined by the Stage size of the loaded movie. (The loaded movie does not inherit the main movie's Stage size.)

All of the printable elements in a movie must be fully loaded before printing can begin.

The Flash Player printing feature supports PostScript and non-PostScript printers. Non-PostScript printers convert vectors to bitmaps.

See also

print(), printAsBitmap(), printAsBitmapNum(), PrintJob class


private

Availability

Flash Player 6.

Usage

class someClassName{
  private var name;
  private function name() {
    // your statements here
  }
}

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Parameters

name The name of the variable or function that you want to specify as private.

Description

Keyword; specifies that a variable or function is available only to the class that declares or defines it, or to subclasses of that class. By default, a variable or function is available to any class that calls it. Use this keyword if you want to restrict access to a variable or function. For more information, see Controlling member access.

You can use this keyword only in class definitions, not in interface definitions.

See also

public, static


public

Flash Player 6.

Usage

class someClassName{
  public var name;
  public function name() {
    // your statements here
  }
}

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Parameters

name The name of the variable or function that you want to specify as public.

Description

Keyword; specifies that a variable or function is available to any class that calls it. Because variables and functions are public by default, this keyword is used primarily for stylistic reasons. For example, you might want to use it for reasons of consistency in a block of code that also contains private or static variables.

Example

The following two blocks of code are functionally identical.

private var age:Number;
public var name:String;
static var birth:Date;

private var age:Number;
var name:String;
static var birth:Date;

For more information, see Controlling member access.

See also

private, static


_quality

Availability

Flash Player 5.

Usage

_quality

Description

Property (global); sets or retrieves the rendering quality used for a movie. Device fonts are always aliased and therefore are unaffected by the _quality property.

The _quality property can be set to the following values:

  • "LOW" Low rendering quality. Graphics are not anti-aliased, bitmaps are not smoothed.
  • "MEDIUM" Medium rendering quality. Graphics are anti-aliased using a 2 x 2 grid, in pixels, but bitmaps are not smoothed. Suitable for movies that do not contain text.
  • "HIGH" High rendering quality. Graphics are anti-aliased using a 4 x 4 grid, in pixels, and bitmaps are smoothed if the movie is static. This is the default rendering quality setting used by Flash.
  • "BEST" Very high rendering quality. Graphics are anti-aliased using a 4 x 4 grid, in pixels, and bitmaps are always smoothed.

Example

The following example sets the rendering quality to LOW:

_quality = "LOW";

See also

_highquality, toggleHighQuality()


random

Availability

Flash Player 4. This function was deprecated in Flash 5 in favor of Math.random().

Usage

random(value)

Parameters

value An integer.

Returns

An integer.

Description

Function; returns a random integer between 0 and one less than the integer specified in the value parameter.

Example

The following use of random() returns a value of 0, 1, 2, 3, or 4:

random(5);

See also

Math.random()


removeMovieClip()

Availability

Flash Player 4.

Usage

removeMovieClip(target)

Parameters

target The target path of a movie clip instance created with duplicateMovieClip(), or the instance name of a movie clip created with MovieClip.attachMovie() or MovieClip.duplicateMovieClip().

Returns

None.

Description

Function; deletes the specified movie clip.

See also

duplicateMovieClip(), MovieClip.duplicateMovieClip(), MovieClip.attachMovie(), MovieClip.removeMovieClip()


return

Availability

Flash Player 5.

Usage

return[expression]

Parameters

expression A string, number, array, or object to evaluate and return as a value of the function. This parameter is optional.

Returns

The evaluated expression parameter, if provided.

Description

Statement; specifies the value returned by a function. The return action evaluates expression and returns the result as a value of the function in which it executes. The return action causes the function to stop running and replaces the function with the returned value. If the return statement is used alone, it returns null.

You can't return multiple values. If you try to do so, only the last value is returned. In the following example, c is returned:

return a, b, c ;

Example

The following example uses the return action inside the body of the sum() function to return the added value of the three parameters. The next line of code calls sum() and assigns the returned value to the variable newValue.

function sum(a, b, c){
  return a + b + c;
}
newValue = sum(4, 32, 78);
trace(newValue);
// sends 114 to the Output panel

See also

function


_root

Availability

Flash Player 5.

Usage

_root.movieClip
_root.action
_root.property

Parameters

movieClip The instance name of a movie clip.

action An action or method.

property A property of the MovieClip object.

Description

Property; specifies or returns a reference to the root movie Timeline. If a movie has multiple levels, the root movie Timeline is on the level containing the currently executing script. For example, if a script in level 1 evaluates _root, _level1 is returned.

Specifying _root is the same as using the slash notation (/) to specify an absolute path within the current level.

Note: If a movie that contains _root is loaded into another movie, _root refers to the Timeline of the loading movie, not to the Timeline that contains _root. If you want to ensure that _root refers to the Timeline of the loaded movie even if it is loaded into another movie, use MovieClip._lockroot.

Example

The following example stops the Timeline of the level containing the currently executing script:

_root.stop();

The following example sends the Timeline in the current level to Frame 3:

_root.gotoAndStop(3);

See also

MovieClip._lockroot, _parent, targetPath


scroll

Availability

Flash Player 4.

Usage

textFieldVariableName.scroll = x

Description

Property; a deprecated property that controls the display of information in a text field associated with a variable. The scroll property defines where the text field begins displaying content; after you set it, Flash Player updates it as the user scrolls through the text field. The scroll property is useful for directing users to a specific paragraph in a long passage, or creating scrolling text fields. This property can be retrieved and modified.

Example

The following code is attached to an Up button that scrolls the text field myText:

on (release) {
  myText.scroll = myText.scroll + 1;
}

See also

TextField.maxscroll, TextField.scroll


Selection class

Availability

Flash Player 5.

Description

The Selection class lets you set and control the text field in which the insertion point is located; that is, the field that has focus. Selection-span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on).

There is no constructor function for the Selection class, because there can only be one currently focused field at a time.

Method summary for the Selection class

Method | Description
Selection.addListener() | Registers an object to receive notification when onSetFocus is invoked.
Selection.getBeginIndex() | Returns the index at the beginning of the selection span. Returns -1 if there is no index or currently selected field.
Selection.getCaretIndex() | Returns the current caret (insertion point) position in the currently focused selection span. Returns -1 if there is no caret position or currently focused selection span.
Selection.getEndIndex() | Returns the index at the end of the selection span. Returns -1 if there is no index or currently selected field.
Selection.getFocus() | Returns the name of the variable for the currently focused text field. Returns null if there is no currently focused text field.
Selection.removeListener() | Removes an object that was registered with addListener().
Selection.setFocus() | Focuses the text field associated with the specified variable.
Selection.setSelection() | Sets the beginning and ending indexes of the selection span.

Listener summary for the Selection class

Listener | Description
Selection.onSetFocus | Notified when the input focus changes.


Selection.addListener()

Availability

Flash Player 6.

Usage

Selection.addListener(newListener)

Parameters

newListener An object with an onSetFocus method.

Returns

None.

Description

Method; registers an object to receive keyboard focus change notifications. When the focus changes (for example, whenever Selection.setFocus() is invoked), all listening objects registered with addListener() have their onSetFocus method invoked. Multiple objects may listen for focus change notifications. If the listener newListener is already registered, no change occurs.


Selection.getBeginIndex()

Availability

Flash Player 5.

Usage

Selection.getBeginIndex()

Parameters

None.

Returns

An integer.

Description

Method; returns the index at the beginning of the selection span. If no index exists or no text field currently has focus, the method returns -1. Selection span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on).


Selection.getCaretIndex()

Availability

Flash Player 5.

Usage

Selection.getCaretIndex()

Parameters

None.

Returns

An integer.

Description

Method; returns the index of the blinking insertion point (caret) position. If there is no blinking insertion point displayed, the method returns -1. Selection span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on).


Selection.getEndIndex()

Availability

Flash Player 5.

Usage

Selection.getEndIndex()

Parameters

None.

Returns

An integer.

Description

Method; returns the ending index of the currently focused selection span. If no index exists, or if there is no currently focused selection span, the method returns -1. Selection span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on).


Selection.getFocus()

Availability

Flash Player 5. Instance names for buttons and text fields work in Flash Player 6 and later.

Usage

Selection.getFocus()

Parameters

None.

Returns

A string or null.

Description

Method; returns a string specifying the target path of the object that has focus.

  • If a TextField object has focus, and the object has an instance name, this method returns the target path of the TextField object. Otherwise, it returns the Text Field's variable name.
  • If a Button object or button movie clip has focus, this method returns the target path of the Button object or button movie clip.
  • If neither a TextField object, Button object, nor button movie clip has focus, this method returns null.

See also

Selection.onSetFocus, Selection.setFocus()


Selection.onSetFocus

Availability

Flash Player 6.

Usage

someListener.onSetFocus = function( [ oldFocus [, newFocus ] ]){
  // statements;
}

Parameters

oldfocus The object losing focus. This parameter is optional.

newfocus The object receiving focus. This parameter is optional.

Description

Listener; notified when the input focus changes. To use this listener, you must create a listener object. You can then define a function for this listener and use Selection.addListener() to register the listener with the Selection object, as in the following code:

someListener = new Object();
someListener.onSetFocus = function () {
  // statements
}
Selection.addListener(someListener);

Listeners enable different pieces of code to cooperate because multiple listeners can receive notification about a single event.

See also

Selection.addListener(), Selection.setFocus()


Selection.removeListener()

Availability

Flash Player 6.

Usage

Selection.removeListener(listener)

Parameters

listener The object that will no longer receive focus notifications.

Returns

If listener was successfully removed, the method returns a true value. If listener was not successfully removed—for example, if listener was not on the Selection object's listener list—the method returns a value of false.

Description

Method; removes an object previously registered with Selection.addListener().


Selection.setFocus()

Availability

Flash Player 5. Instance names for buttons and movie clips work only in Flash Player 6 and later.

Usage

Selection.setFocus("instanceName")

Parameters

instanceName A string specifying the path to the instance name of a button, movie clip, or text field.

Returns

An event.

Description

Method; gives focus to the selectable (editable) text field, button, or movie clip specified by instanceName. The instanceName parameter must be a string literal of the path to the instance. You can use dot or slash notation to specify the path. You can also use a relative or absolute path. If you are using ActionScript 2.0, you must use dot notation.

If null is passed, the current focus is removed.

Example

The following example gives focus to a text field associated with myVar, on the main Timeline. Because the instanceName parameter is an absolute path, you can call the action from any Timeline.

Selection.setFocus("_root.myVar");

In the following example, the text field associated with myVar is in a movie clip called myClip on the main Timeline. You can use either of the following two paths to set focus; the first is relative and the second is absolute.

Selection.setFocus("myClip.myVar");
Selection.setFocus("_root.myClip.myVar");

See also

Selection.getFocus(), Selection.onSetFocus


Selection.setSelection()

Availability

Flash Player 5.

Usage

Selection.setSelection(start, end)

Parameters

start The beginning index of the selection span.

end The ending index of the selection span.

Returns

Nothing.

Description

Method; sets the selection span of the currently focused text field. The new selection span will begin at the index specified in the start parameter, and end at the index specified in the end parameter. Selection span indexes are zero-based (for example, the first position is 0, the second position is 1, and so on). This method has no effect if there is no currently focused text field.


set

Availability

Flash Player 6.

Usage

function set property(varName) {
  // your statements here
}

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Parameters

property Word you want to use to refer to the property that set will access; this value must be the same as the value used in the corresponding get command.

varName The local variable that sets the value you're assigning.

Returns

Nothing.

Description

Keyword; permits implicit "setting" of properties associated with objects based on classes you have defined in external class files. Using implicit set methods lets you access properties of objects without accessing them directly. Implicit get/set methods are syntactic shorthand for the Object.addProperty() method in ActionScript 1.

For more information, see Implicit get/set methods.

See also

get, Object.addProperty()


set variable

Availability

Flash Player 4.

Usage

set(variable, expression)

Parameters

variable An identifier to hold the value of the expression parameter.

expression A value assigned to the variable.

Returns

Nothing.

Description

Statement; assigns a value to a variable. A variable is a container that holds data. The container itself is always the same, but the contents can change. By changing the value of a variable as the SWF file plays, you can record and save information about what the user has done, record values that change as the SWF file plays, or evaluate whether a condition is true or false.

Variables can hold any data type (for example, String, Number, Boolean, Object, or MovieClip). The Timeline of each SWF file and movie clip has its own set of variables, and each variable has its own value independent of variables on other Timelines.

Strict data typing is not supported inside a set statement. If you use this statement to set a variable to a value whose data type is different from the data type associated with the variable in a class file, no compiler error is thrown.

Example

This example sets a variable called orig_x_pos, which stores the original x axis position of the ship movie clip in order to reset the ship to its starting location later in the SWF file.

on(release) {
  set("orig_x_pos", getProperty ("ship", _x ));
}

The previous code gives the same result as the following code:

on(release) {
  orig_x_pos = ship._x;
}

See also

var, call()


setInterval()

Availability

Flash Player 6.

Usage

setInterval(functionName, interval [, param1, param2, ..., paramN])

Parameters

functionName A function name or a reference to an anonymous function.

interval The time in milliseconds between calls to the functionName parameter.

param1, param2, ..., paramN Optional parameters passed to the function or methodName parameter.

Returns

An interval identifier that you can pass to clearInterval() to cancel the interval.

Description

Function; calls a function or a method or an object at periodic intervals while a SWF file plays. You can use an interval function to update variables from a database or update a time display.

If interval is less than the SWF file's frame rate (for example, 10 frames per second [fps] is equal to 100 milliseconds), the interval function is called as close to interval as possible. You must use the updateAfterEvent() function to make sure that the screen refreshes often enough. If interval is greater than the SWF file's frame rate, the interval function is only called each time the playhead enters a frame; this minimizes the impact each time the screen is refreshed.

Example

Usage 1:The following example calls an anonymous function every 1000 milliseconds (every 1 second).

setInterval( function(){ trace("interval called"); }, 1000 );

Usage 2: The following example defines two event handlers and calls each of them. Both calls to setInterval() send the string "interval called" to the Output panel every 1000 milliseconds. The first call to setInterval() calls the callback1() function, which contains a trace() action. The second call to setInterval() passes the "interval called" string to the function callback2() as a parameter.

function callback1() {
  trace("interval called");
}

function callback2(arg) {
  trace(arg);
}

setInterval( callback1, 1000 );
setInterval( callback2, 1000, "interval called" );

Usage 3: This example uses a method of an object. You must use this syntax when you want to call a method that is defined for an object.

obj = new Object();
obj.interval = function() {
  trace("interval function called");
}

setInterval( obj, "interval", 1000 );

obj2 = new Object();
obj2.interval = function(s) {
  trace(s);
}
setInterval( obj2, "interval", 1000, "interval function called" );

You must use the second form of the setInterval() syntax to call a method of an object, as follows:

setInterval( obj2, "interval", 1000, "interval function called" );

See also

clearInterval(), updateAfterEvent()


setProperty()

Availability

Flash Player 4.

Usage

setProperty(target, property, value/expression)

Parameters

target The path to the instance name of the movie clip whose property is to be set.

property The property to be set.

value The new literal value of the property.

expression An equation that evaluates to the new value of the property.

Returns

Nothing.

Description

Function; changes a property value of a movie clip as the movie plays.

Example

This statement sets the _alpha property of a movie clip named star to 30% when the button is clicked:

on(release) {
  setProperty("star", _alpha, "30");
}

See also

getProperty


SharedObject class

Availability

Flash Player 6.

Description

Shared objects are quite powerful: they offer real-time data sharing between objects that are persistent on the user's computer. You can think of local shared objects as "cookies."

You can use local shared objects to maintain local persistence. This is the simplest way to use a shared object. For example, you can call SharedObject.getLocal() to create a shared object, such as a calculator with memory, in the player. Because the shared object is locally persistent, Flash saves its data attributes on the user's machine when the SWF file ends. The next time the SWF file runs, the calculator contains the values it had when the SWF file ended. Alternatively, if you set the shared object's properties to null before the SWF ends, the calculator opens without any prior values the next time the SWF file runs.

To create a local shared object, use the following syntax:

// Create a local shared object
so = SharedObject.getLocal("foo");

Local disk space considerations

Local shared objects are always persistent on the client, up to available memory and disk space.

By default, Flash can save locally persistent remote shared objects up to 100K in size. When you try to save a larger object, Flash Player displays the Local Storage dialog box, which lets the user allow or deny local storage for the domain that is requesting access. Make sure your Stage size is at least 215 x 138 pixels; this is the minimum size Flash requires to display the dialog box.

If the user clicks Allow, the object is saved and SharedObject.onStatus is invoked with a code property of SharedObject.Flush.Success; if the user clicks Deny, the object is not saved and SharedObject.onStatus is invoked with a code property of SharedObject.Flush.Failed.

The user can also specify permanent local storage settings for a particular domain by right-clicking (Windows) or Control-clicking (Macintosh) while a SWF file is playing, choosing Settings, and then opening the Local Storage panel.

You can't use ActionScript to specify local storage settings for a user, but you can display the Local Storage panel for the user by using System.showSettings(1).

The following list summarizes how the user's disk space choices interact with shared objects:

  • If the user selects Never, objects are never saved locally, and all SharedObject.flush() commands issued for the object return false.
  • If the user selects Unlimited (moves the slider all the way to the right), objects are saved locally up to available disk space.
  • If the user selects None (moves the slider all the way to the left), all SharedObject.flush() commands issued for the object return "pending" and cause the player to ask the user if additional disk space can be allotted to make room for the object, as explained above.
  • If the user selects 10 KB, 100 KB, 1 MB, or 10 MB, objects are saved locally and SharedObject.flush() returns true if the object fits within the specified amount of space. If more space is needed, SharedObject.flush() returns "pending", and the player asks the user if additional disk space can be allotted to make room for the object, as explained above.

Additionally, if the user selects a value that is less than the amount of disk space currently being used for locally persistent data, the player warns the user that any locally saved shared objects will be deleted.

Note: There is no size limit in Flash Player that runs from the authoring environment.

Method summary for the SharedObject class

Method | Description
SharedObject.clear() | Purges all of the data from the shared object and deletes the shared object from the disk.
SharedObject.flush() | Immediately writes a locally persistent shared object to a local file.
SharedObject.getLocal() | Returns a reference to a locally persistent shared object that is available only to the current client.
SharedObject.getSize() | Gets the current size of the shared object, in bytes.

Property summary for the SharedObject class

Property (read-only) | Description
SharedObject.data | The collection of attributes assigned to the data property of the object; these attributes can be shared and/or stored.

Event handler summary for the SharedObject class

Event handler | Description
SharedObject.onStatus | Invoked every time an error, warning, or informational note is posted for a shared object.

Constructor for the SharedObject class

For information on creating local shared objects, see SharedObject.getLocal().


SharedObject.clear()

Availability

Flash Player 7.

Usage

my_so.clear()

Parameters

None.

Returns

Nothing.

Description

Method; purges all of the data from the shared object and deletes the shared object from the disk. The reference to my_so is still active, and my_so is now empty.


SharedObject.data

Availability

Flash Player 6.

Usage

myLocalSharedObject.data

Description

Read-only property; the collection of attributes assigned to the data property of the object; these attributes can be shared and/or stored. Each attribute can be an object of any of the basic ActionScript or JavaScript types—Array, Number, Boolean, and so on. For example, the following lines assign values to various aspects of a shared object:

itemsArray = new Array(101,346,483);
currentUserIsAdmin = true;
currentUserName = "Ramona";
so.data.itemNumbers = itemsArray;
so.data.adminPrivileges = currentUserIsAdmin;
so.data.userName = currentUserName;

All attributes of a shared object's data property are saved if the object is persistent.

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

To delete attributes for local shared objects, use code like delete so.data.attributeName; setting an attribute to null or undefined for a local shared object does not delete the attribute.

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

so.favoriteColor = "blue";
so.favoriteNightClub = "The Bluenote Tavern";
so.favoriteSong = "My World is Blue";

Example

The following example sets the current stream to the user's selection.

curStream = _root.so.data.msgList[selected].streamName;

See also

Sound class


SharedObject.flush()

Availability

Flash Player 6.

Usage

myLocalSharedObject.flush([minimumDiskSpace])

Parameters

minimumDiskSpace An optional integer specifying the number of bytes that must be allotted for this object. The default value is 0.

Returns

A Boolean value of true or false, or a string value of "pending".

  • If the user has permitted local information storage for objects from this domain, and the amount of space allotted is sufficient to store the object, this method returns true. (If you have passed a value for minimumDiskSpace, the amount of space allotted must be at least equal to that value for true to be returned).
  • If the user has permitted local information storage for objects from this domain, but the amount of space allotted is not sufficient to store the object, this method returns "pending".
  • If the user has permanently denied local information storage for objects from this domain, or if Flash is unable to save the object for any reason, this method returns false.

Description

Method; immediately writes a locally persistent shared object to a local file. If you don't use this method, Flash writes the shared object to a file when the shared object session ends—that is, when the SWF file is closed, when the shared object is garbage-collected because it no longer has any references to it, or when you call SharedObject.clear().

If this method returns "pending", the Flash Player displays a dialog box asking the user to increase the amount of disk space available to objects from this domain. To allow space for the shared object to "grow" when it is saved in the future, thus avoiding return values of "pending", pass a value for minimumDiskSpace. When Flash tries to write the file, it looks for the number of bytes passed to minimumDiskSpace, instead of looking for just enough space to save the shared object at its current size.

For example, if you expect a shared object to grow to a maximum size of 500 bytes, even though it may start out much smaller, pass 500 for minimumDiskSpace. If Flash asks the user to allot disk space for the shared object, it will ask for 500 bytes. After the user allots the requested amount of space, Flash won't have to ask for more space on future attempts to flush the object (as long as its size doesn't exceed 500 bytes).

After the user responds to the dialog box, this method is called again and returns either true or false; also, SharedObject.onStatus is invoked with a code property of SharedObject.Flush.Success or SharedObject.Flush.Failed.

For more information, see Local disk space considerations.

Example

The following function gets a shared object, SO, and fills writable properties with user-provided settings. Finally, flush() is called to save the settings and allot a minimum of 1000 bytes of disk space.

this.SyncSettingsCore=function(soname, override, settings)
{
  var SO=SharedObject.getLocal(soname, "http://www.mydomain.com/app/sys");

  // settings list index
  var i;

  // For each specified value in settings:
  // If override is true, set the persistent setting to the provided value.
  // If override is false, fetch the persistent setting, unless there
  // isn't one, in which case, set it to the provided value.
  for (i in settings) {
    if (override || (SO.data[i] == null)) {
      SO.data[i]= settings[i];
    } else {
      settings[i]= SO.data[i];
    }
  }
  SO.flush(1000);
}


SharedObject.getLocal()

Availability

Flash Player 6.

Usage

SharedObject.getLocal(objectName [, localPath])

Note: The correct syntax is SharedObject.getLocal. To assign the object to a variable, use syntax like myLocalSO = SharedObject.getLocal.

Parameters

objectName The name of the object. The name can include forward slashes (/); for example, work/addresses is a legal name. Spaces are not allowed in a shared object name, nor are the following characters:

~ % & \ ; :  " ' , < > ? #

localPath An optional string parameter that specifies the full or partial path to the SWF file that created the shared object, and that determines where the shared object will be stored locally. The default value is the full path.

Returns

A reference to a shared object that is persistent locally and is available only to the current client. If Flash can't create or find the shared object (for example, if localPath was specified but no such directory exists), this method returns null.

Description

Method; returns a reference to a locally persistent shared object that is available only to the current client.

Note: If the user has chosen to never allow local storage for this domain, the object is not saved locally, even if a value for localPath is specified. For more information, see Local disk space considerations.

To avoid name collisions, Flash looks at the location of the SWF file that is creating the shared object. For example, if a SWF file at www.myCompany.com/apps/stockwatcher.swf creates a shared object named portfolio, that shared object will not conflict with another object named portfolio that was created by a SWF file at www.yourCompany.com/photoshoot.swf, because the SWF files originate from two different directories.

Example

The following example saves the last frame a user entered to a local shared object kookie.

// Get the kookie
so = sharedobject.getlocal("kookie");

// Get the user of the kookie and go to the frame number saved for this user.
if (so.data.user != undefined) {
  this.user = so.data.user;
  this.gotoAndStop(so.data.frame);
}

The following code block is placed on each SWF frame.

// On each frame, call the rememberme function to save the frame number.
function rememberme() {
  so.data.frame=this._currentFrame;
  so.data.user="John";
}


SharedObject.getSize()

Availability

Flash Player 6.

Usage

myLocalSharedObject.getSize()

Parameters

None.

Returns

A numeric value specifying the size of the shared object, in bytes.

Description

Method; gets the current size of the shared object, in bytes.

Flash calculates the size of a shared object by stepping through each of its data properties; the more data properties the object has, the longer it takes to estimate its size. For this reason, estimating object size can have significant processing cost. Therefore, you may want to avoid using this method unless you have a specific need for it.

Example

The following example gets the size of the shared object so.

var soSize= this.so.getSize();


SharedObject.onStatus

Availability

Flash Player 6.

Usage

myLocalSharedObject.onStatus = function(infoObject) {
  // your statements here
}

Parameters

infoObject A parameter defined according to the status message.

Returns

Nothing.

Description

Event handler; invoked every time an error, warning, or informational note is posted for a shared object. If you want to respond to this event handler, you must create a function to process the information object generated by the shared object.

The information object has a code property containing a string that describes the result of the onStatus handler, and a level property containing a string that is either "Status" or "Error".

In addition to this onStatus handler, Flash also provides a "super" function called System.onStatus. If onStatus is invoked for a particular object and there is no function assigned to respond to it, Flash processes a function assigned to System.onStatus if it exists.

The following events notify you when certain SharedObject activities occur.

Code property | Level property | Meaning
SharedObject.Flush.Failed | Error | A SharedObject.flush() command that returned "pending" has failed (the user did not allot additional disk space for the shared object when Flash Player displayed the Local Storage Settings dialog box).
SharedObject.Flush.Success | Status | A SharedObject.flush() command that returned "pending" has been successfully completed (the user allotted additional disk space for the shared object).

See also

SharedObject.getLocal(), System.onStatus


Sound class

Availability

Flash Player 5.

Description

The Sound class lets you control sound in a movie. You can add sounds to a movie clip from the library while the movie is playing and control those sounds. If you do not specify a target when you create a new Sound object, you can use the methods to control sound for the whole movie.

You must use the constructor new Sound to create a Sound object before calling the methods of the Sound class.

Method summary for the Sound class

Method | Description
Sound.attachSound() | Attaches the sound specified in the parameter.
Sound.getBytesLoaded() | Returns the number of bytes loaded for the specified sound.
Sound.getBytesTotal() | Returns the size of the sound in bytes.
Sound.getPan() | Returns the value of the previous setPan() call.
Sound.getTransform() | Returns the value of the previous setTransform() call.
Sound.getVolume() | Returns the value of the previous setVolume() call.
Sound.loadSound() | Loads an MP3 file into Flash Player.
Sound.setPan() | Sets the left/right balance of the sound.
Sound.setTransform() | Sets the amount of each channel, left and right, to be played in each speaker.
Sound.setVolume() | Sets the volume level for a sound.
Sound.start() | Starts playing a sound from the beginning or, optionally, from an offset point set in the parameter.
Sound.stop() | Stops the specified sound or all sounds currently playing.

Property summary for the Sound class

Property | Description
Sound.duration | Length of a sound, in milliseconds.
Sound.id3 | Provides access to the metadata that is part of an MP3 file.
Sound.position | Number of milliseconds a sound has been playing.

Event handler summary for the Sound class

Event handler | Description
Sound.onID3 | Invoked each time new ID3 data is available.
Sound.onLoad | Invoked when a sound loads.
Sound.onSoundComplete | Invoked when a sound stops playing.

Constructor for the Sound class

Availability

Flash Player 5.

Usage

new Sound([target])

Parameters

target The movie clip instance on which the Sound object operates. This parameter is optional.

Returns

A reference to a Sound object.

Description

Constructor; creates a new Sound object for a specified movie clip. If you do not specify a target instance, the Sound object controls all of the sounds in the movie.

Example

The following example creates a new Sound object called global_sound. The second line calls setVolume() and adjusts the volume on all sounds in the movie to 50%.

global_sound = new Sound();
global_sound.setVolume(50);

The following example creates a new Sound object, passes it the target movie clip my_mc, and calls the start method, which starts any sound in my_mc.

movie_sound = new Sound(my_mc);
movie_sound.start();


Sound.attachSound()

Availability

Flash Player 5.

Usage

my_sound.attachSound("idName")

Parameters

idName The identifier of an exported sound in the library. The identifier is located in the Linkage Properties dialog box.

Returns

Nothing.

Description

Method; attaches the sound specified in the idName parameter to the specified Sound object. The sound must be in the library of the current SWF file and specified for export in the Linkage Properties dialog box. You must call Sound.start() to start playing the sound.

To make sure that the sound can be controlled from any scene in the SWF file, place the sound on the main Timeline of the SWF file.


Sound.duration

Availability

Flash Player 6.

Usage

my_sound.duration

Description

Property (read-only); the duration of a sound, in milliseconds.


Sound.getBytesLoaded()

Availability

Flash Player 6.

Usage

my_sound.getBytesLoaded()

Parameters

None.

Returns

An integer indicating the number of bytes loaded.

Description

Method; returns the number of bytes loaded (streamed) for the specified Sound object. You can compare the value of getBytesLoaded() with the value of getBytesTotal() to determine what percentage of a sound has loaded.

See also

Sound.getBytesTotal()


Sound.getBytesTotal()

Availability

Flash Player 6.

Usage

my_sound.getBytesTotal()

Parameters

None.

Returns

An integer indicating the total size, in bytes, of the specified Sound object.

Description

Method; returns the size, in bytes, of the specified Sound object.

See also

Sound.getBytesLoaded()


Sound.getPan()

Availability

Flash Player 5.

Usage

my_sound.getPan();

Parameters

None.

Returns

An integer.

Description

Method; returns the pan level set in the last setPan() call as an integer from -100 (left) to 100 (right). (0 sets the left and right channels equally.) The pan setting controls the left-right balance of the current and future sounds in a SWF file.

This method is cumulative with setVolume() or setTransform().

See also

Sound.setPan()


Sound.getTransform()

Availability

Flash Player 5.

Usage

my_sound.getTransform();

Parameters

None.

Returns

An object with properties that contain the channel percentage values for the specified sound object.

Description

Method; returns the sound transform information for the specified Sound object set with the last Sound.setTransform() call.


Sound.getVolume()

Availability

Flash Player 5.

Usage

my_sound.getVolume()

Parameters

None.

Returns

An integer.

Description

Method; returns the sound volume level as an integer from 0 to 100, where 0 is off and 100 is full volume. The default setting is 100.

See also

Sound.setVolume()


Sound.id3

Availability

Flash Player 6; behavior updated in Flash Player 7.

Usage

my_sound.id3

Description

Property (read-only); provides access to the metadata that is part of an MP3 file.

MP3 sound files can contain ID3 tags, which provide metadata about the file. If an MP3 sound that you load using Sound.attachSound() or Sound.loadSound() contains ID3 tags, you can query these properties. Only ID3 tags that use the UTF-8 character set are supported.

Flash Player 6 r40 and later use the Sound.id3 property to support ID3 1.0 and ID3 1.1 tags. Flash Player 7 adds support for ID3 2.0 tags, specifically 2.3 and 2.4.

The following table lists the standard ID3 2.0 tags and the type of content the tags represent; you query them in the format my_sound.id3.COMM, my_sound.id3.TIME, and so on. MP3 files can contain tags other than those in this table; Sound.id3 provides access to those tags as well.

Property | Description
COMM | Comment
TALB | Album/movie/show title
TBPM | Beats per minute
TCOM | Composer
TCON | Content type
TCOP | Copyright message
TDAT | Date
TDLY | Playlist delay
TENC | Encoded by
TEXT | Lyricist/text writer
TFLT | File type
TIME | Time
TIT1 | Content group description
TIT2 | Title/song name/content description
TIT3 | Subtitle/description refinement
TKEY | Initial key
TLAN | Languages
TLEN | Length
TMED | Media type
TOAL | Original album/movie/show title
TOFN | Original filename
TOLY | Original lyricists/text writers
TOPE | Original artists/performers
TORY | Original release year
TOWN | File owner/licensee
TPE1 | Lead performers/soloists
TPE2 | Band/orchestra/accompaniment
TPE3 | Conductor/performer refinement
TPE4 | Interpreted, remixed, or otherwise modified by
TPOS | Part of a set
TPUB | Publisher
TRCK | Track number/position in set
TRDA | Recording dates
TRSN | Internet radio station name
TRSO | Internet radio station owner
TSIZ | Size
TSRC | ISRC (international standard recording code)
TSSE | Software/hardware and settings used for encoding
TYER | Year
WXXX | URL link frame

Flash Player 6 supported several ID31.0 tags. If these tags are in not in the MP3 file, but corresponding ID3 2.0 tags are, the ID3 2.0 tags are copied into the ID3 1.0 properties, as shown in the following table. This process provides backward compatibility with scripts that you may have written already that read ID3 1.0 properties.

ID3 2.0 tag | Corresponding ID3 1.0 property
COMM | Sound.id3.comment
TALB | Sound.id3.album
TCON | Sound.id3.genre
TIT2 | Sound.id3.songname
TPE1 | Sound.id3.artist
TRCK | Sound.id3.track
TYER | Sound.id3.year

Example

See Sound.onID3 for an example of the use of this property.

See also

Sound.attachSound(), Sound.loadSound()


Sound.loadSound()

Availability

Flash Player 6.

Usage

my_sound.loadSound("url", isStreaming)

Parameters

url The location on a server of an MP3 sound file.

isStreaming A Boolean value that indicates whether the sound is a streaming sound (true) or an event sound (false).

Returns

Nothing.

Description

Method; loads an MP3 file into a Sound object. You can use the isStreaming parameter to indicate whether the sound is an event or a streaming sound.

Event sounds are completely loaded before they play. They are managed by the ActionScript Sound class and respond to all methods and properties of this class.

Streaming sounds play while they are downloading. Playback begins when sufficient data has been received to start the decompressor.

All MP3s (event or streaming) loaded with this method are saved in the browser's file cache on the user's system.

Example

The following example loads an event sound:

my_sound.loadSound( "http://serverpath:port/mp3filename", false);

The following example loads a streaming sound:

my_sound.loadSound( "http://serverpath:port/mp3filename", true);

See also

Sound.onLoad


Sound.onID3

Availability

Flash Player 7.

Usage

my_sound.onID3 = function(){
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked each time new ID3 data is available for an MP3 file that you load using Sound.attachSound() or Sound.loadSound(). This handler provides access to ID3 data without polling. If both ID3 1.0 and ID3 2.0 tags are present in a file, this handler is called twice.

Example

The following example traces the ID3 properties of song.mp3 to the Output panel.

my_sound = new Sound();
my_sound.onID3 = function(){
  for( var prop in my_sound.id3 ){
    trace( prop + " : "+ my_sound.id3[prop] );
  }
}
my_sound.loadSound("song.mp3", false);

See also

Sound.attachSound(), Sound.id3, Sound.loadSound()


Sound.onLoad

Availability

Flash Player 6.

Usage

my_sound.onLoad = function(success){
  // your statements here
}

Parameters

success A Boolean value of true if my_sound has been loaded successfully, false otherwise.

Returns

Nothing.

Description

Event handler; invoked automatically when a sound loads. You must create a function that executes when the this handler is invoked. You can use either an anonymous function or a named function (for an example of each, see Sound.onSoundComplete). You should define this handler before you call my_sound.loadSound().

See also

Sound.loadSound()


Sound.onSoundComplete

Availability

Flash Player 6.

Usage

my_sound.onSoundComplete = function(){
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked automatically when a sound finishes playing. You can use this handler to trigger events in a SWF file when a sound finishes playing.

You must create a function that executes when this handler is invoked. You can use either an anonymous function or a named function.

Example

Usage 1: The following example uses an anonymous function:

my_sound = new Sound();
my_sound.attachSound("mySoundID");
my_sound.onSoundComplete = function() {
  trace("mySoundID completed");
}
my_sound.start();

Usage 2: The following example uses a named function:

function callback1() {
  trace("mySoundID completed");
}

my_sound = new Sound();
my_sound.attachSound("mySoundID");
my_sound.onSoundComplete = callback1;
my_sound.start();

See also

Sound.onLoad


Sound.position

Availability

Flash Player 6.

Usage

my_sound.position

Description

Property (read-only); the number of milliseconds a sound has been playing. If the sound is looped, the position will be reset to 0 at the beginning of each loop.


Sound.setPan()

Availability

Flash Player 5.

Usage

my_sound.setPan(pan);

Parameters

pan An integer specifying the left-right balance for a sound. The range of valid values is -100 to 100, where -100 uses only the left channel, 100 uses only the right channel, and 0 balances the sound evenly between the two channels.

Returns

An integer.

Description

Method; determines how the sound is played in the left and right channels (speakers). For mono sounds, pan determines which speaker (left or right) the sound plays through.

Example

The following example creates a Sound object called my_sound and attaches a sound with the identifier L7 from the library. It also calls setVolume() and setPan() to control the L7 sound.

onClipEvent(mouseDown) {
// create a sound object
  my_sound = new Sound(this);
// attach a sound from the library
  my_sound.attachSound("L7");
//set volume to 50%
  my_sound.setVolume(50);
//turn off the sound in the right channel
  my_sound.setPan(-100);
//start 30 seconds into the sound and play it 5 times
  my_sound.start(30, 5);

See also

Sound.attachSound(), Sound.setPan(), Sound.setTransform(), Sound.setVolume(), Sound.start()


Sound.setTransform()

Availability

Flash Player 5.

Usage

my_sound.setTransform(soundTransformObject)

Parameters

soundTransformObject An object created with the constructor for the generic Object class.

Returns

Nothing.

Description

Method; sets the sound transform (or balance) information, for a Sound object.

The soundTransformObject parameter is an object that you create using the constructor method of the generic Object class with parameters specifying how the sound is distributed to the left and right channels (speakers).

Sounds use a considerable amount of disk space and memory. Because stereo sounds use twice as much data as mono sounds, it is generally best to use 22-KHz 6-bit mono sounds. You can use setTransform() to play mono sounds as stereo, play stereo sounds as mono, and to add interesting effects to sounds.

The properties for the soundTransformObject are as follows:

11 A percentage value specifying how much of the left input to play in the left speaker (0-100).

1r A percentage value specifying how much of the right input to play in the left speaker (0-100).

rr A percentage value specifying how much of the right input to play in the right speaker (0-100).

rl A percentage value specifying how much of the left input to play in the right speaker (0-100).

The net result of the parameters is represented by the following formula:

leftOutput = left_input * ll + right_input * lr
rightOutput = right_input * rr + left_input * rl

The values for left_input or right_input are determined by the type (stereo or mono) of sound in your SWF file.

Stereo sounds divide the sound input evenly between the left and right speakers and have the following transform settings by default:

ll = 100
lr = 0
rr = 100
rl = 0

Mono sounds play all sound input in the left speaker and have the following transform settings by default:

ll = 100
lr = 100
rr = 0
rl = 0

Example

The following example illustrates a setting that can be achieved by using setTransform(), but cannot be achieved by using setVolume() or setPan(), even if they are combined.

The following code creates a new soundTransformObject object and sets its properties so that sound from both channels will play only in the left channel.

mySoundTransformObject = new Object;
mySoundTransformObject.ll = 100;
mySoundTransformObject.lr = 100;
mySoundTransformObject.rr = 0;
mySoundTransformObject.rl = 0;

To apply the soundTransformObject object to a Sound object, you then need to pass the object to the Sound object using setTransform() as follows:

my_sound.setTransform(mySoundTransformObject);

The following example plays a stereo sound as mono; the soundTransformObjectMono object has the following parameters:

mySoundTransformObjectMono = new Object;
mySoundTransformObjectMono.ll = 50;
mySoundTransformObjectMono.lr = 50;
mySoundTransformObjectMono.rr = 50;
mySoundTransformObjectMono.rl = 50;
my_sound.setTransform(soundTransformObjectMono);

This example plays the left channel at half capacity and adds the rest of the left channel to the right channel; the soundTransformObjectHalf object has the following parameters:

mySoundTransformObjectHalf = new Object;
mySoundTransformObjectHalf.ll = 50;
mySoundTransformObjectHalf.lr = 0;
mySoundTransformObjectHalf.rr = 100;
mySoundTransformObjectHalf.rl = 50;
my_sound.setTransform(soundTransformObjectHalf);

See also

Object class


Sound.setVolume()

Availability

Flash Player 5.

Usage

my_sound.setVolume(volume)

Parameters

volume A number from 0 to 100 representing a volume level. 100 is full volume and 0 is no volume. The default setting is 100.

Returns

Nothing.

Description

Method; sets the volume for the Sound object.

Example

The following example sets volume to 50% and transfers the sound over time from the left speaker to the right speaker:

onClipEvent (load) {
  i = -100;
  my_sound = new Sound();
  my_sound.setVolume(50);
}
onClipEvent (enterFrame) {
  if (i <= 100) {
    my_sound.setPan(i++);
  }
}

See also

Sound.setPan(), Sound.setTransform()


Sound.start()

Availability

Flash Player 5.

Usage

my_sound.start([secondOffset, loop])

Parameters

secondOffset An optional parameter that lets you start playing the sound at a specific point. For example, if you have a 30-second sound and want the sound to start playing in the middle, specify 15 for the secondOffset parameter. The sound is not delayed 15 seconds, but rather starts playing at the 15-second mark.

loop An optional parameter allowing you to specify the number of times the sound should play consecutively.

Returns

Nothing.

Description

Method; starts playing the last attached sound from the beginning if no parameter is specified, or starting at the point in the sound specified by the secondOffset parameter.

See also

Sound.stop()


Sound.stop()

Availability

Flash Player 5.

Usage

my_sound.stop(["idName"])

Parameters

idName An optional parameter specifying a specific sound to stop playing. The idName parameter must be enclosed in quotation marks (" ").

Returns

Nothing.

Description

Method; stops all sounds currently playing if no parameter is specified, or just the sound specified in the idName parameter.

See also

Sound.start()


_soundbuftime

Availability

Flash Player 4.

Usage

_soundbuftime = integer

Parameters

integer The number of seconds before the SWF file starts to stream.

Description

Property (global); establishes the number of seconds of streaming sound to prebuffer. The default value is 5 seconds.


Stage class

Availability

Flash Player 6.

Description

The Stage class is a top-level class whose methods, properties, and handlers you can access without using a constructor.

Use the methods and properties of this class to access and manipulate information about the boundaries of a SWF file.

Method summary for the Stage class

Method | Description
Stage.addListener() | Adds a listener object that detects when a SWF file is resized.
Stage.removeListener() | Removes a listener object from the Stage object.

Property summary for the Stage class

Property | Description
Stage.align | Alignment of the SWF file in the player or browser.
Stage.height | Height of the Stage, in pixels.
Stage.scaleMode | The current scaling of the SWF file.
Stage.showMenu | Shows or hides the default items in the Flash Player context menu.
Stage.width | Width of the Stage, in pixels.

Event handler summary for the Stage class

Event handler | Description
Stage.onResize | Invoked when Stage.scaleMode is set to "noScale" and the SWF file is resized.


Stage.addListener()

Availability

Flash Player 6.

Usage

Stage.addListener(myListener)

Parameters

myListener An object that listens for a callback notification from the Stage.onResize event.

Returns

Nothing.

Description

Method; detects when a SWF file is resized (but only if Stage.scaleMode = "noScale"). The addListener() method doesn't work with the default movie scaling setting ("showAll") or other scaling settings ("exactFit" and "noBorder").

To use addListener(), you must first create a listener object. Stage listener objects receive notification from Stage.onResize.

Example

This example creates a new listener object called myListener. It then uses myListener to call onResize and define a function that will be called when onResize is triggered. Finally, the code adds the myListener object to the callback list of the Stage object. Listener objects allow multiple objects to listen for resize notifications.

myListener = new Object();
myListener.onResize = function () { ... }
Stage.scaleMode = "noScale"
Stage.addListener(myListener);

See also

Stage.onResize, Stage.removeListener()


Stage.align

Availability

Flash Player 6.

Usage

Stage.align

Description

Property; indicates the current alignment of the SWF file in the player or browser.

The following table lists the values for the align property. Any value not listed here centers the SWF file in the player or browser area.

Value | Vertical | Horizontal
"T" | top | center
"B" | bottom | center
"L" | center | left
"R" | center | right
"TL" | top | left
"TR" | top | right
"BL" | bottom | left
"BR" | bottom | right


Stage.height

Availability

Flash Player 6.

Usage

Stage.height

Description

Property (read-only); indicates the current height, in pixels, of the Stage. When the value of Stage.scaleMode is "noScale", the height property represents the height of the player. When the value of Stage.scaleMode is not "noScale", height represents the height of the SWF file.

See also

Stage.align, Stage.scaleMode, Stage.width


Stage.onResize

Availability

Flash Player 6.

Usage

myListener.onResize = function(){
  // your statements here
}

Parameters

None.

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when Stage.scaleMode is set to "noScale" and the SWF file is resized. You can use this event handler to write a function that lays out the objects on the Stage when a SWF file is resized.

Example

The following example displays a message in the Output panel when the Stage is resized.

Stage.scaleMode = "noScale"
myListener = new Object();
myListener.onResize = function () {
  trace("Stage size is now " + Stage.width + " by " + Stage.height);
}
Stage.addListener(myListener);
// later, call Stage.removeListener(myListener)

See also

Stage.addListener(), Stage.removeListener()


Stage.removeListener()

Availability

Flash Player 6.

Usage

Stage.removeListener(myListener)

Parameters

myListener An object added to an object's callback list with addListener().

Returns

A Boolean value.

Description

Method; removes a listener object created with addListener().

See also

Stage.addListener()


Stage.scaleMode

Availability

Flash Player 6.

Usage

Stage.scaleMode = "value"

Description

Property; indicates the current scaling of the SWF file within the Stage. The scaleMode property forces the SWF file into a specific scaling mode. By default, the SWF file uses the HTML parameters set in the Publish Settings dialog box.

The scaleMode property can use the values "exactFit", "showAll", "noBorder", and "noScale". Any other value sets the scaleMode property to the default "showAll".


Stage.showMenu

Availability

Flash Player 6.

Usage

Stage.showMenu

Description

Property; specifies whether to show or hide the default items in the Flash Player context menu. If showMenu is set to true (the default), all context menu items appear. If showMenu is set to false, only the Settings item appears.

See also

ContextMenu class, ContextMenuItem class


Stage.width

Availability

Flash Player 6.

Usage

Stage.width

Description

Property (read-only); indicates the current width, in pixels, of the Stage. When the value of Stage.scaleMode is "noScale", the width property represents the width of the player. When the value of Stage.scaleMode is not "noScale", width represents the width of the SWF file.

See also

Stage.align, Stage.height, Stage.scaleMode


startDrag()

Availability

Flash Player 4.

Usage

startDrag(target,[lock, left, top, right, bottom])

Parameters

target The target path of the movie clip to drag.

lock A Boolean value specifying whether the draggable movie clip is locked to the center of the mouse position (true), or locked to the point where the user first clicked on the movie clip (false). This parameter is optional.

left, top, right, bottom Values relative to the coordinates of the movie clip's parent that specify a constraint rectangle for the movie clip. These parameters are optional.

Returns

Nothing.

Description

Function; makes the target movie clip draggable while the movie is playing. Only one movie clip can be dragged at a time. Once a startDrag() operation is executed, the movie clip remains draggable until explicitly stopped by stopDrag(), or until a startDrag() action for another movie clip is called.

Example

To create a movie clip that users can position in any location, attach the startDrag() and stopDrag() actions to a button inside the movie clip.

on(press) {
  startDrag(this,true);
}
on(release) {
  stopDrag();
}

See also

MovieClip._droptarget, MovieClip.startDrag(), stopDrag()


static

Availability

Flash Player 6.

Usage

class someClassName{
  static var name;
  static function name() {
    // your statements here
  }
}

Note: To use this keyword, you must specify ActionScript 2.0 and Flash Player 6 or later in the Flash tab of your FLA file's Publish Settings dialog box. This keyword is supported only when used in external script files, not in scripts written in the Actions panel.

Parameters

name The name of the variable or function that you want to specify as static.

Description

Keyword; specifies that a variable or function is created only once per class rather than being created in every object based on that class. For more information, see Instance and class members.

You can use this keyword in class definitions only, not in interface definitions.

See also

private, public


stop()

Availability

Flash 2.

Usage

stop()

Parameters

None.

Returns

Nothing.

Description

Function; stops the SWF file that is currently playing. The most common use of this action is to control movie clips with buttons.

See also

gotoAndStop(), MovieClip.gotoAndStop()


stopAllSounds()

Availability

Flash Player 3.

Usage

stopAllSounds()

Parameters

None.

Returns

Nothing.

Description

Function; stops all sounds currently playing in a SWF file without stopping the playhead. Sounds set to stream will resume playing as the playhead moves over the frames they are in.

Example

The following code could be applied to a button that, when clicked, stops all sounds in the SWF file.

on(release) {
  stopAllSounds();
}

See also

Sound class


stopDrag()

Availability

Flash Player 4.

Usage

stopDrag()

Parameters

None.

Returns

Nothing.

Description

Function; stops the current drag operation.

Example

This code stops the drag action on the instance my_mc when the user releases the mouse button:

on(press) {
  startDrag("my_mc");
}
on(release) {
  stopdrag();
}

See also

MovieClip._droptarget, MovieClip.stopDrag(), startDrag()


" " (string delimiter)

Availability

Flash Player 4.

Usage

"text"

Parameters

text A character.

Returns

Nothing.

Description

String delimiter; when used before and after characters, quotation marks indicate that the characters have a literal value and are considered a string—not a variable, numerical value, or other ActionScript element.

Example

This example uses quotation marks to indicate that the value of the variable yourGuess is the literal string "Prince Edward Island" and not the name of a variable. The value of province is a variable, not a literal; to determine the value of province, the value of yourGuess must be located.

yourGuess = "Prince Edward Island";
on(release){
  province = yourGuess;
  trace(province);
}

// displays Prince Edward Island in the Output panel

See also

String class, String()


String class

Availability

Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly).

Description

The String class is a wrapper for the string primitive data type, and provides methods and properties that let you manipulate primitive string value types. You can convert the value of any object into a string using the String() function.

All of the methods of the String class, except for concat(), fromCharCode(), slice(), and substr(), are generic. This means the methods themselves call this.toString() before performing their operations, and you can use these methods with other non-String objects.

Because all string indexes are zero-based, the index of the last character for any string x is x.length - 1.

You can call any of the methods of the String class using the constructor method new String or using a string literal value. If you specify a string literal, the ActionScript interpreter automatically converts it to a temporary String object, calls the method, and then discards the temporary String object. You can also use the String.length property with a string literal.

Do not confuse a string literal with a String object. In the following example, the first line of code creates the string literal s1, and the second line of code creates the String object s2.

s1 = "foo"
s2 = new String("foo")

Use string literals unless you specifically need to use a String object.

Method summary for the String class

Method | Description
String.charAt() | Returns the character at a specific location in a string.
String.charCodeAt() | Returns the value of the character at the specified index as a 16-bit integer between 0 and 65535.
String.concat() | Combines the text of two strings and returns a new string.
String.fromCharCode() | Returns a string made up of the characters specified in the parameters.
String.indexOf() | Returns the position of the first occurrence of a specified substring.
String.lastIndexOf() | Returns the position of the last occurrence of a specified substring.
String.slice() | Extracts a section of a string and returns a new string.
String.split() | Splits a String object into an array of strings by separating the string into substrings.
String.substr() | Returns a specified number of characters in a string, beginning at a specified location.
String.substring() | Returns the characters between two indexes in a string.
String.toLowerCase() | Converts the string to lowercase and returns the result; does not change the contents of the original object.
String.toUpperCase() | Converts the string to uppercase and returns the result; does not change the contents of the original object.

Property summary for the String class

Property | Description
String.length | A nonzero-based integer specifying the number of characters in the specified String object.

Constructor for the String class

Availability

Flash Player 5.

Usage

new String(value)

Parameters

value The initial value of the new String object.

Returns

A reference to a String object.

Description

Constructor; creates a new String object.

See also

String(), " " (string delimiter)


String.charAt()

Availability

Flash Player 5.

Usage

my_str.charAt(index)

Parameters

index An integer that specifies the position of a character in the string. The first character is indicated by 0, and the last character is indicated by my_str.length-1.

Returns

A character.

Description

Method; returns the character in the position specified by the parameter index. If index is not a number from 0 to string.length - 1, an empty string is returned.

This method is similar to String.charCodeAt() except that the returned value is a character, not a 16-bit integer character code.

Example

In the following example, this method is called on the first letter of the string "Chris".

my_str = new String("Chris");
i = my_str.charCodeAt(0); // i = "C"


String.charCodeAt()

Availability

Flash Player 5.

Usage

my_str.charCodeAt(index)

Parameters

index An integer that specifies the position of a character in the string. The first character is indicated by 0, and the last character is indicated by my_str.length - 1.

Returns

An integer.

Description

Method; returns a 16-bit integer from 0 to 65535 that represents the character specified by index. If index is not a number from 0 to string.length - 1, NaN is returned.

This method is similar to String.charAt() except that the returned value is a 16-bit integer character code, not a character.

Example

In the following example, this method is called on the first letter of the string "Chris".

my_str = new String("Chris");
i = my_str.charCodeAt(0); // i = 67


String.concat()

Availability

Flash Player 5.

Usage

my_str.concat(value1,...valueN)

Parameters

value1,...valueN Zero or more values to be concatenated.

Returns

A string.

Description

Method; combines the value of the String object with the parameters and returns the newly formed string; the original value, my_str, is unchanged.


String.fromCharCode()

Availability

Flash Player 5.

Usage

String.fromCharCode(c1,c2,...cN)

Parameters

c1,c2,...cN Decimal integers that represent ASCII values.

Returns

A string.

Description

Method; returns a string made up of the characters represented by the ASCII values in the parameters.

Example

This example uses fromCharCode() to insert an @ character in the e-mail address.

address_str = "dog" + String.fromCharCode(64) + "house.net";
trace(address_str); // dog@house.net


String.indexOf()

Availability

Flash Player 5.

Usage

my_str.indexOf(substring, [startIndex])

Parameters

substring An integer or string specifying the substring to be searched for within my_str.

startIndex An optional integer specifying the starting point in my_str to search for the substring.

Returns

The position of the first occurrence of the specified substring, or -1.

Description

Method; searches the string and returns the position of the first occurrence of substring found at or after startIndex within the calling string. If substring is not found, the method returns -1.

See also

String.lastIndexOf()


String.lastIndexOf()

Availability

Flash Player 5.

Usage

my_str.lastIndexOf(substring, [startIndex])

Parameters

substring An integer or string specifying the string to be searched for.

startIndex An optional integer specifying the starting point to search for substring.

Returns

The position of the last occurrence of the specified substring, or -1.

Description

Method; searches the string from right to left and returns the index of the last occurrence of substring found before startIndex within the calling string. If substring is not found, the method returns -1.

See also

String.indexOf()


String.length

Availability

Flash Player 5.

Usage

my_str.length

Description

Property; a nonzero-based integer specifying the number of characters in the specified String object.

Because all string indexes are zero-based, the index of the last character for any string x is x.length - 1.


String.slice()

Availability

Flash Player 5.

Usage

my_str.slice(start, [end])

Parameters

start A number specifying the index of the starting point for the slice. If start is a negative number, the starting point is determined from the end of the string, where -1 is the last character.

end An integer that is 1+ the index of the ending point for the slice. The character indexed by the end parameter is not included in the extracted string. If this parameter is omitted, String.length is used. If end is a negative number, the ending point is determined by counting back from the end of the string, where -1 is the last character.

Returns

A substring of the specified string.

Description

Method; returns a string that includes the start character and all characters up to (but not including) the end character. The original String object is not modified. If the end parameter is not specified, the end of the substring is the end of the string. If the value of start is greater than or equal to the value of end, the method returns an empty string.

Example

The following example sets a variable, text, creates a String object, my_str, and passes it the text variable. The slice() method extracts a section of the string contained in the variable, and trace() sends it to the Output panel. The example shows using both a positive and negative value for the end parameter.

text = "Lexington";
my_str = new String( text );
trace(my_str.slice( 1, 3 )); // "ex"
trace(my_str.slice( 1, -6 )); // "ex"

See also

String.substr(), String.substring()


String.split()

Availability

Flash Player 5.

Usage

my_str.split("delimiter", [limit])

Parameters

delimiter The character or string at which my_str splits.

limit The number of items to place into the array. This parameter is optional.

Returns

An array containing the substrings of my_str.

Description

Method; splits a String object into substrings by breaking it wherever the specified delimiter parameter occurs, and returns the substrings in an array. If you use an empty string ("") as a delimiter, each character in the string is placed as an element in the array, as in the following code.

my_str = "Joe";
i = my_str.split("");
trace (i);

The Output panel displays the following:

J,o,e

If the delimiter parameter is undefined, the entire string is placed into the first element of the returned array.

Example

The following example returns an array with five elements.

my_str = "P, A, T, S, Y";
my_str.split(",");

This example returns an array with two elements, "P" and "A".

my_str.split(",", 2);


String.substr()

Availability

Flash Player 5.

Usage

my_str.substr(start, [length])

Parameters

start An integer that indicates the position of the first character in my_str to be used to create the substring. If start is a negative number, the starting position is determined from the end of the string, where the -1 is the last character.

length The number of characters in the substring being created. If length is not specified, the substring includes all of the characters from the start to the end of the string.

Returns

A substring of the specified string.

Description

Method; returns the characters in a string from the index specified in the start parameter through the number of characters specified in the length parameter. The substr method does not change the string specified by my_str; it returns a new string.


String.substring()

Availability

Flash Player 5.

Usage

my_str.substring(start, [end])

Parameters

start An integer that indicates the position of the first character of my_str used to create the substring. Valid values for start are 0 through String.length - 1. If start is a negative value, 0 is used.

end An integer that is 1+ the index of the last character in my_str to be extracted. Valid values for end are 1 through String.length. The character indexed by the end parameter is not included in the extracted string. If this parameter is omitted, String.length is used. If this parameter is a negative value, 0 is used.

Returns

A string.

Description

Method; returns a string consisting of the characters between the points specified by the start and end parameters. If the end parameter is not specified, the end of the substring is the end of the string. If the value of start equals the value of end, the method returns an empty string. If the value of start is greater than the value of end, the parameters are automatically swapped before the function executes and the original value is unchanged.


String.toLowerCase()

Availability

Flash Player 5.

Usage

my_str.toLowerCase()

Parameters

None.

Returns

A string.

Description

Method; returns a copy of the String object, with all of the uppercase characters converted to lowercase. The original value is unchanged.


String.toUpperCase()

Availability

Flash Player 5.

Usage

my_str.toUpperCase()

Parameters

None.

Returns

A string.

Description

Method; returns a copy of the String object, with all of the lowercase characters converted to uppercase. The original value is unchanged.


String()

Availability

Flash Player 4; behavior changed in Flash Player 7.

Usage

String(expression)

Parameters

expression An expression to convert to a string.

Returns

A string.

Description

Function; returns a string representation of the specified parameter as follows:

If expression is a number, the return string is a text representation of the number.

If expression is a string, the return string is expression.

If expression is an object, the return value is a string representation of the object generated by calling the string property for the object, or by calling Object.toString() if no such property exists.

If expression is undefined, the return values are as follows:

  • In files published for Flash Player 6 or earlier, the result is an empty string ("").
  • In files published for Flash Player 7 or later, the result is undefined.

If expression is a Boolean value, the return string is "true" or "false".

If expression is a movie clip, the return value is the target path of the movie clip in slash (/) notation.

Note: Slash notation is not supported by ActionScript 2.0.

See also

Number.toString(), Object.toString(), String class, " " (string delimiter)


substring

Availability

Flash Player 4. This function has been deprecated in favor of String.substr().

Usage

substring("string", index, count)

Parameters

string The string from which to extract the new string.

index The number of the first character to extract.

count The number of characters to include in the extracted string, not including the index character.

Returns

Nothing.

Description

String function; extracts part of a string. This function is one-based, whereas the String object methods are zero-based.

See also

String.substr()


super

Availability

Flash Player 6.

Usage

super.method([arg1, ..., argN])
super([arg1, ..., argN])

Parameters

method The method to invoke in the superclass.

arg1 Optional parameters that are passed to the superclass version of the method (syntax 1) or to the constructor function of the superclass (syntax 2).

Returns

Both forms invoke a function. The function may return any value.

Description

Operator: the first syntax style may be used within the body of an object method to invoke the superclass version of a method, and can optionally pass parameters (arg1 ... argN) to the superclass method. This is useful for creating subclass methods that add additional behavior to superclass methods, but also invoke the superclass methods to perform their original behavior.

The second syntax style may be used within the body of a constructor function to invoke the superclass version of the constructor function and may optionally pass it parameters. This is useful for creating a subclass that performs additional initialization, but also invokes the superclass constructor to perform superclass initialization.


switch

Availability

Flash Player 4.

Usage

switch (expression){
  caseClause:
  [defaultClause:]
}

Parameters

expression Any expression.

caseClause A case keyword followed by an expression, a colon, and a group of statements to execute if the expression matches the switch expression parameter using strict equality (===).

defaultClause A default keyword followed by statements to execute if none of the case expressions match the switch expression parameter strict equality (===).

Returns

Nothing.

Description

Statement; creates a branching structure for ActionScript statements. Like the if action, the switch action tests a condition and executes statements if the condition returns a value of true.

Example

In the following example, if the number parameter evaluates to 1, the trace() action that follows case 1 executes, if the number parameter evaluates to 2, the trace() action that follows case 2 executes, and so on. If no case expression matches the number parameter, the trace() action that follows the default keyword executes.

switch (number) {
  case 1:
    trace ("case 1 tested true");
    break;
  case 2:
    trace ("case 2 tested true");
    break;
  case 3:
    trace ("case 3 tested true");
    break;
  default:
    trace ("no case tested true")
}

In the following example, there isn't a break in the first case group so if the number is 1, both A and B are sent to the Output panel:

switch (number) {
  case 1:
    trace ("A");
  case 2:
    trace ("B");
    break;
  default:
    trace ("D")
}

See also

=== (strict equality), break, case, default, if


System class

Availability

Flash Player 6.

Description

This is a top-level class that contains the capabilities object (see System.capabilities object), the security object (see System.security object), and the methods, properties, and event handlers listed below.

Method summary for the System class

Method | Description
System.setClipboard() | Replaces the contents of the system clipboard with a text string.
System.showSettings() | Displays a Flash Player Settings panel.

Property summary for the System class

Method | Description
System.exactSettings | Specifies whether to use superdomain or exact-domain matching rules when accessing local settings.
System.useCodepage | Tells Flash Player whether to use Unicode or the traditional code page of the operating system running the player to interpret external text files.

Event handler summary for the System class

Method | Description
System.onStatus | Provides a super event handler for certain objects


System.exactSettings

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

System.exactSettings

Description

Property; specifies whether to use superdomain or exact-domain matching rules when accessing local settings (such as camera or microphone access permissions) or locally persistent data (shared objects). The default value is true for files published for Flash Player 7 or later, and false for files published for Flash Player 6.

If this value is true, the settings and data for a SWF file hosted at here.xyz.com are stored at here.xyz.com, the settings and data for a SWF file hosted at there.xyz.com are stored at there.xyz.com, and so on. If this value is false, the settings and data for SWF files hosted at here.xyz.com, there.xyz.com, and xyz.com are shared, and are all stored at xyz.com.

If some of your files set this property to false and others set it to true, you might find that Swf files in different subdomains share settings and data. For example, if this property is false in a SWF file hosted at here.xyz.com and true in a SWF file hosted at xyz.com, both files will use the same settings and data—namely, those at xyz.com. If this isn't the behavior you want, make sure that you set this property in each file to correctly represent where you want to store settings and data.

If you want to change this property from its default value, issue the System.exactSettings = false command in the first frame of your document. The property can't be changed after any activity that requires access to local settings, such as System.ShowSettings() or SharedObject.getLocal().

If you use loadMovie(), MovieClip.loadMovie(), or MovieClipLoader.loadClip() to load one SWF file into another, all of the files published for Flash Player 7 share a single value for System.exactSettings, and all of the files published for Flash Player 6 share a single value for System.exactSettings. Therefore, if you specify a value for this property in one file published for a particular Player version, you should do so in all files that you plan to load. If you load multiple files, the setting specified in the last file loaded overwrites any previously specified setting.

For more information on how domain matching is implemented in Flash, see Flash Player security features.

See also

SharedObject.getLocal(), System.showSettings()


System.onStatus

Availability

Flash Player 6.

Description

Event handler: provides a "super" event handler for certain objects.

The LocalConnection, NetStream, and SharedObject objects provide an onStatus event handler that uses an information object for providing information, status, or error messages. To respond to this event handler, you must create a function to process the information object, and you must know the format and contents of the information object returned.

In addition to the specific onStatus methods provided for the objects listed above, Flash also provides a "super" function called System.onStatus. If onStatus is invoked for a particular object with a level property of "error" and there is no function assigned to respond to it, Flash processes a function assigned to System.onStatus if it exists.

Note: The Camera and Microphone classes also have onStatus handlers, but do not pass information objects with a level property of "error". Therefore, System.onStatus is not called if you don't specify a function for these handlers.

The following example illustrates how you can create generic and specific functions to process information objects sent by the onStatus method.

// Create generic function
System.onStatus = function(genericError)
{
  // Your script would do something more meaningful here
  trace("An error has occurred. Please try again.");
}

// Create function for NetStream object
// If the NetStream object returns a different information object
// from the one listed below, with a level property of "error",
// System.onStatus will be invoked

videoStream_ns.onStatus = function(infoObject) {
  if (infoObject.code == "NetStream.Play.StreamNotFound") {
    trace("Could not find video file.");
  }
}

See also

Camera.onStatus, LocalConnection.onStatus, Microphone.onStatus, NetStream.onStatus, SharedObject.onStatus


System.setClipboard()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

System.setClipboard(string)

Parameters

string A plain-text string of characters to place on the system clipboard, replacing its current contents (if any). If you pass a string literal, as opposed to a variable of type string, enclose the literal in quotation marks.

Returns

A Boolean value of true if the text was successfully placed on the clipboard, false otherwise.

Description

Method; replaces the contents of the system clipboard with a specified text string.


System.showSettings()

Availability

Flash Player 6.

Usage

System.showSettings([panel])

Parameters

panel An optional number that specifies which Flash Player Settings panel to display, as shown in the following table:

Value passed for panel | Settings panel displayed
None (parameter is omitted) or an unsupported value | Whichever panel was open the last time the user closed the Player Settings panel
0 | Privacy
1 | Local Storage
2 | Microphone
3 | Camera

Returns

Nothing.

Description

Method; displays the specified Flash Player Settings panel, which lets users do any of the following:

  • Allow or deny access to the camera and microphone
  • Specify the local disk space available for shared objects
  • Select a default camera and microphone
  • Specify microphone gain and echo suppression settings

For example, if your application requires the use of a camera, you can tell the user to select Allow in the Privacy Settings panel, and then issue a System.showSettings(0) command. (Make sure your Stage size is at least 215 x 138 pixels; this is the minimum size Flash requires to display the panel.)

See also

Camera.get(), Microphone.get(), SharedObject.getLocal()


System.useCodepage

Availability

Flash Player 6.

Usage

System.useCodepage

Description

Property; a Boolean value that tells Flash Player whether to use Unicode or the traditional code page of the operating system running the player to interpret external text files. The default value of system.useCodepage is false.

  • When the property is set to false, Flash Player interprets external text files as Unicode. (These files must be encoded as Unicode when you save them.)
  • When the property is set to true, Flash Player interprets external text files using the traditional code page of the operating system running the player.

Text that you include or load as an external file (using the #include command, the loadVariables() or getURL actions, or the LoadVars or XML objects) must be encoded as Unicode when you save the text file, in order for Flash Player to recognize it as Unicode. To encode external files as Unicode, save the files in an application that supports Unicode, such as Notepad on Windows 2000.

If you include or load external text files that are not Unicode-encoded, you should set system.useCodepage to true. Add the following code as the first line of code in the first frame of the SWF file that is loading the data:

system.useCodepage = true;

When this code is present, Flash Player interprets external text using the traditional code page of the operating system running Flash Player. This is generally CP1252 for an English Windows operating system and Shift-JIS for a Japanese operating system. If you set system.useCodepage to true, Flash Player 6 and later treat text as Flash Player 5 does. (Flash Player 5 treated all text as if it were in the traditional code page of the operating system running the player.)

If you set system.useCodepage to true, keep in mind that the traditional code page of the operating system running the player must include the characters used in your external text file in order for the text to display. For example, if you load an external text file that contains Chinese characters, those characters will not display on a system that uses the CP1252 code page, because that code page does not include Chinese characters.

To ensure that users on all platforms can view external text files used in your SWF files, you should encode all external text files as Unicode and leave System.useCodepage set to false by default. This way Flash Player 6 and later will interpret the text as Unicode.


System.capabilities object

Availability

Flash Player 6.

Description

You can use the System.capabilities object to determine the abilities of the system and player hosting a SWF file. This allows you to tailor content for different formats. For example, the screen of a cell phone (black and white, 100 square pixels) is different than the 1000-square-pixel color PC screen. To provide appropriate content to as many users as possible, you can use the System.capabilities object to determine the type of device a user has. You can then either specify to the server to send different SWF files based on the device capabilities, or tell the SWF file to alter its presentation based on the capabilities of the device.

You can send capabilities information using a GET or POST HTTP method. The following is an example of a server string for a device that does not have MP3 support and has a 400 x 200 pixel, 8 x 4 centimeter screen:

"A=t&SA=t&SV=t&EV=t&MP3=t&AE=t&VE=t&ACC=f&PR=t&SP=t&SB=f&DEB=t&V=WIN%207%2C0%2C0%2C226&M=Macromedia%20Windows&R=1152x864&DP=72&COL=color&AR=1.0&OS=Windows%20XP&L=en&PT=External&AVD=f&LFD=f"

Property summary for the System.capabilities object

Property | Description | Server string
System.capabilities.avHardwareDisable | Read-only; specifies whether the user's camera and microphone are enabled or disabled. | AVD
System.capabilities.hasAccessibility | Indicates whether the player is running on a system that supports communication between Flash Player and accessibility aids. | ACC
System.capabilities.hasAudio | Indicates whether the player is running on a system that has audio capabilities. | A
System.capabilities.hasAudioEncoder | Indicates whether the player is running on a system that can encode an audio stream, such as that coming from a microphone. | AE
System.capabilities.hasEmbeddedVideo | Indicates whether the player is running on a system that supports embedded video. | EV
System.capabilities.hasMP3 | Indicates whether the player is running on a system that has an MP3 decoder. | MP3
System.capabilities.hasPrinting | Indicates whether the player is running on a system that supports printing. | PR
System.capabilities.hasScreenBroadcast | Indicates whether the player supports the development of screen broadcast applications to be run through the Flash Communication Server. | SB
System.capabilities.hasScreenPlayback | Indicates whether the player supports the playback of screen broadcast applications that are being run through the Flash Communication Server. | SP
System.capabilities.hasStreamingAudio | Indicates whether the player can play streaming audio. | SA
System.capabilities.hasStreamingVideo | Indicates whether the player can play streaming video. | SV
System.capabilities.hasVideoEncoder | Indicates whether the player can encode a video stream, such as that coming from a web camera. | VE
System.capabilities.isDebugger | Indicates whether the player is an officially released version or a special debugging version. | DEB
System.capabilities.language | Indicates the language of the system on which the player is running. | L
System.capabilities.localFileReadDisable | Read-only; specifies whether the player will attempt to read anything (including the first SWF file the player launches with) from the user's hard disk. | LFD
System.capabilities.manufacturer | Indicates the manufacturer of Flash Player. | M
System.capabilities.os | Indicates the operating system hosting Flash Player. | OS
System.capabilities.pixelAspectRatio | Indicates the pixel aspect ratio of the screen. | AR
System.capabilities.playerType | Indicates the type of player: stand-alone, external, plug-in, or ActiveX. | PT
System.capabilities.screenColor | Indicates whether the screen is color, grayscale, or black and white. | COL
System.capabilities.screenDPI | Indicates the dots-per-inch screen resolution, in pixels. | DP
System.capabilities.screenResolutionX | Indicates the horizontal size of the screen. | R
System.capabilities.screenResolutionY | Indicates the vertical size of the screen. | R
System.capabilities.serverString | A URL-encoded string that specifies values for each System.capabilities property. | n/a
System.capabilities.version | A string containing Flash Player version and platform information. | V


System.capabilities.avHardwareDisable

Availability

Flash Player 7.

Usage

System.capabilities.avHardwareDisable

Description

Read-only property; a Boolean value that specifies whether the user's camera and microphone are enabled or disabled.

See also

Camera.get(), Microphone.get(), System.showSettings()


System.capabilities.hasAccessibility

Availability

Flash Player 6 r65.

Usage

System.capabilities.hasAccessibility

Description

Property; a Boolean value that indicates whether the player is running in an environment that supports communication between Flash Player and accessibility aids. The server string is ACC.

See also

Accessibility.isActive(), Accessibility.updateProperties(), _accProps


System.capabilities.hasAudio

Availability

Flash Player 6.

Usage

System.capabilities.hasAudio

Description

Property; a Boolean value that indicates whether the player is running on a system that has audio capabilities. The server string is A.


System.capabilities.hasAudioEncoder

Availability

Flash Player 6.

Usage

System.capabilities.hasAudioEncoder

Description

Property; a Boolean value that indicates whether the player can encode an audio stream, such as that coming from a microphone. The server string is AE.


System.capabilities.hasEmbeddedVideo

Availability

Flash Player 6 r65.

Usage

System.capabilities.hasEmbeddedVideo

Description

Property; a Boolean value that indicates whether the player is running on a system that supports embedded video. The server string is EV.


System.capabilities.hasMP3

Availability

Flash Player 6.

Usage

System.capabilities.hasMP3

Description

Property; a Boolean value that indicates whether the player is running on a system that has an MP3 decoder. The server string is MP3.


System.capabilities.hasPrinting

Availability

Flash Player 6 r65.

Usage

System.capabilities.hasPrinting

Description

Property; a Boolean value that indicates whether the player is running on a system that supports printing. The server string is PR.


System.capabilities.hasScreenBroadcast

Availability

Flash Player 6 r79.

Usage

System.capabilities.hasScreenBroadcast

Description

Property; a Boolean value that indicates whether the player supports the development of screen broadcast applications to be run through the Flash Communication Server. The server string is SB.


System.capabilities.hasScreenPlayback

Availability

Flash Player 6 r79.

Usage

System.capabilities.hasScreenPlayback

Description

Property; a Boolean value that indicates whether the player supports the playback of screen broadcast applications that are being run through the Flash Communication Server. The server string is SP.


System.capabilities.hasStreamingAudio

Availability

Flash Player 6 r65.

Usage

System.capabilities.hasStreamingAudio

Description

Property; a Boolean value that indicates whether the player can play streaming audio. The server string is SA.


System.capabilities.hasStreamingVideo

Availability

Flash Player 6 r65.

Usage

System.capabilities.hasStreamingVideo

Description

Property; a Boolean value that indicates whether the player can play streaming video. The server string is SV.


System.capabilities.hasVideoEncoder

Availability

Flash Player 6.

Usage

System.capabilities.hasVideoEncoder

Description

Property; a Boolean value that indicates whether the player can encode a video stream, such as that coming from a web camera. The server string is VE.


System.capabilities.isDebugger

Availability

Flash Player 6.

Usage

System.capabilities.isDebugger

Description

Property; a Boolean value that indicates whether the player is an officially released version (false) or a special debugging version (true). The server string is DEB.


System.capabilities.language

Availability

Flash Player 6.

Usage

System.capabilities.language

Description

Property; indicates the language of the system on which the player is running. This property is specified as a lowercase two-letter language code from ISO 639-1 and an optional uppercase two-letter country code subtag from ISO 3166. The codes represent the language of the system on which the player is running. The languages themselves are named with the English tags. For example, "fr" specifies French.

Language | Tag | Supported countries and tags
Czech | cs |
Danish | da |
Dutch | nl |
English | en |
Finnish | fi |
French | fr |
German | de |
Hungarian | hu |
Italian | it |
Japanese | ja |
Korean | ko |
Norwegian | no |
Other/unknown | xu |
Polish | pl |
Portuguese | pt |
Russian | ru |
Simplified Chinese | zh | People's Republic of China (Simplified Chinese): zh-CN
Spanish | es |
Swedish | sv |
Traditional Chinese | zh | Taiwan (Traditional Chinese) : zh-TW
Turkish | tr |


System.capabilities.localFileReadDisable

Availability

Flash Player 7.

Usage

System.capabilities.localFileReadDisable

Description

Read-only property; a Boolean value that specifies whether Flash Player attempts to read anything (including the first SWF file that Flash Player launches with) from the user's hard disk.


System.capabilities.manufacturer

Availability

Flash Player 6.

Usage

System.capabilities.manufacturer

Description

Property; a string that indicates the manufacturer of Flash Player, in the format "Macromedia OSName" (OSName could be "Windows", "Macintosh", "Linux", or "Other OS Name"). The server string is M.


System.capabilities.os

Availability

Flash Player 6.

Usage

System.capabilities.os

Description

Property; a string that indicates the current operating system. The os property can return the following strings: "Windows XP", "Windows 2000", "Windows NT", "Windows 98/ME", "Windows 95", "Windows CE" (available only in Flash Player SDK, not in the desktop version), "Linux", and "MacOS". The server string is OS.


System.capabilities.pixelAspectRatio

Availability

Flash Player 6.

Usage

System.capabilities.pixelAspectRatio

Description

Property; an integer that indicates the pixel aspect ratio of the screen. The server string is AR.


System.capabilities.playerType

Availability

Flash Player 7.

Usage

System.capabilities.playerType

Description

Property; a string that indicates the type of player. This property can have the value "StandAlone", "External", "PlugIn", or "ActiveX". The server string is PT.


System.capabilities.screenColor

Availability

Flash Player 6.

Usage

System.capabilities.screenColor

Description

Property; indicates whether the screen is color (color), grayscale (gray), or black and white (bw). The server string is COL.


System.capabilities.screenDPI

Availability

Flash Player 6.

Usage

System.capabilities.screenDPI

Description

Property; indicates the dots-per-inch (dpi) resolution of the screen, in pixels. The server string is DP.


System.capabilities.screenResolutionX

Availability

Flash Player 6.

Usage

System.capabilities.screenResolutionX

Description

Property; an integer that indicates the maximum horizontal resolution of the screen. The server string is R (which returns both the width and height of the screen).


System.capabilities.screenResolutionY

Availability

Flash Player 6.

Usage

System.capabilities.screenResolutionY

Description

Property; an integer that indicates the maximum vertical resolution of the screen. The server string is R (which returns both the width and height of the screen).


System.capabilities.serverString

Availability

Flash Player 6.

Usage

System.capabilities.serverString

Description

Property; a URL-encoded string that specifies values for each System.capabilities property, as in this example:

A=t&SA=t&SV=t&EV=t&MP3=t&AE=t&VE=t&ACC=f&PR=t&SP=t&SB=f&DEB=t&V=WIN%207%2C0%2C0%2C226&M=Macromedia%20Windows&R=1152x864&DP=72&COL=color&AR=1.0&OS=Windows%20XP&L=en&PT=External&AVD=f&LFD=f


System.capabilities.version

Availability

Flash Player 6.

Usage

System.capabilities.version

Description

Property; a string containing the Flash Player platform and version information, for example, "WIN 7,0,0,231". The server string is V.


System.security object

Availability

Flash Player 6.

Description

This object contains methods that specify how SWF files in different domains can communicate with each other.

Method summary for the System.security object

Method | Description
System.security.allowDomain() | Allows SWF files in the identified domains to access objects and variables in the calling SWF file, or in any other SWF file from the same domain as the calling SWF file.
System.security.allowInsecureDomain() | Allows SWF files in the identified domains to access objects and variables in the calling SWF file, which is hosted using the HTTPS protocol.


System.security.allowDomain()

Availability

Flash Player 6; behavior changed in Flash Player 7.

Usage

System.security.allowDomain("domain1", "domain2, ... domainN")

Parameters

domain1, domain2, ... domainN Strings that specify domains that can access objects and variables in the file containing the System.Security.allowDomain() call. The domains can be formatted in the following ways:

  • "domain.com"
  • "http://domain.com"
  • "http://IPaddress"

Description

Method; allows SWF files in the identified domains to access objects and variables in the calling SWF file, or in any other SWF file from the same domain as the calling SWF file.

In files playing back in Flash Player 7 or later, the parameter(s) passed must follow exact-domain naming rules. For example, to allow access by SWF files hosted at either www.domain.com or store.domain.com, both domain names must be passed:

// For Flash Player 6
System.security.allowDomain("domain.com");
// Corresponding commands to allow access by SWF files
// that are running in Flash Player 7 or later
System.security.allowDomain("www.domain.com". "store.domain.com");

Also, for files running in Flash Player 7 or later, you can't use this method to allow SWF files hosted using a secure protocol (HTTPS) to permit access from SWF files hosted in nonsecure protocols; you must use System.security.allowInsecureDomain() instead.

Occasionally, you might encounter the following situation. Suppose you load a child SWF file from a different domain. You want to implement this method so that the child SWF can script the parent movie, but you don't know the final domain from which the child SWF will come. This can happen, for example, when you use load-balancing redirects or third-party servers.

In this situation, you can use the MovieClip._url property as an argument to this method. For example, if you load a SWF file into my_mc, you can then call System.security.allowDomain(my_mc._url).

If you do this, be sure to wait until the SWF file in my_mc is loaded, because the _url property will not have its final, correct value until the file is completely loaded. The best way to determine when a child SWF finishes loading is to use MovieClipLoader.onLoadComplete().

The opposite situation can also occur: that is, you might create a child SWF file that wants to allow its parent to script it, but doesn't know what the domain of its parent will be. In this situation, call System.security.allowDomain(_parent._url) from the child SWF. In this situation, you don't have to wait for the parent SWF file to load; the parent will already be loaded by the time the child loads.

Example

The SWF file located at www.macromedia.com/MovieA.swf contains the following lines.

System.security.allowDomain("www.shockwave.com");
loadMovie("http://www.shockwave.com/MovieB.swf", _root.my_mc);

Because MovieA contains the allowDomain() command, MovieB can access the objects and variables in MovieA. If MovieA didn't contain this command, the Flash security implementation would prevent MovieA from accessing MovieB's objects and variables.

See also

MovieClip._url, MovieClipLoader.onLoadComplete(), _parent


System.security.allowInsecureDomain()

Availability

Flash Player 7.

Usage

System.Security.allowInsecureDomain("domain")

Parameters

domain An exact domain name, such as "www.myDomainName.com" or "store.myDomainName.com".

Returns

Nothing.

Description

Method; allows SWF files in the identified domains to access objects and variables in the calling SWF file, which is hosted using the HTTPS protocol.

By default, SWF files hosted using the HTTPS protocol can be accessed only by other SWF files hosted using the HTTPS protocol. This implementation maintains the integrity provided by the HTTPS protocol.

Macromedia does not recommend using this method to override the default behavior because it compromises HTTPS security. However, you may need to do so, for example, if you must permit access to HTTPS files published for Flash Player 7 or later from HTTP files published for Flash Player 6.

A SWF file published for Flash Player 6 can use System.security.allowDomain() to permit HTTP to HTTPS access. However, because security is implemented differently in Flash Player 7, you must use System.Security.allowInsecureDomain() to permit such access in SWF files published for Flash Player 7 or later.

Example

In this example, you host a math test on a secure domain so that only registered students can access it. You have also developed a number of SWF files that illustrate certain concepts, which you host on an insecure domain. You want students to be able to access the test from the SWF file that contains information about a concept.

// This SWF file is at https://myEducationSite.somewhere.com/mathTest.swf
// Concept files are at http://myEducationSite.somewhere.com
System.Security.allowInsecureDomain("myEducationSite.somewhere.com")

See also

System.security.allowDomain(), System.exactSettings


targetPath

Availability

Flash Player 5.

Usage

targetpath(movieClipObject)

Parameters

movieClipObject Reference (for example, _root or _parent) to the movie clip for which the target path is being retrieved.

Returns

A string containing the target path of the specified movie clip.

Description

Function; returns a string containing the target path of movieClipObject. The target path is returned in dot notation. To retrieve the target path in slash notation, use the _target property.

Example

This example displays the target path of a movie clip as soon as it loads.

onClipEvent(load){
  trace(targetPath(this));
}

See also

eval()


tellTarget

Availability

Flash Player 3. (Deprecated in Flash 5; use of dot notation and the with action is recommended.)

Usage

tellTarget("target") {
  statement(s);
}

Parameters

target A string that specifies the target path of the Timeline to be controlled.

statement(s) The instructions to execute if the condition evaluates to true.

Returns

Nothing.

Description

Deprecated action; applies the instructions specified in the statements parameter to the Timeline specified in the target parameter. The tellTarget action is useful for navigation controls. Assign tellTarget to buttons that stop or start movie clips elsewhere on the Stage. You can also make movie clips go to a particular frame in that clip. For example, you might assign tellTarget to buttons that stop or start movie clips on the Stage or prompt movie clips to jump to a particular frame.

In Flash 5 or later, you can use dot notation instead of the tellTarget action. You can use the with action to issue multiple actions to the same Timeline. You can use the with action to target any object, whereas the tellTarget action can only target movie clips.

Example

This tellTarget statement controls the movie clip instance ball on the main Timeline. Frame 1 of the ball instance is blank and has a stop() action so that it isn't visible on the Stage. When the button with the following action is clicked, tellTarget tells the playhead in ball to go to Frame 2 where the animation starts.

on(release) {
  tellTarget("ball") {
    gotoAndPlay(2);
  }
}

The following example uses dot notation to achieve the same results.

on(release) {
  ball.gotoAndPlay(2);
}

If you need to issue multiple commands to the ball instance, you can use the with action, as in the following statement.

on(release) {
  with(ball) {
    gotoAndPlay(2);
    _alpha = 15;
    _xscale = 50;
    _yscale = 50;
  }
}

See also

with


TextField class

Availability

Flash Player 6.

Description

All dynamic and input text fields in a SWF file are instances of the TextField class. You can give a text field an instance name in the Property inspector and use the methods and properties of the TextField class to manipulate it with ActionScript. TextField instance names are displayed in the Movie Explorer and in the Insert Target Path dialog box in the Actions panel.

The TextField class inherits from the Object class.

To create a text field dynamically, you can use MovieClip.createTextField().

Method summary for the TextField class

Method | Description
TextField.addListener() | Registers an object to receive notification when the onChanged and onScroller event handlers are invoked.
TextField.getFontList() | Returns names of fonts on the player's host system as an array.
TextField.getDepth() | Returns the depth of a text field.
TextField.getNewTextFormat() | Gets the default text format assigned to newly inserted text.
TextField.getTextFormat() | Returns a TextFormat object containing formatting information for some or all text in a text field.
TextField.removeListener() | Removes a listener object.
TextField.removeTextField() | Removes a text field that was created with MovieClip.createTextField().
TextField.replaceSel() | Replaces the current selection.
TextField.setNewTextFormat() | Sets a TextFormat object for text that is inserted by a user or by a method.
TextField.setTextFormat() | Sets a TextFormat object for a specified range of text in a text field.

Property summary for the TextField class

Property | Description
TextField._alpha | The transparency value of a text field instance.
TextField.autoSize | Controls automatic alignment and sizing of a text field.
TextField.background | Indicates if the text field has a background fill.
TextField.backgroundColor | Indicates the color of the background fill.
TextField.border | Indicates if the text field has a border.
TextField.borderColor | Indicates the color of the border.
TextField.bottomScroll | The bottommost visible line in a text field. Read-only.
TextField.embedFonts | Indicates whether the text field uses embedded font outlines or device fonts.
TextField._height | The height of a text field instance in pixels. This only affects the bounding box of the text field, it does not affect the border thickness or text font size.
TextField._highquality | Indicates the rendering quality of the SWF file.
TextField.hscroll | Indicates the horizontal scroll value of a text field.
TextField.html | Indicates the current maximum scrolling position of a text field.
TextField.htmlText | Contains the HTML representation of a text field's contents.
TextField.length | The number of characters in a text field. Read-only.
TextField.maxChars | The maximum number of characters that a text field can contain.
TextField.maxhscroll | The maximum value of TextField.hscroll. Read-only.
TextField.maxscroll | The maximum value of TextField.scroll. Read-only.
TextField.menu | Associates a ContextMenu object with a text field.
TextField.mouseWheelEnabled | Indicates whether Flash Player should automatically scroll multiline text fields when the mouse pointer is positioned over a text field and the user rolls the mouse wheel.
TextField.multiline | Indicates if the text field contains multiple lines.
TextField._name | The instance name of a text field instance.
TextField._parent | A reference to the instance that is the parent of this instance; either of type Button or MovieClip.
TextField.password | Indicates if a text field hides the input characters.
TextField._quality | Indicates the rendering quality of a SWF file.
TextField.restrict | The set of characters that a user can enter into a text field.
TextField._rotation | The degree of rotation of a text field instance.
TextField.scroll | Indicates the current scrolling position of a text field.
TextField.selectable | Indicates whether a text field is selectable.
TextField._soundbuftime | The amount of time a sound must prebuffer before it streams.
TextField.tabEnabled | Indicates whether a movie clip is included in automatic tab ordering.
TextField.tabIndex | Indicates the tab order of an object.
TextField._target | The target path of the specified text field instance. Read-only.
TextField.text | The current text in the text field.
TextField.textColor | The color of the current text in the text field.
TextField.textHeight | The height of the text field's bounding box.
TextField.textWidth | The width of the text field's bounding box.
TextField.type | Indicates whether a text field is an input text field or dynamic text field.
TextField._url | The URL of the SWF file that created the text field instance. Read-only.
TextField.variable | The variable name associated with the text field.
TextField._visible | A Boolean value that determines whether a text field instance is hidden or visible.
TextField._width | The width of a text field instance in pixels. This only affects the bounding box of the text field, it does not affect the border thickness or text font size.
TextField.wordWrap | Indicates whether the text field word-wraps.
TextField._x | The x coordinate of a text field instance
TextField._xmouse | The x coordinate of the pointer relative to a text field instance. Read-only.
TextField._xscale | The value specifying the percentage for horizontally scaling a text field instance.
TextField._y | The y coordinate of a text field instance.
TextField._ymouse | The y coordinate of the pointer relative to a text field instance. Read-only.
TextField._yscale | The value specifying the percentage for vertically scaling a text field instance.

Event handler summary for the TextField class

Event handler | Description
TextField.onChanged | Invoked when the text field is changed.
TextField.onKillFocus | Invoked when the text field loses focus.
TextField.onScroller | Invoked when one of the text field scroll properties changes.
TextField.onSetFocus | Invoked when the text field receives focus.

Listener summary for the TextField class

Method | Description
TextField.onChanged | Notified when the text field is changed.
TextField.onScroller | Notified when the scroll or maxscroll property of a text field changes.


TextField.addListener()

Availability

Flash Player 6.

Usage

my_txt.addListener(listener)

Parameters

listener An object with an onChanged or onScroller event handler.

Returns

Nothing.

Description

Method; registers an object to receive notification when the onChanged and onScroller event handlers have been invoked. When a text field changes or is scrolled, the TextField.onChanged and TextField.onScroller event handlers are invoked, followed by the onChanged and onScroller event handlers of any objects registered as listeners. Multiple objects can be registered as listeners.

To remove a listener object from a text field, call TextField.removeListener().

A reference to the text field instance is passed as a parameter to the onScroller and onChanged handlers by the event source. You can capture this data by putting a parameter in the event handler method. For example, the following code uses txt as the parameter that is passed to the onScroller event handler. The parameter is then used in a trace statement to send the instance name of the text field to the Output panel.

myTextField.onScroller = function (txt) {
  trace (txt._name + " changed");
};

Example

The following example defines an onChange handler for the input text field myText. It then defines a new listener object, myListener, and defines an onChanged handler for that object. This handler will be invoked when the text field myText is changed. The final line of code calls TextField.addListener to register the listener object myListener with the text field myText so that it will be notified when myText changes.

myText.onChanged = function (txt) {
  trace(txt._name + " changed");
};
myListener = new Object();
myListener.onChanged = function (txt) {
  trace(txt._name + " changed and notified myListener");
};

myText.addListener(myListener);

See also

TextField.onChanged, TextField.onScroller, TextField.removeListener()


TextField._alpha

Availability

Flash Player 6.

Usage

my_txt._alpha

Description

Property; sets or retrieves the alpha transparency value of the text field specified by my_txt. Valid values are 0 (fully transparent) to 100 (fully opaque). The default value is 100.

Example

The following code sets the _alpha property of a text field named text1_txt to 30% when the button is clicked:

on(release) {
  text1_txt._alpha = 30;
}

See also

Button._alpha, MovieClip._alpha


TextField.autoSize

Availability

Flash Player 6.

Usage

my_txt.autoSize

Description

Property; controls automatic sizing and alignment of text fields. Acceptable values for autoSize are "none" (the default), "left", "right", and "center". When you set the autoSize property, true is a synonym for "left" and false is a synonym for "none".

The values of autoSize, multiline, and wordWrap determine whether a text field expands or contracts to the left side, right side, or bottom side. You can use the following code and enter different values for autoSize, multiline, and wordWrap to see how the field resizes when these values change.

createTextField("my_txt", 1, 0, 0, 200, 20);
with (my_txt) {
  border = true;
  borderColor = 0x000000;
  multiline = false;
  wordWrap = false;
  autoSize = "none";
  text = "Here is a whole bunch of text that won't fit in the field ";
}

Example

The following sets the autosize property of the text field my_txt to "center".

my_txt.autosize = "center";


TextField.background

Availability

Flash Player 6.

Usage

my_txt.background

Description

Property; if true, the text field has a background fill. If false, the text field has no background fill.


TextField.backgroundColor

Availability

Flash Player 6.

Usage

my_txt.backgroundColor

Description

Property; the color of the text field background. Default is 0xFFFFFF (white). This property may be retrieved or set, even if there currently is no background but the color is only visible if the text field has a border.

See also

TextField.background


TextField.border

Availability

Flash Player 6.

Usage

my_txt.border

Description

Property; if true, the text field has a border. If false, the text field has no border.


TextField.borderColor

Availability

Flash Player 6.

Usage

my_txt.borderColor

Description

Property; the color of the text field border, the Default is 0x000000 (black). This property may be retrieved or set, even if there is currently no border.

See also

TextField.border


TextField.bottomScroll

Availability

Flash Player 6.

Usage

my_txt.bottomScroll

Description

Property (read-only); an integer (one-based index) that indicates the bottommost line that is currently visible in my_txt. Think of the text field as a "window" onto a block of text. The property TextField.scroll is the one-based index of the topmost visible line in the window.

All the text between lines TextField.scroll and TextField.bottomScroll is currently visible in the text field.


TextField.condenseWhite

Availability

Flash Player 6.

Usage

my_txt.condenseWhite

Description

Property; a Boolean value that specifies whether extra white space (spaces, line breaks, and so on) in an HTML text field should be removed when the field is rendered in a browser. The default value is false.

If you set this value to true, you must use standard HTML commands such as <BR> and <P> to place line breaks in the text field.

If my_txt.html is false, this property is ignored.

See also

TextField.html


TextField.embedFonts

Availability

Flash Player 6.

Usage

my_txt.embedFonts

Description

Property; a Boolean value that, when true, renders the text field using embedded font outlines. If false, it renders the text field using device fonts.


TextField.getDepth()

Availability

Flash Player 6.

Usage

my_txt.getDepth()

Parameters

None.

Returns

An integer.

Description

Method; returns the depth of a text field.


TextField.getFontList()

Availability

Flash Player 6.

Usage

TextField.getFontList()

Parameters

None.

Returns

An array.

Description

Method; a static method of the global TextField class. You don't specify a specific text field (such as my_txt) when you call this method. This method returns names of fonts on the player's host system as an array. (It does not return names of all fonts in currently loaded SWF files.) The names are of type string.

Example

The following code displays a font list returned by getFontList().

font_array = TextField.getFontList();
for( i in font_array){

  trace(font_array[i]);

}


TextField.getNewTextFormat()

Availability

Flash Player 6.

Usage

my_txt.getNewTextFormat()

Parameters

None.

Returns

A TextFormat object.

Description

Method; returns a TextFormat object containing a copy of the text field's text format object. The text format object is the format that newly inserted text, such as text inserted with the replaceSel() method or text entered by a user, receives. When getNewTextFormat() is invoked, the TextFormat object returned has all of its properties defined. No property is null.


TextField.getTextFormat()

Availability

Flash Player 6.

Usage

my_txt.getTextFormat()
my_txt.getTextFormat(index)
my_txt.getTextFormat(beginIndex, endIndex)

Parameters

index An integer that specifies a character in a string.

beginIndex, endIndex Integers that specify the starting and ending locations of a span of text within my_txt.

Returns

An object.

Description

Method; Usage 1: returns a TextFormat object containing formatting information for all text in a text field. Only properties that are common to all text in the text field are set in the resulting TextFormat object. Any property which is mixed, meaning that it has different values at different points in the text, has its value set to null.

Usage 2: Returns a TextFormat object containing a copy of the text field's text format at index.

Usage 3: Returns a TextFormat object containing formatting information for the span of text from beginIndex to endIndex.

See also

TextField.getNewTextFormat(), TextField.setNewTextFormat(), TextField.setTextFormat()


TextField._height

Availability

Flash Player 6.

Usage

my_txt._height

Description

Property; the height of the text field, in pixels.

Example

The following code example sets the height and width of a text field.

my_txt._width = 200;
my_txt._height = 200;


TextField._highquality

Availability

Flash Player 6.

Usage

my_txt._highquality

Description

Property (global); specifies the level of anti-aliasing applied to the current SWF file. Specify 2 (best quality) to apply high quality with bitmap smoothing always on. Specify 1 (high quality) to apply anti-aliasing; this will smooth bitmaps if the SWF file does not contain animation. Specify 0 (low quality) to prevent anti-aliasing.

See also

_quality


TextField.hscroll

Availability

Flash Player 6.

Usage

my_txt.hscroll

Returns

An integer.

Description

Property; indicates the current horizontal scrolling position. If the hscroll property is 0, the text is not horizontally scrolled.

For more information on scrolling text, see Creating scrolling text.

Example

The following example scrolls the text horizontally.

on (release) {
  my_txt.hscroll += 1;
}

See also

TextField.maxhscroll, TextField.scroll


TextField.html

Availability

Flash Player 6.

Usage

my_txt.html

Description

Property; a flag that indicates whether the text field contains an HTML representation. If the html property is true, the text field is an HTML text field. If html is false, the text field is a non-HTML text field.

See also

TextField.htmlText


TextField.htmlText

Availability

Flash Player 6.

Usage

my_txt.htmlText

Description

Property; if the text field is an HTML text field, this property contains the HTML representation of the text field's contents. If the text field is not an HTML text field, it behaves identically to the text property. You can indicate that a text field is an HTML text field in the Property inspector, or by setting the text field's html property to true.

Example

In the following example, the text in the text field text2 is rendered bold.

text2.html = true;
text2.htmlText = "<b> this is bold text </b>";

See also

TextField.html


TextField.length

Availability

Flash Player 6.

Usage

my_txt.length

Returns

A number.

Description

Property (read-only); indicates the number of characters in a text field. This property returns the same value as text.length, but is faster. A character such as tab ("\t") counts as one character.


TextField.maxChars

Availability

Flash Player 6.

Usage

my_txt.maxChars

Description

Property; indicates the maximum number of characters that the text field can contain. A script may insert more text than maxChars allows; the maxChars property only indicates how much text a user can enter. If the value of this property is null, there is no limit on the amount of text a user can enter.


TextField.maxhscroll

Availability

Flash Player 6.

Usage

my_txt.maxhscroll

Description

Property (read-only); indicates the maximum value of TextField.hscroll.


TextField.maxscroll

Availability

Flash Player 6.

Usage

TextField.maxscroll

Description

Property (read-only); indicates the maximum value of TextField.scroll.

For more information on scrolling text, see Creating scrolling text.


TextField.menu

Availability

Flash Player 7.

Usage

my_txt.menu = contextMenu

Parameters

contextMenu A ContextMenu object.

Description

Property; associates the ContextMenu object contextMenu with the text field my_txt. The ContextMenu class lets you modify the context menu that appears when the user right-clicks (Windows) or Control-clicks (Macintosh) in Flash Player.

This property works only with selectable (editable) text fields; it has no affect on nonselectable text fields.

Example

The following example assigns the ContextMenu object menu_cm to the text field news_txt. The ContextMenu object contains a custom menu item labeled "Print" with an associated callback handler named doPrint(), which performs printing operations (not shown):

var menu_cm = new ContextMenu();
menu_cm.customItems.push(new ContextMenuItem("Print...", doPrint));
function doPrint(menu, obj) {
  // "Print" code here
}
news_txt.menu = menu_cm;

See also

Button.menu, ContextMenu class, ContextMenuItem class, MovieClip.menu


TextField.mouseWheelEnabled

Availability

Flash Player 7.

Usage

my_txt.mouseWheelEnabled

Description

Property; a Boolean value that indicates whether Flash Player should automatically scroll multiline text fields when the mouse pointer is positioned over a text field and the user rolls the mouse wheel. By default, this value is true. This property is useful if you want to prevent mouse wheel scrolling of text fields, or implement your own text field scrolling.

See also

Mouse.onMouseWheel


TextField.multiline

Availability

Flash Player 6.

Usage

my_txt.multiline

Description

Property; indicates whether the text field is a multiline text field. If the value is true, the text field is multiline; if the value is false, the text field is a single-line text field.


TextField._name

Availability

Flash Player 6.

Usage

my_txt._name

Description

Property; the instance name of the text field specified by my_txt.


TextField.onChanged

Availability

Flash Player 6.

Usage

my_txt.onChanged = function(){
  // your statements here
}

Parameters

None.

Returns

The instance name of the text field.

Description

Event handler; invoked when the content of a text field changes. By default, it is undefined; you can define it in a script.

A reference to the text field instance is passed as a parameter to the onChanged handler. You can capture this data by putting a parameter in the event handler method. For example, the following code uses txt as the parameter that is passed to the onChanged event handler. The parameter is then used in a trace() statement to send the instance name of the text field to the Output panel.

myTextField.onChanged = function (txt) {
  trace (txt._name + " changed");
};


TextField.onKillFocus

Availability

Flash Player 6.

Usage

my_txt.onKillFocus = function(newFocus){
  // your statements here
}

Parameters

newFocus The object that is receiving the focus.

Returns

Nothing.

Description

Event handler; invoked when a text field loses keyboard focus. The onKillFocus method receives one parameter, newFocus, which is an object representing the new object receiving the focus. If no object receives the focus, newFocus contains the value null.


TextField.onScroller

Availability

Flash Player 6.

Usage

my_txt.onScroller = function(textFieldInstance){
  // your statements here
}

Parameters

textFieldInstance A reference to the TextField object whose scroll position was changed.

Returns

Nothing.

Description

Event handler; invoked when one of the text field scroll properties changes.

A reference to the text field instance is passed as a parameter to the onScroller handler. You can capture this data by putting a parameter in the event handler method. For example, the following code uses txt as the parameter that is passed to the onScroller event handler. The parameter is then used in a trace() statement to send the instance name of the text field to the Output panel.

myTextField.onScroller = function (txt) {
  trace (txt._name + " scrolled");
};

See also

TextField.hscroll, TextField.maxhscroll, TextField.maxscroll, TextField.scroll


TextField.onSetFocus

Availability

Flash Player 6.

Usage

my_txt.onSetFocus = function(oldFocus){
  // your statements here
}

Parameters

oldFocus The object to lose focus.

Returns

Nothing.

Description

Event handler; invoked when a text field receives keyboard focus. The oldFocus parameter is the object that loses the focus. For example, if the user presses the Tab key to move the input focus from a button to a text field, oldFocus contains the text field instance.

If there is no previously focused object, oldFocus contains a null value.


TextField._parent

Availability

Flash Player 6.

Usage

my_txt._parent.property
_parent.property

Description

Property; a reference to the movie clip or object that contains the current text field or object. The current object is the one containing the ActionScript code that references _parent.

Use _parent to specify a relative path to movie clips or objects that are above the current text field. You can use _parent to climb up multiple levels in the display list as in the following:

_parent._parent._alpha = 20;

See also

Button._parent, MovieClip._parent, _root, targetPath


TextField.password

Availability

Flash Player 6.

Usage

my_txt.password

Description

Property; if the value of password is true, the text field is a password text field and hides the input characters. If false, the text field is not a password text field.


TextField._quality

Availability

Flash Player 6.

Usage

my_txt._quality

Description

Property (global); sets or retrieves the rendering quality used for a SWF file. Device fonts are always aliased and, therefore, are unaffected by the _quality property.

Note: Although you can specify this property for a TextField object, it is actually a global property, and you can specify its value simply as _quality. For more information, see _quality.


TextField.removeListener()

Availability

Flash Player 6.

Usage

my_txt.removeListener(listener)

Parameters

listener The object that will no longer receive notifications from TextField.onChanged or TextField.onScroller.

Returns

If listener was successfully removed, the method returns a true value. If listener was not successfully removed (for example, if listener was not on the TextField object's listener list), the method returns a value of false.

Description

Method; removes a listener object previously registered to a text field instance with TextField.addListener().


TextField.removeTextField()

Availability

Flash Player 6.

Usage

my_txt.removeTextField()

Description

Method; removes the text field specified by my_txt. This operation can only be performed on a text field that was created with MovieClip.createTextField(). When you call this method, the text field is removed. This method is similar to MovieClip.removeMovieClip().


TextField.replaceSel()

Availability

Flash Player 6.

Usage

my_txt.replaceSel(text)

Parameters

text A string.

Returns

Nothing.

Description

Method; replaces the current selection with the contents of the text parameter. The text is inserted at the position of the current selection, using the current default character format and default paragraph format. The text is not treated as HTML, even if the text field is an HTML text field.

You can use the replaceSel() method to insert and delete text without disrupting the character and paragraph formatting of the rest of the text.

You must use Selection.setFocus() to focus the field before issuing this command.

See also

Selection.setFocus()


TextField.replaceText()

Availability

Flash Player 7.

Usage

my_txt.replaceText(beginIndex, endIndex, text)

Description

Method; replaces a range of characters, specified by the beginIndex and endIndex parameters, in the specified text field with the contents of the text parameter.


TextField.restrict

Availability

Flash Player 6.

Usage

my_txt.restrict

Description

Property; indicates the set of characters that a user may enter into the text field. If the value of the restrict property is null, you can enter any character. If the value of the restrict property is an empty string, you can't enter any character. If the value of the restrict property is a string of characters, you can enter only characters in the string into the text field. The string is scanned from left to right. A range may be specified using the dash (-). This only restricts user interaction; a script may put any text into the text field. This property does not synchronize with the Embed Font Outlines check boxes in the Property inspector.

If the string begins with ^, all characters are initially accepted and succeeding characters in the string are excluded from the set of accepted characters. If the string does not begin with ^, no characters are initially accepted and succeeding characters in the string are included in the set of accepted characters.

Example

The following example allows only uppercase characters, spaces, and numbers to be entered into a text field:

my_txt.restrict = "A-Z 0-9";

The following example includes all characters, but excludes lowercase letters:

my_txt.restrict = "^a-z";

You can use a backslash to enter a ^ or - verbatim. The accepted backslash sequences are \-, \^ or \\. The backslash must be an actual character in the string, so when specified in ActionScript, a double backslash must be used. For example, the following code includes only the dash (-) and caret (^):

my_txt.restrict = "\\-\\^";

The ^ may be used anywhere in the string to toggle between including characters and excluding characters. The following code includes only uppercase letters, but excludes the uppercase letter Q:

my_txt.restrict = "A-Z^Q";

You can use the \u escape sequence to construct restrict strings. The following code includes only the characters from ASCII 32 (space) to ASCII 126 (tilde).

my_txt.restrict = "\u0020-\u007E";


TextField._rotation

Availability

Flash Player 6.

Usage

my_txt._rotation

Description

Property; the rotation of the text field, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement my_txt._rotation = 450 is the same as my_txt._rotation = 90.

See also

Button._rotation, MovieClip._rotation


TextField.scroll

Availability

Flash Player 6.

Usage

my_txt.scroll

Description

Property; defines the vertical position of text in a text field. The scroll property is useful for directing users to a specific paragraph in a long passage, or creating scrolling text fields. This property can be retrieved and modified.

For more information on scrolling text, see Creating scrolling text.

Example

The following code is attached to an Up button that scrolls the my_txt text field.

on (release) {
  my_txt.scroll = myText.scroll + 1;
}

See also

TextField.hscroll, TextField.maxscroll


TextField.selectable

Availability

Flash Player 6.

Usage

my_txt.selectable

Description

Property; a Boolean value that indicates whether the text field is selectable (editable). The value true indicates that the text is selectable.


TextField.setNewTextFormat()

Availability

Flash Player 6.

Usage

my_txt.setNewTextFormat(textFormat)

Parameters

textFormat A TextFormat object.

Returns

Nothing.

Description

Method; sets a TextFormat object for newly inserted text, such as text inserted with the replaceSel() method or text entered by a user in a text field. Each text field has a new text format. When text is inserted, the new text is assigned the new text format.

The text format is set in a new TextFormat object. It contains both character and paragraph formatting information. Character formatting information describes the appearance of individual characters; for example, font name, point size, color, and associated URL. Paragraph formatting information describes the appearance of a paragraph; for example, left margin, right margin, indentation of the first line, and left, right, and center alignment.

See also

TextField.getNewTextFormat(), TextField.getTextFormat(), TextField.setTextFormat()


TextField.setTextFormat()

Availability

Flash Player 6.

Usage

my_txt.setTextFormat (textFormat)
my_txt.setTextFormat (index, textFormat)
my_txt.setTextFormat (beginIndex, endIndex, textFormat)

Parameters

textFormat A TextFormat object, which contains character and paragraph formatting information.

index An integer that specifies a character within my_txt.

beginIndex An integer.

endIndex An integer that specifies the first character after the desired text span.

Returns

Nothing.

Description

Method; sets a TextFormat object for a specified range of text in a text field. You can assign each character in a text field a text format. The text format of the first character of a paragraph is examined to perform paragraph formatting for the entire paragraph. The setTextFormat() method changes the text format applied to individual characters, to groups of characters, or to the entire body of text in a text field.

The text format is set in a new TextFormat object. It contains both character and paragraph formatting information. Character formatting information describes the appearance of individual characters, for example, font name, point size, color, and associated URL. Paragraph formatting information describes the appearance of a paragraph, for example, left margin, right margin, indentation of the first line, and left, right, and center alignment.

Usage 1: Applies the properties of textFormat to all text in the text field.

Usage 2: Applies the properties of textFormat to the character at position index.

Usage 3: Applies the properties of the textFormat parameter to the span of text from the beginIndex parameter to the endIndex parameter.

Notice that any text inserted manually by the user, or replaced by means of TextField.replaceSel(), does not assume the formatting specified in a call to setTextFormat(). To set the default formatting for a TextField object, use TextField.setNewTextFormat().

Example

This example creates a new TextFormat object called myTextFormat and sets its bold property to true. It then calls setTextFormat() and applies the new text format to the my_txt text field.

myTextFormat = new TextFormat();
myTextFormat.bold = true;
my_txt.setTextFormat(myTextFormat);

See also

TextField.setNewTextFormat(), TextFormat class


TextField._soundbuftime

Availability

Flash Player 6.

Usage

my_txt._soundbuftime

Description

Property (global); an integer that specifies the number of seconds a sound prebuffers before it starts to stream.


TextField.StyleSheet class

Availability

Flash Player 7.

Description

The TextField.StyleSheet class lets you create a style sheet object that contains text formatting rules such as font size, color, and other formatting styles. You can then apply styles defined by a style sheet to a TextField object that contains HTML- or XML-formatted text. The text contained by the TextField object is then automatically formatted according to the tag styles defined by the style sheet object. You can use text styles to define new formatting tags, redefine built-in HTML tags, or create style classes that can be applied to certain HTML tags.

To apply styles to a TextField object, assign the style sheet object to a TextField object's styleSheet property.

For more information, see Formatting text with Cascading Style Sheets.

Method summary for the TextField.StyleSheet class

Method | Description
TextField.StyleSheet.getStyle() | Returns a copy of the style sheet object associated with a specified style name.
TextField.StyleSheet.getStyleNames() | Returns an array that contains the names of all of the styles registered in the style sheet object.
TextField.StyleSheet.load() | Begins loading a CSS file into the style sheet object.
TextField.StyleSheet.parseCSS() | Parses a string of CSS text and creates the specified style.
TextField.StyleSheet.setStyle() | Adds a new style to the style sheet object.

Event handler summary for the TextField.StyleSheet class

L
Method | Description
TextField.StyleSheet.onLoad | Callback handler invoked when a TextField.StyleSheet.load() operation has completed.

Constructor for the TextField.StyleSheet class

Availability

Flash Player 7.

Usage

new TextField.StyleSheet()

Returns

A reference to a TextField.StyleSheet object.

Description

Constructor; creates a TextField.StyleSheet object.


TextField.StyleSheet.getStyle()

Availability

Flash Player 7.

Usage

styleSheet.getStyle(styleName)

Parameters

styleName A string that specifies the name of the style to retrieve.

Returns

An object.

Description

Method; returns a copy of the style object associated with the style named styleName. If there is no style object associated with styleName, null is returned.

Example

Suppose a style sheet object named textStyles loads an external style sheet file named styles.css that contains a single style named heading, which defines font-family, font-size, and font-weight properties, as shown below.

// In styles.css
heading {
  font-family: Arial;
  font-size: 24px;
  font-weight: bold;
}

The following code loads the styles from the CSS file, and then displays each property name and its value in the Output panel.

var styleSheet = new TextField.styleSheet();
styleSheet.load("styles.css");
var sectionStyle = styleSheet.getStyle("heading");
for(property in sectionStyle) {
  var propName = property;
  var propValue = sectionStyle[property];
  trace(propName + " : " + propValue);
}

This would display the following in the Output panel:

fontfamily : Arial
fontsize : 24px
fontweight : bold

See also

TextField.StyleSheet.setStyle()


TextField.StyleSheet.getStyleNames()

Availability

Flash Player 7.

Usage

styleSheet.getStyleNames()

Parameters

None.

Returns

An array.

Description

Method; returns an array that contains the names (as strings) of all of the styles registered in this style sheet.

Example

This example creates a style sheet object named styleSheet that contains two styles, heading and bodyText. It then invokes the style sheet object's getStyleNames() method, assigns the results to the array names_array, and displays the contents of the array in the Output panel.

var styleSheet= new TextField.StyleSheet();
styleSheet.setStyle("heading", {
  fontsize: '24px'
});
styleSheet.setStyle("bodyText", {
  fontsize: '12px'
});
var names_array = styleSheet.getStyleNames();
trace(names.join("\n"));

The following is displayed in the Output panel:

bodyText
heading

See also

TextField.StyleSheet.getStyle()


TextField.StyleSheet.load()

Availability

Flash Player 7.

Usage

styleSheet.load(url)

Parameters

url The URL of a CSS file to load. The URL must be in the same domain as the URL where the SWF file currently resides.

Returns

Nothing.

Description

Method; starts loading the CSS file into styleSheet. The load operation is asynchronous; use the TextField.StyleSheet.onLoad callback handler to determine when the file has finished loading.

The CSS file must reside in exactly the same domain as the SWF file that is loading it. For more information about restrictions on loading data across domains, see Flash Player security features.

Example

The following example loads the CSS file named styles.css (not shown) into the style sheet object styleObj. When the file has finished loading successfully, the style sheet object is applied to a TextField object named news_txt.

var styleObj = new TextField.StyleSheet();
styleObj.load("styles.css");
styleObj.onLoad = function (success) {
  if(success) {
    news_txt.styleSheet = styleObj;
  }
}

See also

TextField.StyleSheet.onLoad


TextField.StyleSheet.onLoad

Availability

Flash Player 7.

Usage

styleSheet.onLoad = function (success) {}

Parameters

success A Boolean value indicating whether the CSS file was successfully loaded.

Returns

Nothing.

Description

Callback handler; invoked when a TextField.StyleSheet.load() operation has completed. If the style sheet loaded successfully, the success parameter is true. If the document was not received, or if an error occurred in receiving the response from the server, the success parameter is false.

Example

The following example loads the CSS file named styles.css (not shown) into the style sheet object styleObj. When the file has finished loading successfully, the style sheet object is applied to a TextField object named news_txt.

var styleObj = new TextField.StyleSheet();
styleObj.load("styles.css");
styleObj.onLoad = function (success) {
  if(success) {
    news_txt.styleSheet = styleObj;
  }
}

See also

TextField.StyleSheet.load()


TextField.StyleSheet.parseCSS()

Availability

Flash Player 7.

Usage

styleSheet.parseCSS(cssText)

Parameters

cssText The CSS text to parse (a string).

Returns

A Boolean value indicating if the text was parsed successfully (true) or not (false).

Description

Method; parses the CSS in cssText and loads the style sheet with it. If a style in cssText is already in styleSheet, the properties in styleSheet are retained, and only the ones in cssText are added or changed in styleSheet.

To extend the native CSS parsing capability, you can override this method by creating a subclass of the TextField.StyleSheet class. For more information, see Creating subclasses.


TextField.StyleSheet.setStyle()

Availability

Flash Player 7.

Usage

styleSheet.setStyle(name, style)

Parameters

name A string that specifies the name of the style to add to the style sheet.

style An object that describes the style, or null.

Returns

Nothing.

Description

Method; adds a new style with the specified name to the style sheet object. If the named style does not already exist in the style sheet, it is added. If the named style already exists in the style sheet, it is replaced. If the style parameter is null, the named style is removed.

Flash Player creates a copy of the style object that you pass to this method.

Example

The following code adds a style named emphasized to the style sheet myStyleSheet. The style includes two style properties: color and fontWeight. The style object is defined with the {} operator.

myStyleSheet.setStyle("emphasized", {color:'#000000',fontWeight:'bold'});

You could also create a style object using an instance of the Object class, and then pass that object as the style parameter, as the next example shows.

var styleObj = new Object();
styleObj.color = '#000000';
styleObj.fontWeight = 'bold';
myStyleSheet.setStyle("emphasized", styleObj);
delete styleObj;

Note: The last line of code (delete styleObj) deletes the original style object passed to setStyle() While not necessary, this step reduces memory usage, because Flash Player creates a copy of the style object you pass to setStyle().

See also

{} (object initializer)


TextField.styleSheet

Availability

Flash Player 7.

Usage

my_txt.styleSheet = TextField StyleSheet

Description

Property; attaches a style sheet to the text field specified by my_txt. For information on creating style sheets, see the TextField.StyleSheet class entry and Formatting text with Cascading Style Sheets.


TextField.tabEnabled

Availability

Flash Player 6.

Usage

my_txt.tabEnabled

Description

Property; specifies whether my_txt is included in automatic tab ordering. It is undefined by default.

If the tabEnabled property is undefined or true, the object is included in automatic tab ordering. If the tabIndex property is also set to a value, the object is included in custom tab ordering as well. If tabEnabled is false, the object is not included in automatic or custom tab ordering, even if the tabIndex property is set.

See also

Button.tabEnabled, MovieClip.tabEnabled


TextField.tabIndex

Availability

Flash Player 6.

Usage

my_txt.tabIndex

Parameters

None.

Returns

Nothing.

Description

Property; lets you customize the tab ordering of objects in a SWF file. You can set the tabIndex property on a button, movie clip, or text field instance; it is undefined by default.

If any currently displayed object in the SWF file contains a tabIndex property, automatic tab ordering is disabled, and the tab ordering is calculated from the tabIndex properties of objects in the SWF file. The custom tab ordering only includes objects that have tabIndex properties.

The tabIndex property must be a positive integer. The objects are ordered according to their tabIndex properties, in ascending order. An object with a tabIndex value of 1 precedes an object with a tabIndex value of 2. If two objects have the same tabIndex value, the one that precedes the other in the tab ordering is undefined.

The custom tab ordering defined by the tabIndex property is flat. This means that no attention is paid to the hierarchical relationships of objects in the SWF file. All objects in the SWF file with tabIndex properties are placed in the tab order, and the tab order is determined by the order of the tabIndex values. If two objects have the same tabIndex value, the one that goes first is undefined. You shouldn't use the same tabIndex value for multiple objects.

See also

Button.tabIndex, MovieClip.tabIndex


TextField._target

Availability

Flash Player 6.

Usage

my_txt._target

Description

Property (read-only); the target path of the text field instance specified by my_txt.


TextField.text

Availability

Flash Player 6.

Usage

my_txt.text

Description

Property; indicates the current text in the text field. Lines are separated by the carriage return character ('\r', ASCII 13). This property contains the normal, unformatted text in the text field, without HTML tags, even if the text field is HTML.

See also

TextField.htmlText


TextField.textColor

Availability

Flash Player 6.

Usage

my_txt.textColor

Description

Property; indicates the color of the text in a text field.


TextField.textHeight

Availability

Flash Player 6.

Usage

my_txt.textHeight

Description

Property; indicates the height of the text.


TextField.textWidth

Availability

Flash Player 6.

Usage

my_txt.textWidth

Description

Property; indicates the width of the text.


TextField.type

Availability

Flash Player 6.

Usage

my_txt.type

Description

Property; Specifies the type of text field. There are two values: "dynamic", which specifies a dynamic text field that cannot be edited by the user, and "input", which specifies an input text field.

Example

my_txt.type = "dynamic";


TextField._url

Availability

Flash Player 6.

Usage

my_txt._url

Description

Property (read only); retrieves the URL of the SWF file that created the text field.


TextField.variable

Availability

Flash Player 6.

Usage

my_txt.variable

Description

Property; The name of the variable that the text field is associated with. The type of this property is String.


TextField._visible

Availability

Flash Player 6.

Usage

my_txt._visible

Description

Property; a Boolean value that indicates whether the text field my_txt is visible. Text fields that are not visible (_visible property set to false) are disabled.

See also

Button._visible, MovieClip._visible


TextField._width

Availability

Flash Player 6.

Usage

my_txt._width

Description

Property; the width of the text field, in pixels.

Example

The following example sets the height and width properties of a text field:

my_txt._width=200;
my_txt._height=200;

See also

MovieClip._height


TextField.wordWrap

Availability

Flash Player 6.

Usage

my_txt.wordWrap

Description

Property; a Boolean value that indicates if the text field has word wrap. If the value of wordWrap is true, the text field has word wrap; if the value is false, the text field does not have word wrap.


TextField._x

Availability

Flash Player 6.

Usage

my_txt._x

Description

Property; an integer that sets the x coordinate of a text field relative to the local coordinates of the parent movie clip. If a text field is on the main Timeline, then its coordinate system refers to the upper left corner of the Stage as (0, 0). If the text field is inside a movie clip that has transformations, the text field is in the local coordinate system of the enclosing movie clip. Thus, for a movie clip rotated 90 degrees counterclockwise, the enclosed text field inherits a coordinate system that is rotated 90 degrees counterclockwise. The text field's coordinates refer to the registration point position.

See also

TextField._xscale, TextField._y, TextField._yscale


TextField._xmouse

Availability

Flash Player 6.

Usage

my_txt._xmouse

Description

Property (read-only); returns the x coordinate of the mouse position relative to the text field.

See also

TextField._ymouse


TextField._xscale

Availability

Flash Player 6.

Usage

my_txt._xscale

Description

Property; determines the horizontal scale of the text field as applied from the registration point of the text field, expressed as a percentage. The default registration point is (0,0).

See also

TextField._x, TextField._y, TextField._yscale


TextField._y

Availability

Flash Player 6.

Usage

my_txt._y

Description

Property; the y coordinate of a text field relative to the local coordinates of the parent movie clip. If a text field is in the main Timeline, then its coordinate system refers to the upper left corner of the Stage as (0, 0). If the text field is inside another movie clip that has transformations, the text field is in the local coordinate system of the enclosing movie clip. Thus, for a movie clip rotated 90 degrees counterclockwise, the enclosed text field inherits a coordinate system that is rotated 90 degrees counterclockwise. The text field's coordinates refer to the registration point position.

See also

TextField._x, TextField._xscale, TextField._yscale


TextField._ymouse

Availability

Flash Player 6.

Usage

my_txt._ymouse

Description

Property (read-only); indicates the y coordinate of the mouse position relative to the text field.

See also

TextField._xmouse


TextField._yscale

Availability

Flash Player 6.

Usage

my_txt._yscale

Description

Property; the vertical scale of the text field as applied from the registration point of the text field, expressed as a percentage. The default registration point is (0,0).

See also

TextField._x, TextField._xscale, TextField._y


TextFormat class

Availability

Flash Player 6.

Description

The TextFormat class represents character formatting information.

You must use the constructor new TextFormat() to create a TextFormat object before calling its methods.

You can set TextFormat parameters to null to indicate that they are undefined. When you apply a TextFormat object to a text field using TextField.setTextFormat(), only its defined properties are applied, as in the following example:

my_fmt = new TextFormat();
my_fmt.bold = true;
my_txt.setTextFormat(my_fmt);

This code first creates an empty TextFormat object with all of its properties undefined, then sets the bold property to a defined value.

The code my_txt.setTextFormat(my_fmt) only changes the bold property of the text field's default text format, because the bold property is the only one defined in my_fmt. All other aspects of the text field's default text format remain unchanged.

When TextField.getTextFormat() is invoked, a TextFormat object is returned with all of its properties defined; no property is null.

Method summary for the TextFormat class

Method | Description
TextFormat.getTextExtent() | Returns text measurement information for a text string.

Property summary for the TextFormat class

Property | Description
TextFormat.align | Indicates the alignment of a paragraph.
TextFormat.blockIndent | Indicates the block indentation, in points.
TextFormat.bold | Indicates whether text is boldface.
TextFormat.bullet | Indicates whether text is in a bulleted list.
TextFormat.color | Indicates the color of text.
TextFormat.font | Indicates the font name of the text with a text format.
TextFormat.indent | Indicates the indentation from the left margin to the first character in the paragraph.
TextFormat.italic | Indicates whether text is italicized.
TextFormat.leading | Indicates the amount of vertical space (called leading) between lines.
TextFormat.leftMargin | Indicates the left margin of the paragraph, in points.
TextFormat.rightMargin | Indicates the right margin of the paragraph, in points.
TextFormat.size | Indicates the point size of text.
TextFormat.tabStops | Specifies custom tab stops.
TextFormat.target | Indicates the window in a browser where a hyperlink is displayed.
TextFormat.underline | Indicates whether text is underlined.
TextFormat.url | Indicates the URL to which the text links.

Constructor for the TextFormat class

Availability

Flash Player 6.

Usage

new TextFormat([font, [size, [color, [bold, [italic, [underline, [url, [target, [align, [leftMargin, [rightMargin, [indent, [leading]]]]]]]]]]]]])

Parameters

font The name of a font for text as a string.

size An integer that indicates the point size.

color The color of text using this text format. A number containing three 8-bit RGB components; for example, 0xFF0000 is red, 0x00FF00 is green.

bold A Boolean value that indicates whether the text is boldface.

italic A Boolean value that indicates whether the text is italicized.

underline A Boolean value that indicates whether the text is underlined.

url The URL to which the text in this text format hyperlinks. If url is an empty string, the text does not have a hyperlink.

target The target window where the hyperlink is displayed. If the target window is an empty string, the text is displayed in the default target window _self. If the url parameter is set to an empty string or to the value null, you can get or set this property, but the property will have no effect.

align The alignment of the paragraph, represented as a string. If "left", the paragraph is left-aligned. If "center", the paragraph is centered. If "right", the paragraph is right-aligned.

leftMargin Indicates the left margin of the paragraph, in points.

rightMargin Indicates the right margin of the paragraph, in points.

indent An integer that indicates the indentation from the left margin to the first character in the paragraph.

leading A number that indicates the amount of leading vertical space between lines.

Returns

A reference to a TextFormat object.

Description

Constructor; creates a TextFormat object with the specified properties. You can then change the properties of the TextFormat object to change the formatting of text fields.

Any parameter may be set to null to indicate that it is not defined. All of the parameters are optional; any omitted parameters are treated as null.


TextFormat.align

Availability

Flash Player 6.

Usage

my_fmt.align

Description

Property; indicates the alignment of the paragraph, represented as a string. The alignment of the paragraph, represented as a string. If "left", the paragraph is left-aligned. If "center", the paragraph is centered. If "right", the paragraph is right-aligned. The default value is null which indicates that the property is undefined.


TextFormat.blockIndent

Availability

Flash Player 6.

Usage

my_fmt.blockIndent

Description

Property; a number that indicates the block indentation in points. Block indentation is applied to an entire block of text; that is, to all lines of the text. In contrast, normal indentation (TextFormat.indent) only affects the first line of each paragraph. If this property is null, the TextFormat object does not specify block indentation.


TextFormat.bold

Availability

Flash Player 6.

Usage

my_fmt.bold

Description

Property; a Boolean value that indicates if the text is boldface. The default value is null, which indicates that the property is undefined.


TextFormat.bullet

Availability

Flash Player 6.

Usage

my_fmt.bullet

Description

Property; a Boolean value that indicates that the text is part of a bulleted list. In a bulleted list, each paragraph of text is indented. To the left of the first line of each paragraph, a bullet symbol is displayed. The default value is null.


TextFormat.color

Availability

Flash Player 6.

Usage

my_fmt.color

Description

Property; indicates the color of text. A number containing three 8-bit RGB components; for example, 0xFF0000 is red, 0x00FF00 is green.


TextFormat.font

Availability

Flash Player 6.

Usage

my_fmt.font

Description

Property; the name of the font for text in this text format, as a string. The default value is null, which indicates that the property is undefined.


TextFormat.getTextExtent()

Availability

Flash Player 6. The optional width parameter is supported in Flash Player 7.

Usage

my_fmt.getTextExtent(text, [width])

Parameters

text A string.

width An optional number that represents the width, in pixels, at which the specified text should wrap.

Returns

An object with the properties width, height, ascent, descent, textFieldHeight, textFieldWidth.

Description

Method; returns text measurement information for the text string text in the format specified by my_fmt. The text string is treated as plain text (not HTML).

The method returns an object with six properties: ascent, descent, width, height, textFieldHeight, and textFieldWidth. All measurements are in pixels.

If a width parameter is specified, word wrapping is applied to the specified text. This lets you determine the height at which a text box shows all of the specified text.

The ascent and descent measurements provide, respectively, the distance above and below the baseline for a line of text. The baseline for the first line of text is positioned at the text field's origin plus its ascent measurement.

The width and height measurements provide the width and height of the text string. The textFieldHeight and textFieldWidth measurements provide the height and width required for a text field object to display the entire text string. Text fields have a 2-pixel-wide "gutter" around them, so the value of textFieldHeight is equal the value of height + 4; likewise, the value of textFieldWidth is always equal to the value of width + 4.

If you are creating a text field based on the text metrics, use textFieldHeight rather than height and textFieldWidth rather than width.

The following figure illustrates these measurements.

When setting up your TextFormat object, set all the attributes exactly as they will be set for the creation of the text field, including font name, font size, and leading. The default value for leading is 2.

Example

This example creates a single-line text field that's just big enough to display a text string using the specified formatting.

var text = "Small string";

// Create a TextFormat object,
// and apply its properties.
var txt_fmt = new TextFormat();
with(txt_fmt) {
  font = "Arial";
  bold = true;
}

// Obtain metrics information for the text string
// with the specified formatting.
var metrics = txt_fmt.getTextExtent(text);

// Create a text field just large enough to display the text.
this.createTextField ("textField", 0, 100, 100, metrics.textFieldWidth, metrics.textFieldHeight);
textField.border = true;
textField.wordWrap = true;
// Assign the same text string and
// TextFormat object to the TextField object.
textField.text = text;
textField.setTextFormat(txt_fmt);

The following example creates a multiline, 100-pixel-wide text field that's high enough to display a string with the specified formatting.

// Create a TextFormat object.
var txt_fmt:TextFormat= new TextFormat();

// Specify formatting properties for the TextFormat object:
txt_fmt.font = "Arial";
txt_fmt.bold = true;
txt_fmt.leading = 4;

// The string of text to be displayed
var textToDisplay:String = "Macromedia Flash 7, now with improved text metrics.";

// Obtain text measurement information for the string,
// wrapped at 100 pixels.
var metrics:Object = txt_fmt.getTextExtent(textToDisplay, 100);

// Create a new TextField object using the metric
// information just obtained.
this.createTextField ("textField", 0, 50, 50-metrics.ascent, 100, metrics.textFieldHeight)
textField.wordWrap = true;
textField.border = true;
// Assign the text and the TextFormat object to the TextObject:
textField.text = textToDisplay;
textField.setTextFormat(aformat);


TextFormat.indent

Availability

Flash Player 6.

Usage

my_fmt.indent

Description

Property; an integer that indicates the indentation from the left margin to the first character in the paragraph. The default value is null, which indicates that the property is undefined.

See also

TextFormat.blockIndent


TextFormat.italic

Availability

Flash Player 6.

Usage

my_fmt.italic

Description

Property; a Boolean value that indicates whether text in this text format is italicized. The default value is null, which indicates that the property is undefined.


TextFormat.leading

Availability

Flash Player 6.

Usage

my_fmt.leading

Description

Property; the amount of vertical space (called leading) between lines. The default value is null, which indicates that the property is undefined.


TextFormat.leftMargin

Availability

Flash Player 6.

Usage

my_fmt.leftMargin

Description

Property; the left margin of the paragraph, in points. The default value is null, which indicates that the property is undefined.


TextFormat.rightMargin

Availability

Flash Player 6.

Usage

my_fmt.rightMargin

Description

Property; the right margin of the paragraph, in points. The default value is null, which indicates that the property is undefined.


TextFormat.size

Availability

Flash Player 6.

Usage

my_fmt.size

Description

Property; the point size of text in this text format. The default value is null, which indicates that the property is undefined.


TextFormat.tabStops

Availability

Flash Player 6.

Usage

my_fmt.tabStops

Description

Property; specifies custom tab stops as an array of non-negative integers. Each tab stop is specified in points. If custom tab stops are not specified (null), the default tab stop is 4 (average character width).


TextFormat.target

Availability

Flash Player 6.

Usage

my_fmt.target

Description

Property; indicates the target window where the hyperlink is displayed. If the target window is an empty string, the text is displayed in the default target window _self. If the TextFormat.url property is an empty string or null, you can get or set this property, but the property will have no effect.


TextFormat.underline

Availability

Flash Player 6.

Usage

my_fmt.underline

Description

Property; a Boolean value that indicates whether the text that uses this text format is underlined (true) or not (false). This underlining is similar to that produced by the <U> tag, but the latter is not "true" underlining, because it does not skip descenders correctly. The default value is null, which indicates that the property is undefined.


TextFormat.url

Availability

Flash Player 6.

Usage

my_fmt.url

Description

Property; indicates the URL that text in this text format hyperlinks to. If the url property is an empty string, the text does not have a hyperlink. The default value is null, which indicates that the property is undefined.


TextSnapshot object

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Description

TextSnapshot objects let you work with static text in a movie clip. You can use them, for example, to lay out text with greater precision than that allowed by dynamic text, but still access the text in a read-only way.

You don't use a constructor to create a TextSnapshot object; it is returned by MovieClip.getTextSnapshot().

Method summary for the TextSnapshot object

Method | Description
TextSnapshot.findText() | Returns the position of the first occurrence of specified text.
TextSnapshot.getCount() | Returns the number of characters.
TextSnapshot.getSelected() | Specifies whether any of the text in the specified range has been selected by TextSnapshot.setSelected().
TextSnapshot.getSelectedText() | Returns a string that contains all the characters specified by TextSnapshot.setSelected().
TextSnapshot.getText() | Returns a string containing the characters in the specified range.
TextSnapshot.hitTestTextNearPos() | Lets you determine which character within the object is on or near specified coordinates.
TextSnapshot.setSelectColor() | Specifies the color to use when highlighting characters that have been selected with the TextSnapshot.setSelected() command.
TextSnapshot.setSelected() | Specifies a range of characters to be selected or deselected.


TextSnapshot.findText()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

my_snap.findText( startIndex, textToFind, caseSensitive )

Parameters

startIndex An integer specifying the starting point in my_snap to search for the specified text.

textToFind A string specifying the text to search for. If you specify a string literal instead of a variable of type String, enclose the string in quotation marks.

caseSensitive A Boolean value specifying whether the text in my_snap must match the case of the string in textToFind.

Returns

The zero-based index position of the first occurrence of the specified text, or -1.

Description

Method; searches the specified TextSnapshot object and returns the position of the first occurrence of textToFind found at or after startIndex. If textToFind is not found, the method returns -1.

Example

The following example illustrates how to use this method. To use this code, place a static text field containing the text "TextSnapshot Example" on the Stage.

function someMovieClipContainingStaticText() {
// the static text is inside the main clip
  return this;
}

var mc:MovieClip = someMovieClipContainingStaticText();
var ts:TextSnapshot = mc.getTextSnapshot();
var index1:Number = ts.findText(0, "Snap", true);
var index2:Number = ts.findText(0, "snap", true);
var index3:Number = ts.findText(0, "snap", false);
trace(index1);    // prints "4"
trace(index2);    // prints "-1"
trace(index3);    // prints "4"

See also

TextSnapshot.getText()


TextSnapshot.getCount()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

my_snap.getCount()

Parameters

None.

Returns

An integer representing the number of characters in the specified TextSnapshot object.

Description

Method; returns the number of characters in a TextSnapshot object.

Example

See TextSnapshot.getText().

See also

TextSnapshot.getText()


TextSnapshot.getSelected()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

my_snap.getSelected(from, to)

Parameters

from An integer that indicates the position of the first character of my_snap to be examined. Valid values for from are 0 through TextSnapshot.getCount() - 1. If from is a negative value, 0 is used.

to An integer that is 1+ the index of the last character in my_snap to be examined. Valid values for to are 0 through TextSnapshot.getCount(). The character indexed by the to parameter is not included in the extracted string. If this parameter is omitted, TextSnapshot.getCount() is used. If this value is less than or equal to the value of from, from+1 is used.

Returns

A Boolean value of true, if at least one character in the given range has been selected by the corresponding TextSnapshot.setSelected() command, false otherwise.

Description

Method; returns a Boolean value that specifies whether a TextSnapshot object contains selected text in the specified range.

To search all characters, pass a value of 0 for from and TextSnapshot.getCount() (or any very large number) for to. To search a single character, pass a value of from+1 for to.

Example

See TextSnapshot.setSelected().

See also

TextSnapshot.getSelectedText(), TextSnapshot.getText()


TextSnapshot.getSelectedText()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

mySnapshot.getSelectedText( [ includeLineEndings ] )

Parameters

includeLineEndings An optional Boolean value that specifies whether newline characters are inserted into the returned string where appropriate. The default value is false.

Returns

A string that contains all the characters specified by the corresponding TextSnapshot.setSelected() command.

Description

Method; returns a string that contains all the characters specified by the corresponding TextSnapshot.setSelected() command. If no characters are selected, an empty string is returned.

If you pass a value of true for includeLineEndings, newline characters are inserted in the string returned where deemed appropriate. In this case, the return string might be longer than the input range. If includeLineEndings is false or omitted, the selected text is returned without any characters added.

Example

See TextSnapshot.setSelected().

See also

TextSnapshot.getSelected()


TextSnapshot.getText()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

mySnapshot.getText(from, to [, includeLineEndings ] )

Parameters

from An integer that indicates the position of the first character of my_snap to be included in the returned string. Valid values for from are 0 through TextSnapshot.getCount() - 1. If from is a negative value, 0 is used.

to An integer that is 1+ the index of the last character in my_snap to be examined. Valid values for to are 0 through TextSnapshot.getCount(). The character indexed by the to parameter is not included in the extracted string. If this parameter is omitted, TextSnapshot.getCount() is used. If this value is less than or equal to the value of from, from+1 is used.

includeLineEndings An optional Boolean value that specifies whether newline characters are inserted into the returned string where appropriate. The default value is false.

Returns

A string containing the characters in the specified range, or an empty string if no characters are found in the specified range.

Description

Method; returns a string that contains all the characters specified by the from and to parameters. If no characters are selected, an empty string is returned.

To return all characters, pass a value of 0 for from and TextSnapshot.getCount() (or any very large number) for to. To return a single character, pass a value of from+1 for to.

If you pass a value of true for includeLineEndings, newline characters are inserted in the string returned where deemed appropriate. In this case, the return string might be longer than the input range. If includeLineEndings is false or omitted, the selected text is returned without any characters added.

Example

The following example illustrates how to use this method. To use this code, place a static text field containing the text "TextSnapshot Example" on the Stage.

function someMovieClipContainingStaticText() {
// the static text is inside the main clip
  return this;
}
var mc:MovieClip = someMovieClipContainingStaticText();
var ts:TextSnapshot = mc.getTextSnapshot();
var count:Number = ts.getCount();
var theText:String = ts.getText(0, count, false);
trace(count);      // prints "20"
trace(theText);      // prints "TextSnapshot Example"

See also

TextSnapshot.getSelectedText()


TextSnapshot.hitTestTextNearPos()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

my_snap.hitTestTextNearPos(x, y [, maxDistance] )

Parameters

x A number that represents the x coordinate of the movie clip containing the text in my_snap.

y A number that represents the x coordinate of the movie clip containing the text in my_snap.

maxDistance An optional number that represents the maximum distance from x, y that can be searched for text. The distance is measured from the centerpoint of each character. The default value is 0.

Returns

An integer representing the index value of the character in my_snap that is nearest to the specified x, y coordinate. Returns -1 if no character is found, or if the font doesn't contain character metric information (see "Description").

Description

Method; lets you determine which character within a TextSnapshot object is on or near specified x, y coordinates of the movie clip containing the text in my_snap.

If you omit or pass a value of 0 for maxDistance, the location specified by the x, y coordinates must lie inside the bounding box of my_snap.

This method functions correctly only for fonts that include character metric information and, by default, Flash does not include this information for static text fields. In some cases, this behavior means that the method will return -1 instead of an index value. To ensure that an index value is returned, you can force the Flash authoring tool to include the character metric information for a font. To do this, add a dynamic text field that uses that font, choose "Character Options" for that dynamic text field, and then specify that font outlines should be embedded for at least one character. It doesn't matter which character(s) you specify, nor even if they are the characters used in the static text fields in question.

Example

The following example illustrates how to use this method. To use this code, place a static text field containing the text "TextSnapshot Example" on the Stage. To test the code, move the cursor over the static text field.

Note: If characters don't appear to be selected when you run the code, you also have to place a dynamic text field on the Stage. See "Description," above.

function someMovieClipContainingStaticText() {
// the static text is inside the main clip
  return this;
}
var mc:MovieClip = someMovieClipContainingStaticText();
mc.ts = mc.getTextSnapshot();
mc.onMouseMove = function() {
  // find which character the mouse is over (if any)
  var hitIndex:Number = ts.hitTestTextNearPos(this._xmouse, this._ymouse, 0);
  // deselect everything
  ts.setSelected(0, ts.getCount(), false);
  if (hitIndex >= 0) {
    // select the single character the mouse is over
    ts.setSelected(hitIndex, hitIndex+1, true);
  }
}

See also

MovieClip.getTextSnapshot(), MovieClip._x, MovieClip._y


TextSnapshot.setSelectColor()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

mySnapshot.setSelectColor(hexColor);

Parameters

hexColor The color used for the border placed around characters that have been selected by the corresponding TextSnapshot.setSelected() command, expressed in 0xRRGGBB format.

Returns

Nothing.

Description

Method; specifies the color to use when highlighting characters that have been selected with the TextSnapshot.setSelected() command. The color is always opaque; you can't specify a transparency value.

Example

See TextSnapshot.setSelected().


TextSnapshot.setSelected()

Availability

Authoring: Flash MX 2004.

Playback: SWF files published for Flash Player 6 or later, playing in Flash Player 7 or later.

Usage

mySnapshot.setSelected(from, to, select)

Parameters

from An integer that indicates the position of the first character of my_snap to select. Valid values for from are 0 through TextSnapshot.getCount() - 1. If from is a negative value, 0 is used.

to An integer that is 1+ the index of the last character in my_snap to be examined. Valid values for to are 0 through TextSnapshot.getCount(). The character indexed by the to parameter is not included in the extracted string. If this parameter is omitted, TextSnapshot.getCount() is used. If this value is less than or equal to the value of from, from+1 is used.

select A Boolean value that specifies whether the text should be selected (true) or deselected (false).

Returns

Nothing.

Description

Method; specifies a range of characters in a TextSnapshot object to be selected or deselected. Characters that are selected are drawn with a colored rectangle behind them, matching the bounding box of the character. The color of the bounding box is defined by TextSnapshot.setSelectColor().

To select or deselect all characters, pass a value of 0 for from and TextSnapshot.getCount() (or any very large number) for to. To specify a single character, pass a value of from+1 for to.

Because characters are individually marked as selected, you can issue this command multiple times to select multiple characters; that is, using this command does not deselect other characters that have been set by this command.

The colored rectangle that indicates a selection is displayed only for fonts that include character metric information and, by default, Flash does not include this information for static text fields. In some cases, this behavior means that text that is selected won't appear to be selected onscreen. To ensure that all selected text appears to be selected, you can force the Flash authoring tool to include the character metric information for a font. To do this, add a dynamic text field that uses that font, choose Character Options for that dynamic text field, and then specify that font outlines should be embedded for at least one character. It doesn't matter which characters you specify, nor even if they are the characters used in the static text fields in question.

Example

The following example illustrates how to use this method. To use this code, place a static text field containing the text "TextSnapshot Example" on the Stage.

Note: If characters don't appear to be selected when you run the code, you also must place a dynamic text field on the Stage. See "Description" above.

function someMovieClipContainingStaticText() {
// the static text is inside the main clip
  return this;
}

// this example assumes that the movie clip contains
// the static text "TextSnapshot Example"
var mc:MovieClip = someMovieClipContainingStaticText();
var ts:TextSnapshot = mc.getTextSnapshot();
var count:Number = ts.getCount();
ts.setSelectColor(0xFF0000);      // set the selection color to red
ts.setSelected(0, 4, true);      // select the first four characters
ts.setSelected(1, 2, false);      // deselect the second character (leaving the rest selected)
var firstCharIsSelected:Boolean = ts.getSelected(0, 1);
var secondCharIsSelected:Boolean = ts.getSelected(1, 2);
var theText:String = ts.getSelectedText(false);  // get the selected text
trace(theText);          // prints "Txt"
trace(firstCharIsSelected);      // prints "true"
trace(secondCharIsSelected);      // prints "false"


this

Availability

Flash Player 5.

Usage

this

Description

Identifier; references an object or movie clip instance. When a script executes, this references the movie clip instance that contains the script. When a method is called, this contains a reference to the object that contains the called method.

Inside an on event handler action attached to a button, this refers to the Timeline that contains the button. Inside an onClipEvent() event handler action attached to a movie clip, this refers to the Timeline of the movie clip itself.

Because this is evaluated in the context of the script that contains it, you can't use this in a script to refer to a variable defined in a class file:

// in file applyThis.as
class applyThis{
  var str:String = "Defined in applyThis.as";
  function conctStr(x:String):String{
    return x+x;
  }

  function addStr():String{
    return str;
  }
}

// Use following code in FLA to test movie
import applyThis;

var obj:applyThis = new applyThis();
var abj:applyThis = new applyThis();
abj.str = "defined in FLA";

trace(obj.addStr.call(abj,null));    // defined in FLA
trace(obj.addStr.call(this,null));   // undefined
trace(obj.addStr.call(obj,null));    // Defined in applyThis.as

Similarly, to call a function defined in a dynamic class, you must use this to scope the function:

// incorrect version of simple.as
dynamic class simple{
  function callfunc(){
    trace(func());
  }

}

// correct version of simple.as
dynamic class simple{
  function callfunc(){
    trace(this.func());
  }
}
// statements in FLA file
import simple;
var obj:simple = new simple();
obj.num = 0;
obj.func = function():Boolean{
  return true;
}
obj.callfunc(); // syntax error with incorrect version of simple.as

Example

In the following example, the keyword this references the Circle object.

function Circle(radius) {
  this.radius = radius;
  this.area = Math.PI * radius * radius;
}

In the following statement assigned to a frame, the keyword this references the current movie clip.

// sets the alpha property of the current movie clip to 20
this._alpha = 20;

In the following statement inside an onClipEvent() handler, the keyword this references the current movie clip.

// when the movie clip loads, a startDrag() operation
// is initiated for the current movie clip.

onClipEvent (load) {
  startDrag (this, true);
}

See also

on(), onClipEvent()


throw

Availability

Flash Player 7.

Usage

throw expression

Description

Statement; generates ("throws") an error that can be handled ("caught") by a catch{} or finally{} code block. If an exception is not caught by a catch or finally block, the string representation of the thrown value is sent to the Output panel.

Typically, you throw instances of the Error class or its subclasses (see the following examples).

Parameters

expression An ActionScript expression or object.

Example

In this example, a function named checkEmail() checks whether the string that is passed to it is a properly formatted e-mail address. If the string does not contain an @ symbol, the function throws an error.

function checkEmail(email:String) {
  if (email.indexOf("@") == -1) {
    throw new Error("Invalid email address");
  }
}

The following code then calls the checkEmail() function within a try code block, passing the text in a text field (email_txt) as a parameter. If the string parameter does not contain a valid e-mail address, the error message is displayed in a text field (error_txt).

try {
  checkEmail("Joe Smith");
} catch (e) {
  error_txt.text = e.toString();
}

In this example, a subclass of the Error class is thrown. The checkEmail() function is modified to throw an instance of that subclass. (For more information, see Creating subclasses.)

// Define Error subclass InvalidEmailError
// In InvalidEmailError.as:
class InvalidEmailAddress extends Error {
  var message = "Invalid email address.";
}
function checkEmail(email:String) {
  if (email.indexOf("@") == -1) {
    throw new InvalidEmailAddress();
  }
}

See also

Error class, try..catch..finally


toggleHighQuality()

Availability

Flash 2; deprecated in favor of _quality.

Usage

toggleHighQuality()

Parameters

None.

Returns

Nothing.

Description

Deprecated function; turns anti-aliasing on and off in Flash Player. Anti-aliasing smooths the edges of objects and slows down SWF playback. This action affects all SWF files in Flash Player.

Example

The following code could be applied to a button that, when clicked, would toggle anti-aliasing on and off:

on(release) {
  toggleHighQuality();
}

See also

_highquality, _quality


trace()

Availability

Flash Player 4.

Usage

trace(expression)

Parameters

expression An expression to evaluate. When a SWF file is opened in the Flash authoring tool (via the Test Movie command), the value of the expression parameter is displayed in the Output panel.

Returns

Nothing.

Description

Statement; evaluates the expression and displays the result in the Output panel in test mode.

Use this action to record programming notes or to display messages in the Output panel while testing a movie. Use the expression parameter to check if a condition exists, or to display values in the Output panel. The trace() action is similar to the alert function in JavaScript.

You can use the Omit Trace Actions command in Publish Settings to remove trace() actions from the exported SWF file.

Example

This example is from a game in which a draggable movie clip instance named my_mc must be released on a specific target. A conditional statement evaluates the _droptarget property and executes different actions depending on where my_mc is released. The trace() action is used at the end of the script to evaluate the location of the my_mc movie clip and to display the result in the Output panel. If my_mc doesn't behave as expected (for example, if it snaps to the wrong target), the values sent to the Output panel by the trace() action will help you determine the problem in the script.

on(press) {
  my_mc.startDrag();
}

on(release) {
  if(eval(_droptarget) != target) {
      my_mc._x = my_mc_xValue;
      my_mc._y = my_mc_yValue;
  } else {
    var my_mc_xValue = my_mc._x;
    var my_mc_yValue = my_mc._y;
    target = "_root.pasture";
  }
  trace("my_mc_xValue = " + my_mc_xValue);
  trace("my_mc_xValue = " + my_mc_xValue);
  stopDrag();
}


true

Availability

Flash Player 5.

Usage

true

Description

Constant; a unique Boolean value that represents the opposite of false.

See also

false


try..catch..finally

Availability

Flash Player 7.

Usage

try {
  // ... try block ...
} finally {
  // ... finally block ...
}
try {
  // ... try block ...
} catch(error[:ErrorType1]) {
  // ... catch block ...
} [catch(error[:ErrorTypeN]) {
  // ... catch block ...
}] [finally {
  // ... finally block ...
}]

Parameters

error The expression thrown from a throw statement, typically an instance of the Error class or a subclass thereof.

ErrorType An optional type specifier for the error identifier. The catch clause only catches errors of the specified type.

Description

Keywords; enclose a block of code in which an error can occur, and then respond to the error. If any code within the try code block throws an error (using the throw action), control passes to the catch block, if one exists, then to the finally code block, if one exists. The finally block always executes, regardless of whether an error was thrown. If code within the try block doesn't throw an error (that is, if the try block completes normally), then the code in the finally block is still executed. The finally block executes even if the try block exits using a return statement.

A try block must be followed by a catch block, a finally block, or both. A single try block can have multiple catch blocks but only one finally block. You can nest try blocks as many levels deep as desired.

The error parameter specified in a catch handler must be a simple identifier such as e or theException or x. The variable in a catch handler can also be typed. When used with multiple catch blocks, typed errors let you catch multiple types of errors thrown from a single try block.

If the exception thrown is an object, the type will match if the thrown object is a subclass of the specified type. If an error of a specific type is thrown, the catch block that handles the corresponding error is executed. If an exception that is not of the specified type is thrown, the catch block does not execute and the exception is automatically thrown out of the try block to a catch handler that matches it.

If an error is thrown within a function, and the function does not include a catch handler, then the ActionScript interpreter exits that function, as well as any caller functions, until a catch block is found. During this process, finally handlers are called at all levels.

Example

The following example shows how to create a try..finally statement. Because code in the finally block is guaranteed to execute, it is typically used to perform any necessary "clean-up" code after a try block executes. In this example, the finally block is used to delete an ActionScript object, regardless of whether an error occurred.

var account = new Account()
try {
  var returnVal = account.getAccountInfo();
  if(returnVal != 0) {
    throw new Error("Error getting account information.");
  }
}
finally {
  // Delete the 'account' object no matter what.
  if(account != null) {
    delete account;
  }
}

The following example demonstrates a try..catch statement. The code within the try block is executed. If an exception is thrown by any code within the try block, control passes to the catch block, which displays the error message in a text field using the Error.toString() method.

var account = new Account()
try {
  var returnVal = account.getAccountInfo();
  if(returnVal != 0) {
    throw new Error("Error getting account information.");
  }
} catch (e) {
  status_txt.text = e.toString();
}

The following example shows a try code block with multiple, typed catch code blocks. Depending on the type of error that occurred, the try code block throws a different type of object. In this case, myRecordSet is an instance of a (hypothetical) class named RecordSet whose sortRows() method can throw two different types of errors: RecordSetException and MalformedRecord.

In this example, the RecordSetException and MalformedRecord objects are subclasses of the Error class. Each is defined in its own AS class file. (For more information, see Creating Classes with ActionScript 2.0.)

// In RecordSetException.as:
class RecordSetException extends Error {
  var message = "Record set exception occurred."
}
// In MalformedRecord.as:
class MalformedRecord extends Error {
  var message = "Malformed record exception occurred.";
}

Within the RecordSet class's sortRows() method, one of these previously defined error objects are thrown depending on the type of exception that occurred. The following code snippet shows how this code might look.

// Within RecordSet.as class file...
function sortRows() {
  ...
  if(recordSetErrorCondition) {
    throw new RecordSetException();
  }
  if(malFormedRecordCondition) {
    throw new MalformedRecord();
  }
  ...
}

Finally, in another AS file or FLA script, the following code invokes the sortRows() method on an instance of the RecordSet class. It defines catch blocks for each type of error that is thrown by sortRows().

try {
  myRecordSet.sortRows();
} catch (e:RecordSetException) {
  trace("Caught a recordset exception");
} catch (e:MalformedRecord) {
  trace("Caught a malformed record exception");
}

See also

Error class, throw, class, extends


typeof

Availability

Flash Player 5.

Usage

typeof(expression)

Parameters

expression A string, movie clip, button, object, or function.

Description

Operator; a unary operator placed before a single parameter. The typeof operator causes the Flash interpreter to evaluate expression; the result is a string specifying whether the expression is a string, movie clip, object, function, number, or Boolean value. The following table shows the results of the typeof operator on each type of expression.

Parameter | Output
String | string
Movie clip | movieclip
Button | object
Text field | object
Number | number
Boolean | boolean
Object | object
Function | function


undefined

Availability

Flash Player 5.

Usage

undefined

Parameters

None.

Returns

Nothing.

Description

A special value, usually used to indicate that a variable has not yet been assigned a value. A reference to an undefined value returns the special value undefined. The ActionScript code typeof(undefined) returns the string "undefined". The only value of type undefined is undefined.

In files published for Flash Player 6 or earlier, the value of undefined.toString() is "" (an empty string). In files published for Flash Player 7 or later, the value of undefined.toString() is undefined.

The value undefined is similar to the special value null. When null and undefined are compared with the equality operator, they compare as equal.

Example

In this example, the variable x has not been declared and therefore has the value undefined. In the first section of code, the equality operator (==) compares the value of x to the value undefined and the appropriate result is sent to the Output panel. In the second section of code, the equality operator compares the values null and undefined.

// x has not been declared
trace ("The value of x is " + x);
if (x == undefined) {
  trace ("x is undefined");
} else {
  trace ("x is not undefined");
}

trace ("typeof (x) is " + typeof (x));
if (null == undefined) {
  trace ("null and undefined are equal");
} else {
  trace ("null and undefined are not equal");
}

The following result is displayed in the Output panel.

The value of x is undefined
x is undefined
typeof (x) is undefined
null and undefined are equal


unescape

Availability

Flash Player 5.

Usage

unescape(x)

Parameters

x A string with hexadecimal sequences to escape.

Returns

A string decoded from a URL-encoded parameter.

Description

Function; evaluates the parameter x as a string, decodes the string from URL-encoded format (converting all hexadecimal sequences to ASCII characters), and returns the string.

Example

The following example illustrates the escape-to-unescape conversion process.

escape("Hello{[World]}");

The escaped result is as follows:

("Hello%7B%5BWorld%5D%7D');

Use unescape to return to the original format:

unescape("Hello%7B%5BWorld%5D%7D");

The result is as follows:

Hello{[World]}


unloadMovie()

Availability

Flash Player 3.

Usage

unloadMovie(target)

Parameters

target The target path of a movie clip.

Returns

None.

Description

Function; removes a movie clip that was loaded by means of loadMovie() from Flash Player. To unload a movie that was loaded by means of loadMovieNum(), use unloadMovieNum() instead of unloadMovie().

Example

The following example unloads the movie clip draggable_mc on the main Timeline, and loads movie.swf into level 4.

on (press) {
    unloadMovie ("_root.draggable_mc");
    loadMovieNum ("movie.swf", 4);
}

The following example unloads the movie loaded into level 4.

on (press) {
    unloadMovieNum (4);
}

See also

loadMovie(), MovieClipLoader.unloadClip()


unloadMovieNum()

Availability

Flash Player 3.

Usage

unloadMovieNum(level)

Parameters

level The level (_levelN) of a loaded movie.

Returns

Nothing.

Description

Function; removes a movie that was loaded by means of loadMovieNum() from Flash Player. To unload a movie that was loaded by means of loadMovie(), use unloadMovie() instead of unloadMovieNum().

See also

loadMovie(), loadMovieNum(), unloadMovie()


updateAfterEvent()

Availability

Flash Player 5.

Usage

updateAfterEvent()

Parameters

None.

Returns

Nothing.

Description

Function; updates the display (independent of the frames per second set for the movie) when you call it within an onClipEvent() handler or as part of a function or method that you pass to setInterval(). Flash ignores calls to updateAfterEvent that are not within an onClipEvent() handler or part of a function or method passed to setInterval().

See also

onClipEvent(), setInterval()


var

Availability

Flash Player 5.

Usage

var variableName [= value1] [...,variableNameN [=valueN]]

Parameters

variableName An identifier.

value The value assigned to the variable.

Returns

Nothing.

Description

Statement; used to declare local or Timeline variables.

  • If you declare variables inside a function, the variables are local. They are defined for the function and expire at the end of the function call.
  • If variables are not declared inside a block ({}) but the action list was executed with a call() action, the variables are local and expire at the end of the current list.
  • If variables are not declared inside a block and the current action list was not executed with the call() action, the variables are interpreted as Timeline variables. However, you don't have to use var to declare Timeline variables.

You cannot declare a variable scoped to another object as a local variable:

my_array.length = 25;     // ok
var my_array.length = 25; // syntax error

When you use var, you can strictly type the variable; see Strict data typing

Note: Classes defined in external scripts also support public, private, and static variable scopes. See Creating Classes with ActionScript 2.0 and private, public, and static.


Video class

Availability

Flash Player 6; the ability to play Flash Video (FLV) files was added in Flash Player 7.

Description

The Video class lets you display live streaming video on the Stage without embedding it in your SWF file. You capture the video by using Camera.get(). In files published for Flash Player 7 and later, you can also use the Video class to play back Flash Video (FLV) files over HTTP or from the local file system. For more information, see Playing back external FLV files dynamically and the NetConnection class and NetStream class entries.

A Video object can be used like a movie clip. As with other objects you place on the stage, you can control various properties of Video objects. For example, you can move the Video object around on the stage by using its _x and _y properties; you can change its size using its _height and _width properties, and so on.

To display the video stream, first place a Video object on the Stage. Then use Video.attachVideo() to attach the video stream to the Video object.

To place a Video object on the Stage:

  1. If the Library panel isn't visible, select Window > Library to display it.
  2. Add an embedded Video object to the library by clicking the Options menu on the right side of the Library panel title bar and selecting New Video.
  3. Drag the Video object to the Stage and use the Property inspector to give it a unique instance name, such as my_video. (Do not name it Video.)

Method summary for the Video class

Method | Description
Video.attachVideo() | Specifies a video stream to be displayed within the boundaries of the Video object on the Stage.
Video.clear() | Clears the image currently displayed in the Video object.

Property summary for the Video class

Property | Description
Video.deblocking | Specifies the behavior for the deblocking filter that the video compressor applies as needed when streaming the video.
Video.height | Read-only; the height of the video stream, in pixels.
Video.smoothing | Specifies whether the video should be smoothed (interpolated) when it is scaled.
Video.width | Read-only; the width of the video stream, in pixels.


Video.attachVideo()

Availability

Flash Player 6; the ability to work with Flash Video (FLV) files was added in Flash Player 7.

Usage

my_video.attachVideo(source)

Parameters

source A Camera object that is capturing video data or a NetStream object. To drop the connection to the Video object, pass null for source.

Returns

Nothing.

Description

Method; specifies a video stream (source) to be displayed within the boundaries of the Video object on the Stage. The video stream is either an FLV file being displayed by means of the NetStream.play() command, a Camera object, or null. If source is null, video is no longer played within the Video object.

You don't have to use this method if the FLV file contains only audio; the audio portion of an FLV files is played automatically when the NetStream.play() command is issued.

If you want to control the audio associated with an FLV file, you can use MovieClip.attachAudio() to route the audio to a movie clip; you can then create a Sound object to control some aspects of the audio. For more information, see MovieClip.attachAudio().

Example

The following example plays live video locally.

active_cam = Camera.get();
my_video.attachVideo(active_cam); // my_video is a Video object on the Stage

The following example plays a previously recorded file named myVideo.flv that is stored in the same directory as the SWF file.

var nc:NetConnection = new NetConnection();
nc.connect(null);
var ns:NetStream = new NetStream(my_nc);
my_video.attachVideo(ns); // my_video is a Video object on the Stage
ns.play("myVideo.flv");

See also

Camera class, NetStream class


Video.clear()

Availability

Flash Player 6.

Usage

my_video.clear()

Parameters

None.

Returns

Nothing.

Description

Method; clears the image currently displayed in the Video object. This is useful when, for example, you want to display standby information without having to hide the Video object.

See also

Video.attachVideo()


Video.deblocking

Availability

Flash Player 6.

Usage

my_video.deblocking

Description

Property; a number that specifies the behavior for the deblocking filter that the video compressor applies as needed when streaming the video. The following are acceptable values:

  • 0 (the default): Let the video compressor apply the deblocking filter as needed.
  • 1: Never use the deblocking filter.
  • 2: Always use the deblocking filter.

The deblocking filter has an effect on overall playback performance, and it is usually not necessary for high-bandwidth video. If your system is not powerful enough, you might experience difficulties playing back video with this filter enabled.


Video.height

Availability

Flash Player 6.

Usage

my_video.height

Description

Read-only property; an integer specifying the height of the video stream, in pixels. For live streams, this value is the same as the Camera.height property of the Camera object that is capturing the video stream. For FLV files, this value is the height of the file that was exported as FLV.

You may want to use this property, for example, to ensure that the user is seeing the video at the same size at which it was captured, regardless of the actual size of the Video object on the Stage.

Example

Usage 1: The following example sets the height and width values of the Video object to match the values of an FLV file. You should call this code after NetStream.onStatus is invoked with a code property of NetStream.Buffer.Full. If you call it when the code property is NetStream.Play.Start, the height and width values will be 0, because the Video object doesn't yet have the height and width of the loaded FLV file.

// Clip is the instance name of the movie clip
// that contains the video object "my_video".
_root.Clip._width = _root.Clip.my_video.width;
_root.Clip._height = _root.Clip.my_video.height;

Usage 2: The following example lets the user press a button to set the height and width of a video stream being displayed in the Flash Player to be the same as the height and width at which the video stream was captured.

on (release) {
  _root.my_video._width = _root.my_video.width
  _root.my_video._height = _root.my_video.height
}

See also

MovieClip._height, Video.width


Video.smoothing

Availability

Flash Player 6.

Usage

my_video.smoothing

Description

Property; a Boolean value that specifies whether the video should be smoothed (interpolated) when it is scaled. For smoothing to work, the player must be in high-quality mode. The default value is false (no smoothing).


Video.width

Availability

Flash Player 6.

Usage

my_video.width

Description

Read-only property; an integer specifying the width of the video stream, in pixels. For live streams, this value is the same as the Camera.width property of the Camera object that is capturing the video stream. For FLV files, this value is the width of the file that was exported as an FLV file.

You may want to use this property, for example, to ensure that the user is seeing the video at the same size at which it was captured, regardless of the actual size of the Video object on the Stage.

Example

See the examples for Video.height.


void

Availability

Flash Player 5.

Usage

void (expression)

Description

Operator; a unary operator that discards the expression value and returns an undefined value. The void operator is often used in comparisons using the == operator to test for undefined values.


while

Availability

Flash Player 4.

Usage

while(condition) {
  statement(s);
}

Parameters

condition The expression that is reevaluated each time the while action is executed.

statement(s) The instructions to execute while the condition evaluates to true.

Returns

Nothing.

Description

Statement; tests an expression and runs a statement or series of statements repeatedly in a loop as long as the expression is true.

Before the statement block is run, the condition is tested; if the test returns true, the statement block is run. If the condition is false, the statement block is skipped and the first statement after the while action's statement block is executed.

Looping is commonly used to perform an action while a counter variable is less than a specified value. At the end of each loop, the counter is incremented until the specified value is reached. At that point, the condition is no longer true, and the loop ends.

The while statement performs the following series of steps. Each repetition of steps 1-4 is called an iteration of the loop. The condition is retested at the beginning of each iteration, as in the following steps:

  1. The expression condition is evaluated.
  2. If condition evaluates to true or a value that converts to the Boolean value true, such as a nonzero number, go to step 3.

    Otherwise, the while statement is completed and execution resumes at the next statement after the while loop.

  3. Run the statement block statement(s).
  4. Go to step 1.

See also

do while, continue, for, for..in


with

Availability

Flash Player 5.

Usage

with (object) {
  statement(s);
}

Parameters

object An instance of an ActionScript object or movie clip.

statement(s) An action or group of actions enclosed in curly braces.

Returns

Nothing.

Description

Statement; lets you specify an object (such as a movie clip) with the object parameter and evaluate expressions and actions inside that object with the statement(s) parameter. This prevents you from having to repeatedly write the object's name or the path to the object.

The object parameter becomes the context in which the properties, variables, and functions in the statement(s) parameter are read. For example, if object is my_array, and two of the properties specified are length and concat, those properties are automatically read as my_array.length and my_array.concat. In another example, if object is state.california, any actions or statements inside the with action are called from inside the california instance.

To find the value of an identifier in the statement(s) parameter, ActionScript starts at the beginning of the scope chain specified by the object and searches for the identifier at each level of the scope chain, in a specific order.

The scope chain used by the with action to resolve identifiers starts with the first item in the following list and continues to the last item:

  • The object specified in the object parameter in the innermost with action.
  • The object specified in the object parameter in the outermost with action.
  • The Activation object. (A temporary object that is automatically created when a function is called that holds the local variables called in the function.)
  • The movie clip containing the currently executing script.
  • The Global object (built-in objects such as Math and String).

To set a variable inside a with action, the variable must have been declared outside the with action or you must enter the full path to the Timeline on which you want the variable to live. If you set a variable in a with action without declaring it, the with action will look for the value according to the scope chain. If the variable doesn't already exist, the new value will be set on the Timeline from which the with action was called.

In Flash 5 or later, the with action replaces the deprecated tellTarget action. You are encouraged to use with instead of tellTarget because it is a standard ActionScript extension to the ECMA-262 standard. The principal difference between the with and tellTarget actions is that with takes a reference to a movie clip or other object as its parameter, while tellTarget takes a target path string that identifies a movie clip as its parameter, and cannot be used to target objects.

Example

The following example sets the _x and _y properties of the someOther_mc instance, and then instructs someOther_mc to go to Frame 3 and stop.

with (someOther_mc) {
  _x = 50;
  _y = 100;
  gotoAndStop(3);
}

The following code snippet shows how to write the preceding code without using a with action.

someOther_mc._x = 50;
someOther_mc._y = 100;
someOther_mc.gotoAndStop(3);

You could also write this code using the tellTarget action. However, if someOther_mc were not a movie clip, but an object, you could not use the with action.

tellTarget ("someOther_mc") {
  _x = 50;
  _y = 100;
  gotoAndStop(3);
}

The with action is useful for accessing multiple items in a scope chain list simultaneously. In the following example, the built-in Math object is placed at the front of the scope chain. Setting Math as a default object resolves the identifiers cos, sin, and PI to Math.cos, Math.sin, and Math.PI, respectively. The identifiers a, x, y, and r are not methods or properties of the Math object, but since they exist in the object activation scope of the function polar(), they resolve to the corresponding local variables.

function polar(r) {
  var a, x, y;
  with (Math) {
    a = PI * r * r;
    x = r * cos(PI);
    y = r * sin(PI/2);
}
trace("area = " +a);
trace("x = " + x);
trace("y = " + y);
}

You can use nested with actions to access information in multiple scopes. In the following example, the instance fresno and the instance salinas are children of the instance california. The statement sets the _alpha values of fresno and salinas without changing the _alpha value of california.

with (california){
  with (fresno){
    _alpha = 20;
  }
  with (salinas){
    _alpha = 40;
  }
}

See also

tellTarget


XML class

Availability

Flash Player 5 (became a native object in Flash Player 6, which improved performance significantly).

Description

Use the methods and properties of the XML class to load, parse, send, build, and manipulate XML document trees.

You must use the constructor new XML() to create an XML object before calling any of the methods of the XML class.

Method summary for the XML class

Method | Description
XML.addRequestHeader() | Adds or changes HTTP headers for POST operations.
XML.appendChild() | Appends a node to the end of the specified object's child list.
XML.cloneNode() | Clones the specified node and, optionally, recursively clones all children.
XML.createElement() | Creates a new XML element.
XML.createTextNode() | Creates a new XML text node.
XML.getBytesLoaded() | Returns the number of bytes loaded for the specified XML document.
XML.getBytesTotal() | Returns the size of the XML document, in bytes.
XML.hasChildNodes() | Returns true if the specified node has child nodes; otherwise, returns false.
XML.insertBefore() | Inserts a node in front of an existing node in the specified node's child list.
XML.load() | Loads a document (specified by the XML object) from a URL.
XML.parseXML() | Parses an XML document into the specified XML object tree.
XML.removeNode() | Removes the specified node from its parent.
XML.send() | Sends the specified XML object to a URL.
XML.sendAndLoad() | Sends the specified XML object to a URL and loads the server response into another XML object.
XML.toString() | Converts the specified node and any children to XML text.

Property summary for the XML class

Property | Description
XML.contentType | Indicates the MIME type transmitted to the server.
XML.docTypeDecl | Sets and returns information about an XML document's DOCTYPE declaration.
XML.firstChild | Read-only; references the first child in the list for the specified node.
XML.ignoreWhite | When set to true, text nodes that contain only white space are discarded during the parsing process.
XML.lastChild | References the last child in the list for the specified node.
XML.loaded | Read-only; checks if the specified XML object has loaded.
XML.nextSibling | Read-only; references the next sibling in the parent node's child list.
XML.nodeName | The node name of an XML object.
XML.nodeType | The type of the specified node (XML element or text node).
XML.nodeValue | The text of the specified node if the node is a text node.
XML.parentNode | Read-only; references the parent node of the specified node.
XML.previousSibling | Read-only; references the previous sibling in the parent node's child list.
XML.status | A numeric status code indicating the success or failure of an XML document parsing operation.
XML.xmlDecl | Specifies information about a document's XML declaration.

Collections summary for the XML class

Method | Description
XML.attributes | Returns an associative array containing all of the attributes of the specified node.
XML.childNodes | Read-only; returns an array containing references to the child nodes of the specified node.

Event handler summary for the XML class

Event handler | Description
XML.onData | An event handler that is invoked when XML text has been completely downloaded from the server, or when an error occurs downloading XML text from a server.
XML.onLoad() | An event handler that returns a Boolean value indicating whether the XML object was successfully loaded with XML.load() or XML.sendAndLoad().

Constructor for the XML class

Availability

Flash Player 5.

Usage

new XML([source])

Parameters

source The XML text parsed to create the new XML object.

Returns

A reference to an XML object.

Description

Constructor; creates a new XML object. You must use the constructor to create an XML object before calling any of the methods of the XML class.

Note: The createElement() and createTextNode() methods are the "constructor" methods for creating the elements and text nodes in an XML document tree.

Example

Usage 1: The following example creates an new, empty XML object.

my_xml = new XML();

Usage 2: The following example creates an XML object by parsing the XML text specified in the source parameter, and populates the newly created XML object with the resulting XML document tree.

anyOtherXML = new XML("<state>California<city>san francisco</city></state>");

See also

XML.createElement(), XML.createTextNode()


XML.addRequestHeader()

Availability

Flash Player 6.

Usage

xml.addRequestHeader(headerName, headerValue)
xml.addRequestHeader(["headerName_1", "headerValue_1" ... "headerName_n", "headerValue_n"])

Parameters

headerName An HTTP request header name.

headerValue The value associated with headerName.

Returns

Nothing.

Description

Method; adds or changes HTTP request headers (such as Content-Type or SOAPAction) sent with POST actions. In the first usage, you pass two strings to the method: headerName and headerValue. In the second usage, you pass an array of strings, alternating header names and header values.

If multiple calls are made to set the same header name, each successive value replaces the value set in the previous call.

You cannot add or change the following standard HTTP headers using this method: Accept-Ranges, Age, Allow, Allowed, Connection, Content-Length, Content-Location, Content-Range, ETag, Host, Last-Modified, Locations, Max-Forwards, Proxy-Authenticate, Proxy-Authorization, Public, Range, Retry-After, Server, TE, Trailer, Transfer-Encoding, Upgrade, URI, Vary, Via, Warning, and WWW-Authenticate.

Example

This example adds a custom HTTP header named SOAPAction with a value of Foo to an XML object named my_xml.

my_xml.addRequestHeader("SOAPAction", "'Foo'");

This next example creates an array named headers that contains two alternating HTTP headers and their associated values. The array is passed as a parameter to the addRequestHeader() method.

var headers = ["Content-Type", "text/plain", "X-ClientAppVersion", "2.0"];
my_xml.addRequestHeader(headers);

See also

LoadVars.addRequestHeader()


XML.appendChild()

Availability

Flash Player 5.

Usage

my_xml.appendChild(childNode)

Parameters

childNode The child node to be added to the specified XML object's child list.

Returns

Nothing.

Description

Method; appends the specified child node to the XML object's child list. The appended child node is placed in the tree structure once removed from its existing parent node, if any.

Example

The following example clones the last node from doc1 and appends it to doc2.

doc1 = new XML(src1);
doc2 = new XML();
node = doc1.lastChild.cloneNode(true);
doc2.appendChild(node);


XML.attributes

Availability

Flash Player 5.

Usage

my_xml.attributes

Parameters

None.

Returns

An array.

Description

Property; an associative array containing all attributes of the specified XML object.

Example

The following example writes the names of the XML attributes to the Output window.

str = "<mytag name=\"Val\"> intem </mytag>";
doc = new XML(str);
y = doc.firstChild.attributes.name;
  trace (y);
doc.firstChild.attributes.order = "first";
z = doc.firstChild.attributes.order
  trace(z);

The following is written to the Output panel:

Val
first


XML.childNodes

Availability

Flash Player 5.

Usage

my_xml.childNodes

Parameters

None.

Returns

An array.

Description

Property (read-only); an array of the specified XML object's children. Each element in the array is a reference to an XML object that represents a child node. This is a read-only property and cannot be used to manipulate child nodes. Use XML.appendChild(), XML.insertBefore(), and XML.removeNode() to manipulate child nodes.

This property is undefined for text nodes (nodeType == 3).

See also

XML.nodeType


XML.cloneNode()

Availability

Flash Player 5.

Usage

my_xml.cloneNode(deep)

Parameters

deep Boolean value specifying whether the children of the specified XML object are recursively cloned.

Returns

An XML node.

Description

Method; constructs and returns a new XML node of the same type, name, value, and attributes as the specified XML object. If deep is set to true, all child nodes are recursively cloned, resulting in an exact copy of the original object's document tree.

The clone of the node that is returned is no longer associated with the tree of the cloned item. Consequently, nextSibling, parentNode, and previousSibling all have a value of null. If a clip copy is not performed, firstChild and lastChild are also null.


XML.contentType

Availability

Flash Player 6.

Usage

my_xml.contentType

Description

Property; the MIME type that is sent to the server when you call the XML.send() or XML.sendAndLoad() method. The default is application/x-www-form-urlencoded.

See also

XML.send(), XML.sendAndLoad()


XML.createElement()

Availability

Flash Player 5.

Usage

my_xml.createElement(name)

Parameters

name The tag name of the XML element being created.

Returns

An XML element.

Description

Method; creates a new XML element with the name specified in the parameter. The new element initially has no parent, no children, and no siblings. The method returns a reference to the newly created XML object representing the element. This method and createTextNode() are the constructor methods for creating nodes for an XML object.


XML.createTextNode()

Availability

Flash Player 5.

Usage

my_xml.createTextNode(text)

Parameters

text The text used to create the new text node.

Returns

Nothing.

Description

Method; creates a new XML text node with the specified text. The new node initially has no parent, and text nodes cannot have children or siblings. This method returns a reference to the XML object representing the new text node. This method and createElement() are the constructor methods for creating nodes for an XML object.


XML.docTypeDecl

Availability

Flash Player 5.

Usage

my_xml.XMLdocTypeDecl

Description

Property; specifies information about the XML document's DOCTYPE declaration. After the XML text has been parsed into an XML object, the XML.docTypeDecl property of the XML object is set to the text of the XML document's DOCTYPE declaration. For example, <!DOCTYPE greeting SYSTEM "hello.dtd">. This property is set using a string representation of the DOCTYPE declaration, not an XML node object.

The ActionScript XML parser is not a validating parser. The DOCTYPE declaration is read by the parser and stored in the docTypeDecl property, but no DTD validation is performed.

If no DOCTYPE declaration was encountered during a parse operation, XML.docTypeDecl is set to undefined. XML.toString() outputs the contents of XML.docTypeDecl immediately after the XML declaration stored in XML.xmlDecl, and before any other text in the XML object. If XML.docTypeDecl is undefined, no DOCTYPE declaration is output.

Example

The following example uses XML.docTypeDecl to set the DOCTYPE declaration for an XML object:

my_xml.docTypeDecl = "<!DOCTYPE greeting SYSTEM \"hello.dtd\">";

See also

XML.toString(), XML.xmlDecl


XML.firstChild

Availability

Flash Player 5.

Usage

my_xml.firstChild

Description

Property (read-only); evaluates the specified XML object and references the first child in the parent node's children list. This property is null if the node does not have children. This property is undefined if the node is a text node. This is a read-only property and cannot be used to manipulate child nodes; use appendChild(), insertBefore(), and removeNode() to manipulate child nodes.

See also

XML.appendChild(), XML.insertBefore(), XML.removeNode()


XML.getBytesLoaded()

Availability

Flash Player 6.

Usage

XML.getBytesLoaded()

Parameters

None.

Returns

An integer indicating the number of bytes loaded.

Description

Method; returns the number of bytes loaded (streamed) for the XML document. You can compare the value of getBytesLoaded() with the value of getBytesTotal() to determine what percentage of an XML document has loaded.

See also

XML.getBytesTotal()


XML.getBytesTotal()

Availability

Flash Player 6.

Usage

XML.getBytesTotal()

Parameters

None.

Returns

An integer.

Description

Method; returns the size, in bytes, of the XML document.

See also

XML.getBytesLoaded()


XML.hasChildNodes()

Availability

Flash Player 5.

Usage

my_xml.hasChildNodes()

Parameters

None.

Returns

A Boolean value.

Description

Method; returns true if the specified XML object has child nodes; otherwise, returns false.

Example

The following example uses the information from the XML object in a user-defined function.

if (rootNode.hasChildNodes()) {
  myfunc (rootNode.firstChild);
}


XML.ignoreWhite

Availability

Flash Player 5.

Usage

my_xml.ignoreWhite = boolean
XML.prototype.ignoreWhite = boolean

Parameters

boolean A Boolean (true or false) value.

Description

Property; default setting is false. When set to true, text nodes that contain only white space are discarded during the parsing process. Text nodes with leading or trailing white space are unaffected.

Usage 1: You can set the ignoreWhite property for individual XML objects, as in the following code:

my_xml.ignoreWhite = true

Usage 2: You can set the default ignoreWhite property for XML objects, as in the following code:

XML.prototype.ignoreWhite = true


XML.insertBefore()

Availability

Flash Player 5.

Usage

my_xml.insertBefore(childNode, beforeNode)

Parameters

childNode The node to be inserted.

beforeNode The node before the insertion point for the childNode.

Returns

Nothing.

Description

Method; inserts a new child node into the XML object's child list, before the beforeNode node. If the beforeNode parameter is undefined or null, the node is added using appendChild(). If beforeNode is not a child of my_xml, the insertion fails.


XML.lastChild

Availability

Flash Player 5.

Usage

my_xml.lastChild

Description

Property (read-only); evaluates the XML object and references the last child in the parent node's child list. This method returns null if the node does not have children. This is a read-only property and cannot be used to manipulate child nodes; use appendChild(), insertBefore(), and removeNode() to manipulate child nodes.

See also

XML.appendChild(), XML.insertBefore(), XML.removeNode()


XML.load()

Availability

Flash Player 5; behavior changed in Flash Player 7.

Usage

my_xml.load(url)

Parameters

url The URL where the XML document to be loaded is located. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see "Description," below.

Returns

Nothing.

Description

Method; loads an XML document from the specified URL, and replaces the contents of the specified XML object with the downloaded XML data. The URL is relative, and is called via HTTP. The load process is asynchronous; it does not finish immediately after the load() method is executed.

In SWF files running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.com can load variables from a SWF file at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

In SWF files of any version running in Flash Player 7 or later, url must be in exactly the same domain (see Flash Player security features). For example, a SWF file at www.someDomain.com can load variables only from SWF files that are also at www.someDomain.com. If you want to load variables from a different domain, you can place a cross-domain policy file on the server hosting the SWF file that is being accessed. For more information, see About allowing cross-domain data loading.

When load() is executed, the XML object property loaded is set to false. When the XML data finishes downloading, the loaded property is set to true, and the onLoad() method is invoked. The XML data is not parsed until it is completely downloaded. If the XML object previously contained any XML trees, they are discarded.

You can specify your own event handler in place of the onLoad() method.

Example

The following is a simple example using XML.load():

doc = new XML();
doc.load ("theFile.xml");

See also

XML.loaded, XML.onLoad()


XML.loaded

Availability

Flash Player 5.

Usage

my_xml.loaded

Description

Property (read-only); determines whether the document-loading process initiated by the XML.load() call has completed. If the process completes successfully, the method returns true; otherwise, it returns false.

Example

The following example uses XML.loaded in a simple script.

if (doc.loaded) {
  gotoAndPlay(4);
}


XML.nextSibling

Availability

Flash Player 5.

Usage

my_xml.nextSibling

Description

Property (read-only); evaluates the XML object and references the next sibling in the parent node's child list. This method returns null if the node does not have a next sibling node. This is a read-only property and cannot be used to manipulate child nodes. Use appendChild(), insertBefore(), and removeNode() to manipulate child nodes.

See also

XML.appendChild(), XML.insertBefore(), XML.removeNode()


XML.nodeName

Availability

Flash Player 5.

Usage

my_xml.nodeName

Description

Property; the node name of the XML object. If the XML object is an XML element (nodeType == 1), nodeName is the name of the tag representing the node in the XML file. For example, TITLE is the nodeName of an HTML TITLE tag. If the XML object is a text node (nodeType == 3), the nodeName is null.

See also

XML.nodeType


XML.nodeType

Availability

Flash Player 5.

Usage

my_xml.nodeType

Description

Property (read-only); takes or returns a nodeType value, where 1 is an XML element and 3 is a text node.

See also

XML.nodeValue


XML.nodeValue

Availability

Flash Player 5.

Usage

my_xml.nodeValue

Description

Property; the node value of the XML object. If the XML object is a text node, the nodeType is 3, and the nodeValue is the text of the node. If the XML object is an XML element (node type is 1), it has a null nodeValue and is read-only.

See also

XML.nodeType


XML.onData

Availability

Flash Player 5

Usage

my_xml.onData = function(src) {
  // your statements here
}

Parameters

src The raw data, usually in XML format, that is sent by the server.

Returns

Nothing.

Description

Event handler; invoked when XML text has been completely downloaded from the server, or when an error occurs downloading XML text from a server. This handler is invoked before the XML is parsed and therefore can be used to call a custom parsing routine instead of using the Flash XML parser. The XML.onData method returns either the value undefined, or a string that contains XML text downloaded from the server. If the returned value is undefined, an error occurred while downloading the XML from the server.

By default, the XML.onData method invokes XML.onLoad(). You can override the XML.onData method with your own behavior, but XML.onLoad() will no longer be called unless you call it in your implementation of XML.onData.

Example

The following example shows what the onData method looks like by default:

XML.prototype.onData = function (src) {
  if (src == undefined) {
    this.onLoad(false);
  } else {
    this.parseXML(src);
    this.loaded = true;
    this.onLoad(true);
  }
}

The XML.onData method can be overridden to intercept the XML text without parsing it.


XML.onLoad()

Availability

Flash Player 5.

Usage

my_xml.onLoad = function (success) {
  //your statements here
}

Parameters

success A Boolean value indicating whether the XML object was successfully loaded with a XML.load() or XML.sendAndLoad() operation.

Returns

Nothing.

Description

Event handler; invoked by Flash Player when an XML document is received from the server. If the XML document is received successfully, the success parameter is true. If the document was not received, or if an error occurred in receiving the response from the server, the success parameter is false. The default implementation of this method is not active. To override the default implementation, you must assign a function containing your own actions.

Example

The following example creates a simple SWF file for a simple e-commerce storefront application. The sendAndLoad() method transmits an XML element containing the user's name and password, and installs an onLoad handler to handle the reply from the server.

function myOnLoad(success) {
  if (success) {
    if (e.firstChild.nodeName == "LOGINREPLY_xml" &&
        e.firstChild.attributes.status == "OK") {
      gotoAndPlay("loggedIn")
    } else {
      gotoAndStop("loginFailed")
    }
  } else {
    gotoAndStop("connectionFailed")
  }
}
var myLoginReply_xml = new XML();
myLoginReply_xml.onLoad = myOnLoad;
my_xml.sendAndLoad("http://www.samplestore.com/login.cgi",
            myLoginReply_xml);

See also

function, XML.load(), XML.sendAndLoad()


XML.parentNode

Availability

Flash Player 5.

Usage

my_xml.parentNode

Description

Property (read-only); references the parent node of the specified XML object, or returns null if the node has no parent. This is a read-only property and cannot be used to manipulate child nodes; use appendChild(), insertBefore(), and removeNode() to manipulate children.


XML.parseXML()

Availability

Flash Player 5.

Usage

my_xml.parseXML(source)

Parameters

source The XML text to be parsed and passed to the specified XML object.

Returns

Nothing.

Description

Method; parses the XML text specified in the source parameter, and populates the specified XML object with the resulting XML tree. Any existing trees in the XML object are discarded.


XML.previousSibling

Availability

Flash Player 5.

Usage

my_xml.previousSibling

Description

Property (read-only); returns a reference to the previous sibling in the parent node's child list. The property has a value of null if the node does not have a previous sibling node. This is a read-only property and cannot be used to manipulate child nodes; use XML.appendChild(), XML.insertBefore(), and XML.removeNode() to manipulate child nodes.


XML.removeNode()

Availability

Flash Player 5.

Usage

my_xml.removeNode()

Parameters

None.

Returns

Nothing.

Description

Method; removes the specified XML object from its parent. All descendants of the node are also deleted.


XML.send()

Availability

Flash Player 5.

Usage

my_xml.send(url, [window])

Parameters

url The destination URL for the specified XML object.

window The browser window to display data returned by the server: _self specifies the current frame in the current window, _blank specifies a new window, _parent specifies the parent of the current frame, and _top specifies the top-level frame in the current window. This parameter is optional; if no window parameter is specified, it is the same as specifying _self.

Returns

Nothing.

Description

Method; encodes the specified XML object into an XML document and sends it to the specified URL using the POST method.


XML.sendAndLoad()

Availability

Flash Player 5; behavior changed in Flash Player 7.

Usage

my_xml.sendAndLoad(url, targetXMLobject)

Parameters

url The destination URL for the specified XML object. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see "Description," below.

targetXMLobject An XML object created with the XML constructor method that will receive the return information from the server.

Returns

Nothing.

Description

Method; encodes the specified XML object into a XML document, sends it to the specified URL using the POST method, downloads the server's response and then loads it into the targetXMLobject specified in the parameters. The server response is loaded in the same manner used by the load() method.

In SWF files running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.com can load variables from a SWF file at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

In SWF files of any version running in Flash Player 7 or later, url must be in exactly the same domain (see Flash Player security features). For example, a SWF file at www.someDomain.com can load variables only from SWF files that are also at www.someDomain.com. If you want to load variables from a different domain, you can place a cross-domain policy file on the server hosting the SWF file that is being accessed. For more information, see About allowing cross-domain data loading.

When load() is executed, the XML object property loaded is set to false. When the XML data finishes downloading, the loaded property is set to true, and the onLoad() method is invoked. The XML data is not parsed until it is completely downloaded. If the XML object previously contained any XML trees, they are discarded.

See also

XML.load()


XML.status

Availability

Flash Player 5.

Usage

my_xml.status

Description

Property; automatically sets and returns a numeric value indicating whether an XML document was successfully parsed into an XML object. The numeric status codes and a description of each are listed as follows:

  • 0 No error; parse was completed successfully.
  • -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 Out of memory.
  • -8 An attribute value was not properly terminated.
  • -9 A start-tag was not matched with an end-tag.
  • -10 An end-tag was encountered without a matching start-tag.


XML.toString()

Availability

Flash Player 5.

Usage

my_xml.toString()

Parameters

None.

Returns

A string.

Description

Method; evaluates the specified XML object, constructs a textual representation of the XML structure including the node, children, and attributes, and returns the result as a string.

For top-level XML objects (those created with the constructor), XML.toString() outputs the document's XML declaration (stored in XML.xmlDecl), followed by the document's DOCTYPE declaration (stored in XML.docTypeDecl), followed by the text representation of all XML nodes in the object. The XML declaration is not output if XML.xmlDecl is undefined. The DOCTYPE declaration is not output if XML.docTypeDecl is undefined.

Example

The following code is an example of XML.toString() that sends <h1>test</h1> to the Output panel.

node = new XML("<h1>test</h1>");
trace(node.toString());

See also

XML.docTypeDecl, XML.xmlDecl


XML.xmlDecl

Availability

Flash Player 5.

Usage

my_xml.xmlDecl

Description

Property; specifies information about a document's XML declaration. After the XML document is parsed into an XML object, this property is set to the text of the document's XML declaration. This property is set using a string representation of the XML declaration, not an XML node object. If no XML declaration was encountered during a parse operation, the property is set to undefined.XML. The toString() method outputs the contents of XML.xmlDecl before any other text in the XML object. If XML.xmlDecl contains the undefined type, no XML declaration is output.

Example

The following example uses XML.xmlDecl to set the XML document declaration for an XML object.

my_xml.xmlDecl = "<?xml version=\"1.0\" ?>";

The following is an example of XML Declaration:

<?xml version="1.0" ?>

See also

XML.docTypeDecl, XML.toString()


XMLNode class

Availability

Flash Player 5.

Description

The XMLnode class supports the following properties, methods, and collections; for information on their usage, see the corresponding XML class entries.

Property, method, or collection | Corresponding XML class entry
appendChild() | XML.appendChild()
attributes | XML.attributes
childNodes | XML.childNodes
cloneNode() | XML.cloneNode()
firstChild | XML.firstChild
hasChildNodes() | XML.hasChildNodes()
insertBefore() | XML.insertBefore()
lastChild | XML.lastChild
nextSibling | XML.nextSibling
nodeName | XML.nodeName
nodeType | XML.nodeType
nodeValue | XML.nodeValue
parentNode | XML.parentNode
previousSibling | XML.previousSibling
removeNode() | XML.removeNode()
toString() | XML.toString()

See also

XML class


XMLSocket class

Availability

Flash Player 5.

Description

The XMLSocket class implements client sockets that allow the computer running Flash Player to communicate with a server computer identified by an IP address or domain name. The XMLSocket class is useful for client-server applications that require low latency, such as real-time chat systems. A traditional HTTP-based chat solution frequently polls the server and downloads new messages using an HTTP request. In contrast, an XMLSocket chat solution maintains an open connection to the server, which allows the server to immediately send incoming messages without a request from the client.

To use the XMLSocket class, the server computer must run a daemon that understands the protocol used by the XMLSocket class. The protocol is as follows:

  • XML messages are sent over a full-duplex TCP/IP stream socket connection.
  • Each XML message is a complete XML document, terminated by a zero byte.
  • An unlimited number of XML messages can be sent and received over a single XMLSocket connection.

The following restrictions apply to how and where an XMLSocket object can connect to the server:

  • The XMLSocket.connect() method can connect only to TCP port numbers greater than or equal to 1024. One consequence of this restriction is that the server daemons that communicate with the XMLSocket object must also be assigned to port numbers greater than or equal to 1024. Port numbers below 1024 are often used by system services such as FTP, Telnet, and HTTP, thus XMLSocket objects are barred from these ports for security reasons. The port number restriction limits the possibility that these resources will be inappropriately accessed and abused.
  • The XMLSocket.connect() method can connect only to computers in the same domain where the SWF file resides. This restriction does not apply to SWF files running off a local disk. (This restriction is identical to the security rules for loadVariables(), XML.sendAndLoad(), and XML.load().) To connect to a server daemon running in a domain other than then one where the SWF resides, you can create a security policy file on the server that allows access from specific domains. For more information on creating policy files for XMLSocket connections, see About allowing cross-domain data loading.

Setting up a server to communicate with the XMLSocket object can be challenging. If your application does not require real-time interactivity, use the loadVariables() action, or Flash HTTP-based XML server connectivity (XML.load(), XML.sendAndLoad(), XML.send()), instead of the XMLSocket class.

To use the methods of the XMLSocket class, you must first use the constructor, new XMLSocket, to create a new XMLSocket object.

Method summary for the XMLSocket class

Method | Description
XMLSocket.close() | Closes an open socket connection.
XMLSocket.connect() | Establishes a connection to the specified server.
XMLSocket.send() | Sends an XML object to the server.

Event handler summary for the XMLSocket class

Event handler | Description
XMLSocket.onClose() | An event handler that is invoked when an XMLSocket connection is closed.
XMLSocket.onConnect() | An event handler that is invoked by Flash Player when a connection request initiated through XMLSocket.connect() has succeeded or failed.
XMLSocket.onData() | An event handler that is invoked when an XML message has been downloaded from the server.
XMLSocket.onXML() | An event handler that is invoked when an XML object arrives from the server.

Constructor for the XMLSocket class

Availability

Flash Player 5.

Usage

new XMLSocket()

Parameters

None.

Returns

A reference to an XMLSocket object.

Description

Constructor; creates a new XMLSocket object. The XMLSocket object is not initially connected to any server. You must call XMLSocket.connect() to connect the object to a server.


XMLSocket.close()

Availability

Flash Player 5.

Usage

myXMLSocket.close()

Parameters

None.

Returns

Nothing.

Description

Method; closes the connection specified by XMLSocket object.

See also

XMLSocket.connect()


XMLSocket.connect()

Availability

Flash Player 5; behavior changed in Flash Player 7.

Usage

myXMLSocket.connect(host, port)

Parameters

host A fully qualified DNS domain name, or an IP address in the form aaa.bbb.ccc.ddd. You can also specify null to connect to the host server on which the SWF file resides. If the SWF file issuing this call is running in a web browser, url must be in the same domain as the SWF file; for details, see "Description," below.

port The TCP port number on the host used to establish a connection. The port number must be 1024 or higher.

Returns

A Boolean value.

Description

Method; establishes a connection to the specified Internet host using the specified TCP port (must be 1024 or higher), and returns true or false depending on whether a connection is successfully established. If you don't know the port number of your Internet host machine, contact your network administrator.

If you specify null for the host parameter, the host contacted will be the host where the SWF file calling XMLSocket.connect() resides. For example, if the SWF file was downloaded from http://www.yoursite.com,specifying null for the host parameter is the same as entering the IP address for www.yoursite.com.

In SWF files running in a version of the player earlier than Flash Player 7, url must be in the same superdomain as the SWF file that is issuing this call. For example, a SWF file at www.someDomain.com can load variables from a SWF file at store.someDomain.com, because both files are in the same superdomain of someDomain.com.

In SWF files of any version running in Flash Player 7 or later, url must be in exactly the same domain (see Flash Player security features). For example, a SWF file at www.someDomain.com can load variables only from SWF files that are also at www.someDomain.com. If you want to load variables from a different domain, you can place a cross-domain policy file on the server hosting the SWF file that is being accessed (it must be placed on the HTTP server running on port 80 in the same domain as the socket server). For more information, see About allowing cross-domain data loading.

When load() is executed, the XML object property loaded is set to false. When the XML data finishes downloading, the loaded property is set to true, and the onLoad() method is invoked. The XML data is not parsed until it is completely downloaded. If the XML object previously contained any XML trees, they are discarded.

If XMLSocket.connect() returns a value of true, the initial stage of the connection process is successful; later, the XMLSocket.onConnect method is invoked to determine whether the final connection succeeded or failed. If XMLSocket.connect() returns false, a connection could not be established.

Example

The following example uses XMLSocket.connect() to connect to the host where the SWF file resides, and uses trace to display the return value indicating the success or failure of the connection.

function myOnConnect(success) {
  if (success) {
    trace ("Connection succeeded!")
  } else {
    trace ("Connection failed!")
  }
}
socket = new XMLSocket()
socket.onConnect = myOnConnect
if (!socket.connect(null, 2000)) {
  trace ("Connection failed!")
}

See also

function, XMLSocket.onConnect()


XMLSocket.onClose()

Availability

Flash Player 5.

Usage

myXMLSocket.onClose() = function() {
  // your statements here
}

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked only when an open connection is closed by the server. The default implementation of this method performs no actions. To override the default implementation, you must assign a function containing your own actions.

See also

function, XMLSocket.onConnect()


XMLSocket.onConnect()

Availability

Flash Player 5.

Usage

myXMLSocket.onConnect(success)
  // your statements here
}

Parameters

success A Boolean value indicating whether a socket connection was successfully established (true or false).

Returns

Nothing.

Description

Event handler; invoked by Flash Player when a connection request initiated through XMLSocket.connect() has succeeded or failed. If the connection succeeded, the success parameter is true; otherwise the success parameter is false.

The default implementation of this method performs no actions. To override the default implementation, you must assign a function containing your own actions.

Example

The following example illustrates the process of specifying a replacement function for the onConnect method in a simple chat application.

The function controls which screen users are taken to, depending on whether a connection is successfully established. If the connection is successfully made, users are taken to the main chat screen on the frame labeled startChat. If the connection is not successful, users go to a screen with troubleshooting information on the frame labeled connectionFailed.

function myOnConnect(success) {
  if (success) {
    gotoAndPlay("startChat")
  } else {
    gotoAndStop("connectionFailed")
  }
}

After creating the XMLSocket object using the constructor method, the script installs the onConnect method using the assignment operator:

socket = new XMLSocket();
socket.onConnect = myOnConnect;

Finally, the connection is initiated. If connect() returns false, the SWF file is sent directly to the frame labeled connectionFailed, and onConnect is never invoked. If connect() returns true, the SWF file jumps to a frame labeled waitForConnection, which is the "Please wait" screen. The SWF file remains on the waitForConnection frame until the onConnect handler is invoked, which happens at some point in the future depending on network latency.

if (!socket.connect(null, 2000)) {
  gotoAndStop("connectionFailed")
} else {
  gotoAndStop("waitForConnection")
}

See also

function, XMLSocket.connect()


XMLSocket.onData()

Availability

Flash Player 5.

Usage

XMLSocket.onData = function(src) {
  // your statements here
}

Parameters

src A string containing the data sent by the server.

Returns

Nothing.

Description

Event handler; invoked when a message has been downloaded from the server, terminated by a zero byte. You can override XMLSocket.onData to intercept the data sent by the server without parsing it as XML. This is a useful if you're transmitting arbitrarily formatted data packets, and you'd prefer to manipulate the data directly when it arrives, rather than have Flash Player parse the data as XML.

By default, the XMLSocket.onData method invokes the XMLSocket.onXML method. If you override XMLSocket.onData with your own behavior, XMLSocket.onXML will no longer be called unless you call it in your implementation of XMLSocket.onData.

XMLSocket.prototype.onData = function (src) {
  this.onXML(new XML(src));
}

In the above example, the src parameter is a string containing XML text downloaded from the server. The zero byte terminator is not included in the string.


XMLSocket.onXML()

Availability

Flash Player 5.

Usage

myXMLSocket.onXML(object) = function() {
  // your statements here
}

Parameter

object An XML object that contains a parsed XML document received from a server.

Returns

Nothing.

Description

Event handler; invoked by Flash Player when the specified XML object containing an XML document arrives over an open XMLSocket connection. An XMLSocket connection may be used to transfer an unlimited number of XML documents between the client and the server. Each document is terminated with a 0 (zero) byte. When Flash Player receives the 0 byte, it parses all of the XML received since the previous 0 byte, or since the connection was established if this is the first message received. Each batch of parsed XML is treated as a single XML document and passed to the onXML method.

The default implementation of this method performs no actions. To override the default implementation, you must assign a function containing actions that you define.

Example

The following function overrides the default implementation of the onXML method in a simple chat application. The function myOnXML instructs the chat application to recognize a single XML element, MESSAGE, in the following format.

<MESSAGE USER="John" TEXT="Hello, my name is John!" />.

The onXML handler must first be installed in the XMLSocket object as follows:

socket.onXML = myOnXML;

The function displayMessage() is assumed to be a user-defined function that displays the message received by the user.

function myOnXML(doc) {
  var e = doc.firstChild;
  if (e != null && e.nodeName == "MESSAGE") {
    displayMessage(e.attributes.user, e.attributes.text);
  }
}

See also

function


XMLSocket.send()

Availability

Flash Player 5.

Usage

myXMLSocket.send(object)

Parameters

object An XML object or other data to transmit to the server.

Returns

Nothing.

Description

Method; converts the XML object or data specified in the object parameter to a string and transmits it to the server, followed by a zero byte. If object is an XML object, the string is the XML textual representation of the XML object. The send operation is asynchronous; it returns immediately, but the data may be transmitted at a later time. The XMLSocket.send() method does not return a value indicating whether the data was successfully transmitted.

If the myXMLSocket object is not connected to the server (using XMLSocket.connect()), the XMLSocket.send() operation will fail.

Example

The following example illustrates how you could specify a user name and password to send the XML object my_xml to the server:

var my_xml = new XML();
var myLogin = my_xml.createElement("login");
myLogin.attributes.username = usernameTextField;
myLogin.attributes.password = passwordTextField;
my_xml.appendChild(myLogin);
myXMLSocket.send(my_xml);

See also

XMLSocket.connect()

Previous


Components dictionary overview

This reference chapter describes each component and each component's application programming interface (API).

Each component description contains information about the following:

  • Keyboard interaction
  • Live preview
  • Accessibility
  • Setting the component parameters
  • Using the component in an application
  • Customizing the component with styles and skins
  • ActionScript methods, properties, and events

Components are presented alphabetically. You can also find components arranged by category in the following tables:


User interface (UI) components

Component | Description
Accordion component (Flash Professional only) | A set of vertical overlapping views with buttons along the top that allow users to switch views.
Alert component (Flash Professional only) | A window that presents the user with a question and buttons to capture their response.
Button component | A resizable button that can be customized with a custom icon.
CheckBox component | Allows users to make a Boolean (true or false) choice.
ComboBox component | Allows users to select one option from a scrolling list of choices. This component can have an selectable text field at the top of the list that allows users to search the list.
DateChooser component (Flash Professional only) | Allows users to select a date or dates from a calendar.
DateField component (Flash Professional only) | A unselectable text field with a calendar icon. When a user clicks anywhere inside the bounding box of the component, a DateChooser component is displayed.
DataGrid component (Flash Professional only) | Allows users to display and manipulate multiple columns of data.
Label component | A non-editable, single-line text field.
List component | Allows users to select one or more options from a scrolling list.
Loader component | A container that holds a loaded SWF or JPEG file.
Menu component (Flash Professional only) | Allows users to select one command from a list; a standard desktop application menu.
MenuBar component (Flash Professional only) | A horizontal bar of menus.
NumericStepper component | Clickable arrows that raise and lower the value of an number.
ProgressBar component | Displays the progress of a process, usually loading.
RadioButton component | Allows users to select between mutually exclusive options.
ScrollPane component | Displays movies, bitmaps, and SWF files in a limited area using automatic scroll bars.
TextArea component | An optionally editable, multiline text field.
TextInput component | An optionally editable, single-line text input field.
Tree component (Flash Professional only) | Allows a user to manipulate hierarchical information.
Window component | A draggable window with a title bar, caption, border, and Close button that display content to the user.


Data components

Component | Description
Data binding classes (Flash Professional only) | These classes implement the Flash runtime data binding functionality.
DataHolder component (Flash Professional only) | Holds data and can be used as a connector between components.
DataProvider API | This component is the model for linear-access lists of data. This model provides simple array-manipulation capabilities that broadcast their changes.
DataSet component (Flash Professional only) | A building block for creating data-driven applications.
RDBMSResolver component (Flash Professional only) | Allows you to save data back to any supported data source. This resolver component translates the XML that can be received and parsed by a web service, JavaBean, servlet, or ASP page.
Web service classes (Flash Professional only) | These classes allow access to web services that use Simple Object Access Protocol (SOPAP) found in the mx.services package.
WebServiceConnector class (Flash Professional only) | Provides scriptless access to web service method calls.
XMLConnector component (Flash Professional only) | Reads and writes XML documents using the HTTP GET and POST methods.
XUpdateResolver component (Flash Professional only) | Allows you to save data back to any supported data source. This resolver component translates the DeltaPacket into XUpdate.


Media components

Component | Description
MediaController component | Controls streaming media playback in an application.
MediaDisplay component | Displays streaming media in an application
MediaPlayback component | A combination of the MediaDisplay and MediaController components.

For more information on these components, see Media components (Flash Professional only).


Managers

Component | Description
DepthManager class | Manages the stacking depths of objects.
FocusManager class | Handles Tab key navigation between components on the screen. Also handles focus changes as users click in the application.
PopUpManager class | Allows you to create and delete pop-up windows.
StyleManager class | Allows you to register styles and manages inherited styles.


Screens

Component | Description
Form class (Flash Professional only) | Allows you to manipulate form application screens at runtime.
Screen class overview (Flash Professional only) | Base class for the Slide and Form classes.
Slide class (Flash Professional only) | Allows you to manipulate slide presentation screens at runtime.


About the Accordion component (Flash Professional only)

The Accordion component is a navigator that contains a sequence of children that it displays one at a time. The children must be a subclass of the UIObject class (which includes all components and screens built using version 2 of the Macromedia Component Architecture), but most commonly children are a subclass of the View class. This includes movie clips assigned to the class mx.core.View. To maintain tabbing order in an accordion's children, the children must also be instances of the View class.

An accordion creates and manages header buttons that a user can press to navigate between the accordion's children. An accordion has a vertical layout with header buttons that span the width of the component. There is one header associated with each child, and each header belongs to the accordion—not to the child. When a user clicks a header, the associated child is displayed below that header. The transition to the new child uses a transition animation.

An accordion with children accepts focus, and changes the appearance of its headers to display focus. When a user tabs into an accordion, the selected header displays the focus indicator. An accordion with no children does not accept focus. Clicking components that can take focus within the selected child gives them focus. When an Accordion instance has focus, you can use the following keys to control it:

Key | Description
Down arrow, Right arrow | Moves focus to the next child header. Focus wraps from last to first without changing the selected child.
Up arrow, Left arrow | Moves focus to the previous child header. Focus wraps from first to last without changing the selected child.
End | Selects the last child.
Enter/Space | Selects the child associated with the header that has focus.
Home | Selects the first child.
Page Down | Selects the next child. Selection wraps from the last child to the first child.
Page Up | Selects the previous child. Selection wraps from the first child to the last child.
Shift +Tab | Moves focus to the previous component. This component may be inside the selected child, or outside the accordion; it will never be another header in the same accordion.
Tab | Moves focus to the next component. This component may be inside the selected child, or outside the accordion; it will never be another header in the same accordion.

The Accordion component cannot be made accessible to screen readers.


Using the Accordion component (Flash Professional only)

The Accordion component can be used to present multi-part forms. For example, a three-child accordion might present forms where the user fills out her shipping address, billing address, and payment information for an e-commerce transaction. Using an accordion instead of multiple web pages minimizes server traffic and allows the user to maintain a better sense of progress and context in an application.

Accordion parameters

The following are authoring parameters that you can set for each Accordion component instance in the Property inspector or in the Component Inspector panel:

childSymbols An array specifying the linkage identifiers of the library symbols to be used to create the accordion's children. The default value is [] (empty array).

childNames An array specifying the instance names of the accordion's children. The default value is [] (empty array).

childLabels An array specifying the text labels to use on the accordion's headers. The default value is [] (empty array).

childIcons An array specifying the linkage identifiers of the library symbols to be used as the icons on the accordion's headers. The default value is [] (empty array).

You can write ActionScript to control these and additional options for the Accordion component using its properties, methods, and events. For more information, see Accordion class (Flash Professional only).

Creating an application with the Accordion component

In this example, an application developer is building the checkout section of an online store. The design calls for an accordion with three forms in which users enter their shipping address, billing address, and payment information. The shipping address and billing address forms are identical.

To use screens to add an Accordion component to an application:

  1. In Flash, select File > New and select Flash Form Application.
  2. Double-click the text Form1 and enter the name addressForm.

    Although it doesn't show up in the library, the addressForm screen is a symbol of the Screen class (which is a subclass of the View class), which an accordion can use as a child.

  3. With the form selected, in the Property inspector, set its visible property to false.

    This hides the contents of the form in the application; the form only appears in the Accordion.

  4. Drag components such as Label and TextInput from the Components panel onto the form to create a mock address form; arrange them, and set their properties in the Parameters pane of the Component Inspector panel.

    Position the form elements in the upper left corner of the form. The upper left corner of the form is placed in the upper left corner of the Accordion.

  5. Repeat steps 2-4 to create a screen named checkoutForm.
  6. Create a new form named accordionForm.
  7. Drag an Accordion component from the Components panel to the accordionForm form and name it myAccordion.
  8. With myAccordion selected, in the Property inspector, do the following:
    • For the childSymbols property, enter addressForm, addressForm, and checkoutForm.

      These strings specify the names of the screens used to create the accordion's children.

      Note: The first two children are instances of the same screen, because the shipping address form and the billing address form have identical components.

    • For the childNames property, enter shippingAddress, billingAddress, and checkout.

      These strings are the ActionScript names of the accordion's children.

    • For the childLabels property, enter Shipping Address, Billing Address, and Checkout.

      These strings are the text labels on the accordion headers.

  9. Select Control > Test Movie.

To add an Accordion component to an application, do the following:

  1. Select File > New and create a new Flash Document.
  2. Select Insert > New Symbol and name it AddressForm.
  3. In the Create New Symbol dialog, click the Advanced button and select Export for ActionScript. In the AS 2.0 class field, enter mx.core.View.

    To maintain tabbing order in an accordion's children, the children must also be instances of the View class.

  4. Drag components such as Label and TextInput from the Components panel onto the Stage to create a mock address form; arrange them, and set their properties in the Parameters pane of the Component Inspector panel.

    Position the form elements in relation to 0, 0 (the middle) on the Stage. The 0, 0 coordinate of the movie clip is placed in the upper left corner of the Accordion.

  5. Select Edit > Edit Document to return to the main Timeline.
  6. Repeat steps 2-5 to create a movie clip named CheckoutForm.
  7. Drag an Accordion component from the Components panel to add it to the Stage on the main Timeline.
  8. In the Property inspector, do the following:
    • Enter the instance name myAccordion.
    • For the childSymbols property, enter AddressForm, AddressForm, and CheckoutForm.

      These strings specify the names of the movie clips used to create the accordion's children.

      Note: The first two children are instances of the same movie clip, because the shipping address form and the billing address form are identical.

    • For the childNames property, enter shippingAddress, billingAddress, and checkout.

      These strings are the ActionScript names of the accordion's children.

    • For the childLabels property, enter Shipping Address, Billing Address, and Checkout.

      These strings are the text labels on the accordion headers.

    • For the childIcons property, enter AddressIcon, AddressIcon, and CheckoutIcon.

      These strings specify the linkage identifiers of the movie clip symbols that are used as the icons on the accordion headers. You must create these movie clip symbols if you want icons in the headers.

  9. Select Control > Test Movie.

To use ActionScript to add children to an Accordion component, do the following:

  1. Select File > New and create a Flash Document.
  2. Drag an Accordion component from the Components panel to the Stage.
  3. In the Property inspector, enter the instance name myAccordion.
  4. Drag a TextInput component to the Stage and delete it.

    This adds it to the Library so that you can dynamically instantiate it in step 6.

  5. In the Actions panel on Frame 1 of the Timeline, enter the following:
    myAccordion.createChild("View", "shippingAddress", { label: "Shipping Address" });
myAccordion.createChild("View", "billingAddress", { label: "Billing Address" });
myAccordion.createChild("View", "payment", { label: "Payment" });

    This code calls the createChild() method to create its child views.

  6. In the Actions panel on Frame 1, below the code you entered in step 4, enter the following code:
    var o = myAccordion.shippingAddress.createChild("TextInput", "firstName");
o.move(20, 38);
o.setSize(116, 20);
o = myAccordion.shippingAddress.createChild("TextInput", "lastName");
o.move(175, 38);
o.setSize(145, 20);

    This code adds component instances (two TextInput components) to the accordion's children.


Customizing the Accordion component (Flash Professional only)

You can transform an Accordion component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()).

The setSize() method and the Transform tool only change the width of the accordion's headers and the width and height of its content area. The height of the headers and the width and height of the children are not affected. Calling the setSize() method is the only way to change the bounding rectangle of an accordion.

If the headers are too small to contain their label text, the labels are clipped. If the content area of an accordion is smaller than a child, the child is clipped.

Using styles with the Accordion component

You can set style properties to change the appearance of the border and background of an Accordion component.

If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

An Accordion component that uses the Halo theme supports the following styles:

Style | Description
themeColor | The background of a component. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
backgroundColor | The background color.
borderColor | The border color.
borderStyle | The border style; possible values are "none", "solid", "inset", "outset", "default", "alert". The "default" value is the look of the Window component's border and the "alert" value is the look of the Alert component's border.
headerHeight | The height of the header buttons in pixels.
color | The header text color.
disabledColor | The color of a disabled accordion.
fontFamily | The font name for the header labels.
fontSize | The point size for the font of the header labels.
fontStyle | The font style for the header labels; either "normal", or "italic".
fontWeight | The font weight for the header labels; either "normal", or "bold".
textDecoration | The text decoration; either "none", or "underline".
openDuration | The duration, in milliseconds, of the transition animation.
openEasing | The tweening function used by the animation.

Using skins with the Accordion component

The Accordion component uses skins to represent the visual states of its header buttons. To skin the buttons and title bar while authoring, modify skin symbols in the Flash UI Components 2/Themes/MMDefault/Accordion Assets skins states folder in the library of one of the themes FLA files. For more information, see About skinning components.

An Accordion component is composed of its border and background, its header buttons, and its children. The border and background are styleable, but not skinnable. The headers are skinnable, but not styleable, using the subset of skins inherited from button listed below. An Accordion component uses the following skin properties to dynamically skin the header buttons:

Property | Description | Default value
falseUpSkin | The up state. | accordionHeaderSkin
falseDownSkin | The pressed state. | accordionHeaderSkin
falseOverSkin | The rolled-over state. | accordionHeaderSkin
trueUpSkin | The toggled state. | accordionHeaderSkin


Accordion class (Flash Professional only)

Inheritance UIObject > UIComponent > View > Accordion

ActionScript Class Name mx.containers.Accordion

An Accordion is a component that contains children that are displayed one at a time. Each child has a corresponding header button that is created when the child is created. A child must be an instance of UIObject.

A movie clip symbol automatically becomes an instance of the UIObject class when it becomes a child of an accordion. However, to maintain tabbing order in an accordion's children, the children must also be instances of the View class. If you use a movie clip symbol as a child, set its AS 2.0 class field to mx.core.View so that it inherits from the View class.

Setting a property of the Accordion class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.Accordion.version);

Note: The following code returns undefined: trace(myAccordionInstance.version);.

Method summary for the Accordion class

Method | Description
Accordion.createChild() | Creates a child for an accordion instance.
Accordion.createSegment() | Creates a child for an accordion instance. The parameters for this method are different from those of the createChild() method.
Accordion.destroyChildAt() | Destroys a child at a specified index position.
Accordion.getChildAt() | Gets a reference to a child at a specified index position.

Inherits all methods from UIObject, UIComponent and mx.core.View.

Property summary for the Accordion class

Property | Description
Accordion.numChildren | The number of children of an accordion instance.
Accordion.selectedChild | A reference to the selected child.
Accordion.selectedIndex | The index position of the selected child.

Inherits all properties from UIObject, UIComponent and mx.core.View.

Event summary for the Accordion class

Event | Description
Accordion.change | Broadcast to all registered listeners when the selectedIndex and selectedChild properties of an accordion change due to a user's mouse click or key press.

Inherits all events from UIObject, UIComponent and mx.core.View.


Accordion.change

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.change = function(eventObject){
  // insert your code here
}
myAccordionInstance.addEventListener("change", listenerObject)

Description

Event; broadcast to all registered listeners when the selectedIndex and selectedChild properties of an accordion change. This event is broadcast only when a user's mouse click or key press changes the value selectedChild or selectedIndex—not when the value is changed with ActionScript. This event is broadcast before the transition animation occurs.

V2 components use a dispatcher/listener event model. The Accordion component dispatches a change event when one of its buttons is pressed and the event is handled by a function (also called a handler) on a listener object (listenerObject) that you create. You call the addEventListener() method and pass it a reference to the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Example

In the following example, a handler called myAccordionListener is defined and passed to the myAccordion.addEventListener() method as the second parameter. The event object is captured by change handler in the evtObject parameter. When the change event is broadcast, a trace statement is sent to the Output panel, as follows:

myAccordionListener = new Object();
myAccordionListener.change = function(){
  trace("Changed to different view");
}
myAccordion.addEventListener("change", myAccordionListener);


Accordion.createChild()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myAccordion.createChild(classOrSymbolName, instanceName[, initialProperties])

Parameters

classOrSymbolName This parameter can either be the constructor function for the class of the UIObject to be instantiated, or the linkage name, a reference to the symbol to be instantiated. The class must be UIObject or a subclass of UIObject, but most often it is a View or a subclass of View.

instanceName The instance name of the new instance.

initialProperties An optional parameter that specifies initial properties for the new instance. You can use the following properties:

  • label This string specifies the text label that the new child instance uses on its header.
  • icon This string specifies the linkage identifier of the library symbol that the child uses for the icon on its header.

Returns

A reference to an instance of the UIObject that is the newly created child.

Description

Method (inherited from View); creates a child for the Accordion. The newly created child is added to the end of the list of children owned by the Accordion. Use this method to place views inside the accordion. The created child is an instance of the class or movie clip symbol specified in the classOrSymbolName parameter. You can use the label and icon properties to specify a text label and an icon for the associated accordion header for each child in the initialProperties parameter.

When each child is created, it is assigned an index number in the order of creation and the numChildren property is increased by 1.

Example

The following code creates an instance of the movie clip symbol PaymentForm named payment as the last child of myAccordion:

var child = myAccordion.createChild("PaymentForm", "payment", { label: "Payment", Icon: "payIcon" });
child.cardType.text = "Visa";
child.cardNumber.text = "1234567887654321";

The following code creates a child that is an instance of the View class:

var child = myAccordion.createChild(mx.core.View, "payment", { label: "Payment", Icon: "payIcon" });
child.cardType.text = "Visa";
child.cardNumber.text = "1234567887654321";

The following code also creates a child that is an instance of the View class, but it uses import to reference the constructor for the View class:

import mx.core.View
var child = myAccordion.createChild(View, "payment", { label: "Payment", Icon: "payIcon" });
child.cardType.text = "Visa";
child.cardNumber.text = "1234567887654321";


Accordion.createSegment()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

myAccordion.createSegment(classOrSymbolName, instanceName[, label[, icon]])

Parameters

classOrSymbolName This parameter can be either a reference to the constructor function for the class of the UIObject to be instantiated, or the linkage name of the symbol to be instantiated. The class must be UIObject or a subclass of UIObject, but most often it is a View or a subclass of View.

instanceName The instance name of the new instance.

label This string specifies the text label that the new child instance uses on its header. This parameter is optional.

icon This string is a reference to the linkage identifier of the library symbol that the child uses for the icon on its header. This parameter is optional.

Returns

A reference to the newly created UIObject instance.

Description

Method; creates a child for the Accordion. The newly created child is added to the end of the list of children owned by the Accordion. Use this method to place views inside the accordion. The created child is an instance of the class or movie clip symbol specified in the classOrSymbolName parameter. You can use the label and icon parameters to specify a text label and an icon for the associated accordion header for each child.

The createSegment() method differs from the createChild() method in that label and icon are passed directly as parameters, not as properties of an initalProperties parameter.

When each child is created, it is assigned an index number in the order of creation and the numChildren property is increased by 1.

Example

The following example creates an instance of the PaymentForm movie clip symbol named payment as the last child of myAccordion:

var child = myAccordion.createSegment("PaymentForm", "payment", "Payment", "payIcon");
child.cardType.text = "Visa";
child.cardNumber.text = "1234567887654321";

The following code creates a child that is an instance of the View class:

var child = myAccordion.createSegment(mx.core.View, "payment", { label: "Payment", Icon: "payIcon" });
child.cardType.text = "Visa";
child.cardNumber.text = "1234567887654321";

The following code also creates a child that is an instance of the View class, but it uses import to reference the constructor for the View class:

import mx.core.View
var child = myAccordion.createSegment(View, "payment", { label: "Payment", Icon: "payIcon" });
child.cardType.text = "Visa";
child.cardNumber.text = "1234567887654321";


Accordion.destroyChildAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myAccordion.destroyChildAt(index)

Parameters

index The index number of the accordion child to destroy. Each child of an accordion is assigned a zero-based index number in the order that it was created.

Returns

Nothing.

Description

Method (inherited from View); destroys one of the accordion's children. The child to be destroyed is specified by its index, which is passed to the method in the index parameter. Calling this method destroys the corresponding header as well.

If the destroyed child is selected, a new selected child is chosen. If there is a next child, it is selected. If there is no next child, the previous child is selected. If there is no previous child, the selection is undefined.

Note: Calling the destroyChildAt() method decreases the numChildren property by 1.

Example

The following code destroys the last child of myAccordion:

myAccordion.destroyChildAt(myAccordion.numChildren - 1);

See also

Accordion.createChild()


Accordion.getChildAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myAccordion.getChildAt(index)

Parameters

index The index number of an accordion child. Each child of an accordion is assigned a zero-based index in the order that it was created.

Returns

A reference to the instance of the UIObject at the specified index.

Description

Method; returns a reference to the child at the specified index. Each accordion child is given an index number for its position. This index number is zero-based, so the first child is 0, the second child is 1, and so on.

Example

The following code gets a reference to the last child of myAccordion:

var lastChild:UIObject = myAccordion.getChildAt(myAccordion.numChildren - 1);


Accordion.numChildren

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myAccordion.numChildren

Description

Property (inherited from View); indicates the number of children (child UIObjects) in an accordion instance. Headers are not counted as children.

Each accordion child is given an index number for its position. This index number is zero-based, so the first child is 0, the second child is 1, and so on. The code myAccordion.numChild - 1 always refers to the last child added to an accordion. For example, if there were 7 children in an accordion, the last child would have the index 6. The numChildren property is not zero-based so the value of myAccordion.numChildren would be 7. The result of 7 - 1 is 6 which is the index number of the last child.

Example

The following example selects the last child:

myAccordion.selectedIndex = myAccordion.numChildren - 1;


Accordion.selectedChild

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myAccordion.selectedChild

Description

Property; the selected child if one or more children exist; undefined if no children exist. This property is either of type UIObject, or undefined.

If the accordion has children, the code myAccordion.selectedChild is equivalent to the code myAccordion.getChildAt(myAccordion.selectedIndex).

Setting this property to a child causes the accordion to begin the transition animation to display the specified child.

Changing the value of selectedChild also changes the value of selectedIndex.

The default value is myAccordion.getChildAt(0) if the accordion has children. If the accordion doesn't have children, the default value is undefined.

Example

The following example gets the label of the selected child view:

var selectedLabel = myAccordion.selectedChild.label;

The following example sets the payment form to be the selected child view:

myAccordion.selectedChild = myAccordion.payment;

See also

Accordion.selectedIndex


Accordion.selectedIndex

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myAccordion.selectedIndex

Description

Property; the zero-based index of the selected child in an accordion with one or more children. For an accordion with no child views, the only valid value is undefined.

Each accordion child is given an index number for its position. This index number is zero-based, so the first child is 0, the second child is 1, and so on. The valid values of selectedIndex are 0, 1, 2, ... , n - 1, where n is the number of children.

Setting this property to a child causes the accordion to begin the transition animation to display the specified child.

Changing the value of selectedIndex also changes the value of selectedChild.

Example

The following example remembers the index of the selected child:

var oldSelectedIndex = myAccordion.selectedIndex;

The following example selects the last child:

myAccordion.selectedIndex = myAccordion.numChildren - 1;

See also

Accordion.selectedChild, Accordion.numChildren


About the Alert component (Flash Professional only)

The Alert component allows you to pop up a window that presents the user with a message and response buttons. The Alert window has a title bar that you can fill with text, a message that you can customize, and buttons whose labels you can change. An Alert window can have any combination of the following buttons: Yes, No, OK, and Cancel. You can change the text labels on the buttons by using the following properties: Alert.yesLabel, Alert.noLabel, Alert.okLabel, and Alert.cancelLabel. You cannot change the order of the buttons in an Alert window; the button order is always OK, Yes, No, Cancel.

To pop up an Alert window, you must call the Alert.show() method. In order to call the method successfully, the Alert component must be in the library. You must drag the Alert component from the Components panel to the Stage and then delete the Alert component from the Stage. This adds the component to the Library but doesn't make it visible in the document.

The live preview for the Alert component is an empty window.

The text and buttons of an Alert window can be made accessible to screen readers. When you add the Alert component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility:

mx.accessibility.AlertAccImpl.enableAccessibility();

You only enable accessibility for a component once no matter how many instances you have of the component.

For more information, see Creating Accessible Content.


Using the Alert component (Flash Professional only)

The Alert can be used whenever you want to announce something to a user. For example, you could pop up an Alert when a user doesn't fill out a form properly, or when a stock hits a certain price, or when a user quits an application without saving his session.

Alert parameters

There are no authoring parameters for the Alert component. You must call the ActionScript Alert.show() method to pop up an Alert window. You can use other ActionScript properties to modify the Alert window in an application. For more information, see Alert class (Flash Professional only).

Creating an application with the Alert component

The following procedure explains how to add a Alert component to an application while authoring. In this example, the Alert component pops up when a stock hits a certain price.

To create an application with the Alert component, do the following:

  1. Double-click the Alert component in the Components panel to add it to the Stage.
  2. Press Backspace (Windows) or Delete (Macintosh) to delete the component from the Stage.

    This adds the component to the library, but doesn't make it visible in the application.

  3. In the Actions panel, enter the following code on Frame 1 of the Timeline to define an event handler for the click event:
    import mx.controls.Alert
myClickHandler = function (evt){
  if (evt.detail == Alert.OK){
    trace("start stock app");
    // startStockApplication();
  }
}
Alert.show("Launch Stock Application?", "Stock Price Alert", Alert.OK | Alert.CANCEL, this, myClickHandler, "stockIcon", Alert.OK);

    This code creates an Alert window with OK and Cancel buttons. When either button is pressed, the myClickHandler function is called. But when the OK button is pressed, the startStockApplication() method is called.

  4. Control > Test Movie.


Customizing the Alert component (Flash Professional only)

The Alert positions itself in the center of the component that was passed as its parent parameter. The parent must be a UIComponent. If it is a movie clip, you can register the clip as mx.core.View so that it inherits from UIComponent.

The Alert window automatically stretches horizontally to fit the message text or any buttons that are displayed. If you want to display large amounts of text, include line breaks in the text.

The Alert does not respond to the setSize() method.

Using styles with the Alert component

You can set style properties to change the appearance of an Alert component. If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

An Alert component that uses the Halo theme supports the following styles:

Style | Description
themeColor | The background of a component. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style; either "normal", or "italic".
fontWeight | The font weight; either "normal", or "bold".
textDecoration | The text decoration; either "none", or "underline".
buttonStyleDeclaration | A class (static) CSSStyleDeclaration for the button's text styles.
messageStyleDeclaration | A class (static) CSSStyleDeclaration for the message's text, border, and background styles.
titleStyleDeclaration | A class (static) CSSStyleDeclaration for the title's text styles.

Using skins with the Alert component

The Alert component uses the Window skins to represent the visual states of its buttons and title bar. To skin the buttons and title bar while authoring, modify skin symbols in the Flash UI Components 2/Themes/MMDefault/Window Assets skins states folder in the library of one of the themes FLA files. For more information, see About skinning components.

There is ActionScript code in the RectBorder.as class that the Alert component uses to draw its borders. You can use RectBorder styles to modify an Alert component as follows:

var myAlert = Alert.show("This is a test of errors", "Error", Alert.OK | Alert.CANCEL, this);
myAlert.setStyle("borderStyle", "inset");

For information about RectBorder styles, see Using skins with the List component.

An Alert component uses the following skin properties to dynamically skin the buttons and title bar:

Property | Description | Default value
buttonUp | The up state of the button. | ButtonSkin
buttonDown | The pressed state of the button. | ButtonSkin
buttonOver | The rolled-over state of button. | ButtonSkin
titleBackground | The window title bar. | TitleBackground


Alert class (Flash Professional only)

Inheritance UIObject > UIComponent > View > ScrollView > Window > Alert

ActionScript Class Name mx.controls.Alert

To use the Alert component, you drag an Alert component to the Stage and delete it so that the component is in the document library but not visible in the application. Then you call Alert.show() to pop up an Alert window. You can pass parameters to Alert.show() that add a message, a title bar, and buttons to the Alert window.

Because ActionScript is asynchronous, the Alert component is not blocking, which means that the lines of ActionScript code after the call to Alert.show() run right away. You must add listeners to handle the click events that are broadcast when a user presses a button and then continue your code after the event is broadcast.

Note: In operating environments that are blocking (for example, Microsoft Windows), a call to Alert.show() would not return until the user has taken an action, such as pushing a button.

Method summary for the Alert class

Event | Description
Alert.show() | Creates an Alert window with optional parameters.

Inherits all methods from UIObject and UIComponent.

Property summary for the Alert class

Property | Description
Alert.buttonHeight | The height of each button in pixels. The default value is 22.
Alert.buttonWidth | The width of each button in pixels. The default value is 100.
Alert.cancelLabel | The label text for the Cancel button.
Alert.noLabel | The label text for the No button.
Alert.okLabel | The label text for the OK button.
Alert.yesLabel | The label text for the Yes button.

Inherits all properties from UIObject and UIComponent.

Event summary for the Alert class

Event | Description
Alert.click | Broadcast when a button in an Alert window is clicked.

Inherits all events from UIObject and UIComponent.


Alert.buttonHeight

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Alert.buttonHeight

Description

Property (class); a class property (static) that changes the height of the buttons.

See also

Alert.buttonWidth


Alert.buttonWidth

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Alert.buttonWidth

Description

Property (class); a class property (static) that changes the width of the buttons.

See also

Alert.buttonHeight


Alert.click

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

clickHandler = function(eventObject){
  // insert code here
}
Alert.show(message[, title[, flags[, parent[, clickHandler[, icon[, defaultButton]]]]]])

Description

Event; broadcast to the registered listener when the OK, Yes, No, or Cancel button is clicked.

V2 components use a dispatcher/listener event model. The Alert component dispatches a click event when one of its buttons is clicked and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You call the Alert.show() method and pass it the name of the handler as a parameter. When a button in the Alert window is clicked, the listener is called.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The Alert.click event's event object has an additional detail property whose value is one of the following depending on which button was clicked: Alert.OK, Alert.CANCEL, Alert.YES, Alert.NO. For more information about event objects, see Event Objects.

Example

In the following example, a handler called myClickHandler is defined and passed to the Alert.show() method as the 5th parameter. The event object is captured by myClickHandler in the evt parameter. The detail property of the event object is then used within a trace statement to send the name of the button that was clicked (Alert.OK or Alert.CANCEL) to the Output panel, as follows:

myClickHandler = function(evt){
  if(evt.detail == Alert.OK){
    trace(Alert.okLabel);
  }else if (evt.detail == Alert.CANCEL){
    trace(Alert.cancelLabel);
  }
}
Alert.show("This is a test of errors", "Error", Alert.OK | Alert.CANCEL, this, myClickHandler);


Alert.cancelLabel

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Alert.cancelLabel

Description

Property (class); a class property (static) that indicates the label text on the Cancel button.

Example

The following example sets the Cancel button's label to "cancellation":

Alert.cancelLabel = "cancellation";


Alert.noLabel

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Alert.noLabel

Description

Property (class); a class property (static) that indicates the label text on the No button.

Example

The following example sets the No button's label to "nyet":

Alert.noLabel = "nyet";


Alert.okLabel

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Alert.okLabel

Description

Property (class); a class property (static) that indicates the label text on the OK button.

Example

The following example sets the OK button's label to "okay":

Alert.okLabel = "okay";


Alert.show()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Alert.show(message[, title[, flags[, parent[, clickHandler[, icon[, defaultButton]]]]]])

Parameters

message The message to display.

title The text in the Alert title bar. This parameter is optional. If the title parameter is not specified, the title bar is blank.

flags An optional parameter that indicates the button or buttons to display in the Alert window. The default value is Alert.OK, which displays an "OK" button. When you use more than one value, separate the values with a | character. The value can be one or more of the following:

  • Alert.OK
  • Alert.CANCEL
  • Alert.YES
  • Alert.NO

You can also use Alert.NONMODAL to indicate that the Alert window is non-modal. A non-modal window allows a user to interact with other windows in the application.

parent The parent window for the Alert component. The Alert window centers itself in the parent window. Use the value null or undefined to specify the _root Timeline. The parent window must inherit from the UIComponent class. You can register the parent window with mx.core.View to cause it to inherit from UIComponent. This parameter is optional.

clickHandler A handler for the click events broadcast when the buttons are clicked. In addition to the standard click event object properties, there is an additional detail property, which contains the value of the button flag that was clicked (Alert.OK, Alert.CANCEL, Alert.YES, Alert.NO). This handler may be a function or an object. For more information, see Using component event listeners.

icon A string that is the linkage identifier of a symbol in the library to use as an icon that is displayed to the left of the text. This parameter is optional.

defaultButton Indicates which button is clicked when a user presses Enter (Windows) or Return (Macintosh). This parameter can be one of the following values:

  • Alert.OK
  • Alert.CANCEL
  • Alert.YES
  • Alert.NO

Returns

The instance of the Alert class that is created.

Description

Method (class); a class (static) method that displays an Alert window with a message, an optional title, optional buttons, and an optional icon. The title of the Alert appears at the top of the window and is aligned to the left. The icon appears to the left of the message text. The buttons appear centered below the message text and the icon.

Example

The following code is a simple example of a modal Alert window with an OK button:

Alert.show("Hello, world!");

The following code defines a click handler that sends a message to the Output panel about which button was clicked:

myClickHandler = function(evt){
  trace (evt.detail + "was clicked");
}
Alert.show("This is a test of errors", "Error", Alert.OK | Alert.CANCEL, this, myClickHandler);

Note: The event object's detail property returns a number to represent each button. The OK button is 4, the cancel button is 8, the yes button is 1, and the no button is 2.


Alert.yesLabel

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Alert.yesLabel

Description

Property (class); a class property (static) that indicates the label text on the Yes button.

Example

The following example sets the OK button's label to "da":

Alert.yesLabel = "da";


About the Button component

The Button component is a resizable rectangular user interface button. You can add a custom icon to a button. You can also change the behavior of a button from push to toggle. A toggle button stays pressed when clicked and returns to its up state when clicked again.

A button can be enabled or disabled in an application. In the disabled state, a button doesn't receive mouse or keyboard input. An enabled button receives focus if you click it or tab to it. When a Button instance has focus, you can use the following keys to control it:

Key | Description
Shift + Tab | Moves focus to the previous object.
Spacebar | Presses or releases the component and triggers the click event.
Tab | Moves focus to the next object.

For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each Button instance reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring. However, in the live preview a custom icon is represented on the Stage by a gray square.

When you add the Button component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility for the Button component:

mx.accessibility.ButtonAccImpl.enableAccessibility();

You only enable accessibility for a component once no matter how many instances you have of the component. For more information, see Creating Accessible Content.


Using the Button component

A button is a fundamental part of any form or web application. You can use buttons wherever you want a user to initiate an event. For example, most forms have a "Submit" button. You could also add "Previous" and "Next" buttons to a presentation.

To add an icon to a button, you need to select or create a movie clip or graphic symbol to use as the icon. The symbol should be registered at 0, 0 for appropriate layout on the button. Select the icon symbol in the Library panel, open the Linkage dialog from the Options menu, and enter a linkage identifier. This is the value to enter for the icon parameter in the Property inspector or Component Inspector panel. You can also enter this value for the Button.icon ActionScript property.

Note: If an icon is larger than the button it will extend beyond the button's borders.

Button parameters

The following are authoring parameters that you can set for each Button component instance in the Property inspector or in the Component Inspector panel:

label sets the value of the text on the button; the default value is Button.

icon adds a custom icon to the button. The value is the linkage identifier of a movie clip or graphic symbol in the library; there is no default value.

toggle turns the button into a toggle switch. If true, the button remains in the down state when pressed and returns to the up state when pressed again. If false, the button behaves like a normal push button; the default value is false.

selected if the toggle parameter is true, this parameter specifies whether the button is pressed (true) or released (false). The default value is false.

labelPlacement orients the label text on the button in relation to the icon. This parameter can be one of four values: left, right, top, or bottom; the default value is right. For more information, see Button.labelPlacement.

You can write ActionScript to control these and additional options for Button components using its properties, methods, and events. For more information, see Button class.

Creating an application with the Button component

The following procedure explains how to add a Button component to an application while authoring. In this example, the button is a Help button with a custom icon that will open a Help system when a user presses it.

To create an application with the Button component, do the following:

  1. Drag a Button component from the Components panel to the Stage.
  2. In the Property inspector, enter the instance name helpBtn.
  3. In the Property inspector, do the following:
    • Enter Help for the label parameter.
    • Enter HelpIcon for the icon parameter.

      To use an icon, there must be a movie clip or graphic symbol in the library with a linkage identifier to use as the icon parameter. In this example, the linkage identifier is HelpIcon.

    • Set the toggle property to true.
  4. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code:
    clippyListener = new Object();
clippyListener.click = function (evt){
  clippyHelper.enabled = evt.target.selected;
}
helpBtn.addEventListener("click", clippyListener);

    The last line of code adds a click event handler to the helpBtn instance. The handler enables and disables the clippyHelper instance, which could be a Help panel of some sort.


Customizing the Button component

You can transform a Button component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()) or any applicable properties and methods of the Button class (see Button class). Resizing the button does not change the size of the icon or label.

The bounding box of a Button instance is invisible and also designates the hit area for the instance. If you increase the size of the instance, you also increase the size of the hit area. If the bounding box is too small to fit the label, the label clips to fit.

If an icon is larger than the button it will extend beyond the button's borders.

Using styles with the Button component

You can set style properties to change the appearance of a button instance. If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

A Button component that uses the Halo theme supports the following styles:

Style | Description
themeColor | The background of a component. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style: either "normal", or "italic".
fontWeight | The font weight: either "normal", or "bold".

Using skins with the Button component

The Button component uses the ActionScript drawing API to draw the button states. To skin the Button component while authoring, modify the ActionScript code within the ButtonSkin.as file located in the First Run\Classes\mx\skins\halo folder.

If you use the UIObject.createClassObject() method to create a Button component instance dynamically (at runtime), you can skin it dynamically. To skin a component at runtime, set the skin properties of the initObject parameter that is passed to the createClassObject() method. These skin properties set the names of the symbols to use as the button's states, both with and without an icon.

If you set the icon parameter while authoring or the icon ActionScript property at runtime, the same linkage identifier is assigned to three icon states: falseUpIcon, falseDownIcon, and trueUpIcon. If you want to designate a unique icon for any of the eight icon states (if, for example, you want a different icon to appear when a user presses a button) you must set properties of the initObject parameter that is passed to the createClassObject() method.

The following code creates an object called initObject to use as the initObject parameter and sets skin properties to new symbol linkage identifiers. The last line of code calls the createClassObject() method to create a new instance of the Button class with the properties passed in the initObject parameter, as follows:

var initObject = new Object();
initObject.falseUpIcon = "MyFalseUpIcon";
initObject.falseDownIcon = "MyFalseDownIcon";
initObject.trueUpIcon = "MyTrueUpIcon";
createClassObject(mx.controls.Button, "ButtonInstance", 0, initObject);

For more information, see About skinning components, and UIObject.createClassObject().

If a button is enabled, it displays its over state when the pointer moves over it. The button receives input focus and displays its down state when it's clicked. The button returns to its over state when the mouse is released. If the pointer moves off the button while the mouse is pressed, the button returns to its original state and it retains input focus. If the toggle parameter is set to true, the state of the button does not change until the mouse is released over it.

If a button is disabled it displays its disabled state, regardless of user interaction.

A Button component uses the following skin properties:

Property | Description
falseUpSkin | The up state. The default value is RectBorder.
falseDownSkin | The pressed state. The default value is RectBorder.
falseOverSkin | The over state. The default value is RectBorder.
falseDisabledSkin | The disabled state. The default value is RectBorder.
trueUpSkin | The toggled state. The default value is RectBorder.
trueDownSkin | The pressed-toggled state. The default value is RectBorder.
trueOverSkin | The over-toggled state. The default value is RectBorder.
trueDisabledSkin | The disabled-toggled state. The default value is RectBorder.
falseUpIcon | The icon up state. The default value is undefined.
falseDownIcon | The icon pressed state. The default value is undefined.
falseOverIcon | The icon over state. The default value is undefined.
falseDisabledIcon | The icon disabled state. The default value is undefined.
trueUpIcon | The icon toggled state. The default value is undefined.
trueOverIcon | The icon over-toggled state. The default value is undefined.
trueDownIcon | The icon pressed-toggled state. The default value is undefined.
trueDisabledIcon | The icon disabled-toggled state. The default value is undefined.


Button class

Inheritance UIObject > UIComponent > SimpleButton > Button

ActionScript Class Name mx.controls.Button

The properties of the Button class allow you to add an icon to a button, create a text label, or indicate whether the button acts as a push button, or a toggle switch at runtime.

Setting a property of the Button class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

The Button component uses the FocusManager to override the default Flash Player focus rectangle and draw a custom focus rectangle with rounded corners. For more information, see Creating custom focus navigation.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.Button.version);

Note: The following code returns undefined: trace(myButtonInstance.version);.

The Button component class is different from the ActionScript built-in Button object.

Method summary for the Button class

Inherits all methods from UIObject and UIComponent.

Property summary for the Button class

Method | Description
SimpleButton.emphasized | Indicates whether a button has the look of a default push button.
SimpleButton.emphasizedStyleDeclaration | The style declaration when the emphasized property is set to true.
Button.icon | Specifies an icon for a button instance.
Button.label | Specifies the text that appears within a button.
Button.labelPlacement | Specifies the orientation of the label text in relation to an icon.
Button.selected | When the toggle property is true, specifies whether the button is pressed (true) or not (false).
Button.toggle | Indicates whether the button behaves as a toggle switch.

Inherits all properties from UIObject and UIComponent.

Event summary for the Button class

Method | Description
Button.click | Broadcast when the mouse is pressed over a button instance or when the Spacebar is pressed.

Inherits all events from UIObject and UIComponent.


Button.click

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(click){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.click = function(eventObject){
  ...
}
buttonInstance.addEventListener("click", listenerObject)

Description

Event; broadcast to all registered listeners when the mouse is clicked (released) over the button or if the button has focus and the Spacebar is pressed.

The first usage example uses an on() handler and must be attached directly to a Button component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the Button component instance myButtonComponent, sends "_level0.myButtonComponent" to the Output panel:

on(click){
  trace(this);
}

Please note that this differs from the behavior of this when used inside an on() handler attached to a regular Flash button symbol. When this is used inside an on() handler attached to a button symbol, it refers to the Timeline that contains the button. For example, the following code, attached to the button symbol instance myButton, sends "_level0" to the Output panel:

on(release){
  trace(this);
}

Note: The built-in ActionScript Button object doesn't have a click event; the closest event is release.

The second usage example uses a dispatcher/listener event model. A component instance (buttonInstance) dispatches an event (in this case, click) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. The event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the addEventListener() method (See UIEventDispatcher.addEventListener()) on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when a button called buttonInstance is clicked. The first line of code labels the button. The second line specifies that the button act like a toggle switch. The third line creates a listener object called form. The fourth line defines a function for the click event on the listener object. Inside the function is a trace action that uses the event object that is automatically passed to the function (in this example, eventObj), to generate a message. The target property of an event object is the component that generated the event (in this example, buttonInstance). The Button.selected property is accessed from the event object's target property. The last line calls the addEventListener() method from buttonInstance and passes it the click event and the form listener object as parameters, as in the following:

buttonInstance.label = "Click Test"
buttonInstance.toggle = true;
form = new Object();
form.click = function(eventObj){
  trace("The selected property has changed to " + eventObj.target.selected);
}
buttonInstance.addEventListener("click", form);

The following code also sends a message to the Output panel when buttonInstance is clicked. The on() handler must be attached directly to buttonInstance, as in the following:

on(click){
  trace("button component was clicked");
}

See also

UIEventDispatcher.addEventListener()


SimpleButton.emphasized

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

buttonInstance.emphasized

Description

Property; indicates whether the button is in an emphasized state (true) or not (false). The emphasized state is equivalent to the looks if a default push button. In general, use the FocusManager.defaultPushButton property instead of setting the emphasized property directly. The default value is false.

The emphasized property is a static property of the SimpleButton class. Therefore, you must access it directly from SimpleButton, as in the following:

SimpleButton.emphasizedStyleDeclaration = "foo";

If you aren't using FocusManager.defaultPushButton, you might just want to set a button to the emphasized state, or use the emphasized state to change text from one color to another. The following example, sets the emphasized property for the button instance, myButton:

_global.styles.foo = new CSSStyleDeclaration();
_global.styles.foo.color = 0xFF0000;
SimpleButton.emphasizedStyleDeclaration = "foo";
myButton.emphasized = true;

See also

SimpleButton.emphasizedStyleDeclaration


SimpleButton.emphasizedStyleDeclaration

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

buttonInstance.emphasizedStyleDeclataion

Description

Property; a string indicating the style declaration that formats a button when the emphasized property is set to true.

See also

SimpleButton.emphasized


Button.icon

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

buttonInstance.icon

Description

Property; A string that specifies the linkage identifier of a symbol in the library to be used as an icon for a button instance. The icon can be a movie clip symbol or a graphic symbol with an upper left registration point. You must resize the button if the icon is too large to fit; neither the button nor the icon will resize automatically. If an icon is larger than a button, the icon will extend over the borders of the button.

To create a custom icon, create a movie clip or graphic symbol. Select the symbol on the Stage in symbol-editing mode and enter 0 in both the X and Y boxes in the Property inspector. In the Library panel, select the movie clip and select Linkage from the Options menu. Select Export for ActionScript, and enter an identifier in the Identifier text box.

The default value is an empty string (""), which indicates that there is no icon.

Use the labelPlacement property to set the position of the icon in relation to the button.

Example

The following code assigns the movie clip from the Library panel with the linkage identifier happiness to the Button instance as an icon:

myButton.icon = "happiness"

See also

Button.labelPlacement


Button.label

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

buttonInstance.label

Description

Property; specifies the text label for a button instance. By default, the label appears centered on the button. Calling this method overrides the label authoring parameter specified in the Property inspector or the Component Inspector panel. The default value is "Button".

Example

The following code sets the label to "Remove from list":

buttonInstance.label = "Remove from list";

See also

Button.labelPlacement


Button.labelPlacement

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

buttonInstance.labelPlacement

Description

Property; sets the position of the label in relation to the icon. The default value is "right". The following are the four possible values, the icon and label are always centered vertically and horizontally within the bounding area of the button:

  • "right" The label is set to the right of the icon.
  • "left" The label is set to the left of the icon.
  • "bottom" The label is set below the icon.
  • "top" The label is placed below the icon.

Example

The following code sets the label to the left of the icon. The second line of the code sends the value of the labelPlacement property to the Output panel:

iconInstance.labelPlacement = "left";
trace(iconInstance.labelPlacement);


Button.selected

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

buttonInstance.selected

Description

Property; a Boolean value specifying whether a button is pressed (true) or not (false). The value of the toggle property must be true to set the selected property to true. If the toggle property is false, assigning a value of true to the selected property has no effect. The default value is false.

The click event is not triggered when the value of the selected property changes with ActionScript. It is triggered when a user interacts with the button.

Example

In the following example, the toggle property is set to true and the selected property is set to true which puts the button in a pressed state. The trace action sends the value true to the Output panel:

ButtonInstance.toggle = true; // toggle needs to be true in order to set the selected property
ButtonInstance.selected = true; //displays the toggled state of the button
trace(ButtonInstance.selected); //traces- true

See also

Button.toggle


Button.toggle

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

buttonInstance.toggle

Description

Property; a Boolean value specifying whether a button acts like a toggle switch (true) or a push button (false); the default value is false. When a toggle switch is pressed, it stays in a pressed state until it's clicked again.

Example

The following code sets the toggle property to true, which makes the myButton instance behave like a toggle switch:

myButton.toggle = true;


About the CellRenderer API

The CellRenderer API is a set of properties and methods that the List-based components (List, DataGrid, Tree, and Menu) use to manipulate and display custom cell content for each of their rows. This customized cell can contain a prebuilt component, such as a CheckBox, or any class you create.

See also:

  • Understanding the List class
  • Using the CellRenderer API


Understanding the List class

To use the CellRenderer API it is important to have an advanced understanding of the List class. The DataGrid, Tree, and Menu components are extension of the List class, so understanding the List class allows you to understand them as well.

Note: A component is a class but a class isn't necessarily a component.

See also:

  • About the composition of the List class
  • About the scrolling behavior of the List class

About the composition of the List class

List classes are composed of rows. These rows display rollover and selection highlights, are used as hit states for row selection, and play a vital part in scrolling. Aside from selection highlights and icons (such as the node icons and expander arrows of a Tree component), a row consists of one cell (or, in the case of the DataGrid, many cells). In the default case, these cells are TextField objects that implement the CellRenderer API. However, you can tell a List to use a different class of component as the cell for each row. The only requirement is that the class must implement the CellRenderer API, which the List uses for communicating with the cell.

The stacking order of a row in a List or DataGrid component.

Note: If a cell has button event handlers (onPress and so on) the background hit area may not receive input necessary to trigger the events.

About the scrolling behavior of the List class

List classes use a fairly complex algorithm to scroll. A list only lays out as many rows as it can display at once; items beyond the value of the rowCount property don't get rows at all. When the list scrolls, it moves all the rows up or down (depending on the scrolling direction). The list then recycles the rows that are scrolled out of view; it reinitializes them and uses them for the new rows being scrolled into view by setting the value of the old row to the new item in the view and moving the old row to where the new item is scrolled into view.

Because of this scrolling behavior, you cannot expect a cell to be used for only one value. Because rows are recycled, it is the responsibility of the cell renderer to know how to completely reset its state when it is set to a new value. For example, if your cell renderer creates an icon to display one item, it might need to remove that icon when another item is rendered with it. Assume your cell renderer is a container that will be filled with numerous item values over time, and it has to know how to completely change itself from displaying one value to displaying another. In fact, your cell should even know how to properly render undefined items, which might mean removing all old content in the cell.


Using the CellRenderer API

You must write a class with four methods (CellRenderer.getPreferredHeight(), CellRenderer.getPreferredWidth(), CellRenderer.setSize(), CellRenderer.setValue()) that the List-based component uses to communicate with the cell.

There are two methods and a property (CellRenderer.getCellIndex(), CellRenderer.getDataLabel(), and CellRenderer.listOwner) that are given automatically to a cell to allow it to communicate with the List-based component. For example, say a cell has a check box within it that causes a row to be selected when it's clicked. The cell renderer needs a reference to the List-based component that contains it in order to call the selectedIndex property of the List-based component. Also, the cell needs to know which item index it is currently rendering so that it can set selectedIndex to the correct number; the cell can use CellRenderer.listOwner and CellRenderer.getCellIndex() to do so. You do not need to implement these APIs; the cell receives them automatically when it is placed inside the List-based component.

Methods to implement for the CellRenderer API

You must write a class with the following methods so that the List, DataGrid, Tree, or Menu, can communicate with the cell:

Name | Description
CellRenderer.getPreferredHeight() | Returns the preferred height of a cell.
CellRenderer.getPreferredWidth() | Returns the preferred width of a cell.
CellRenderer.setSize() | Sets the width and height of a cell.
CellRenderer.setValue() | Sets the content to be displayed in the cell.

Methods provided by the CellRenderer API

The following are the methods that the List, DataGrid, Tree, and Menu give to the cell when it is created within the component. You do not need to implement these methods.

Name | Description
CellRenderer.getDataLabel() | Returns a string containing the name of the cell renderer's data field.
CellRenderer.getCellIndex() | Returns an object with two fields, columnIndex and rowIndex, that indicate the position of the cell.

Properties provided by the CellRenderer API

The following is the property that the List, DataGrid, Tree, and Menu give to the cell when it is created within the component. You do not need to implement this property.

Name | Description
CellRenderer.listOwner | A reference to the List that contains the cell.


CellRenderer.getDataLabel()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.getDataLabel()

Parameters

None.

Returns

A string.

Description

Method; returns a string containing the name of the cell renderer's data field.

Example

The following code helps the cell discover that it's rendering the data field "Price". The variable p is now equal to "Price":

var p = getDataLabel();


CellRenderer.getCellIndex()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.getCellIndex()

Parameters

None.

Returns

An object with two fields: columnIndex and itemIndex.

Description

Method; returns an object with two fields, columnIndex and itemIndex, that locate the cell in the grid. Each field is an integer that indicates a cell's column position and item position. For any components other than the DataGrid, the value of columnIndex is always 0.

Example

This example edits a DataGrid's dataProvider from within a cell:

var index = getCellIndex();
var colName = listOwner.getColumnAt(index.columnIndex).columnName;
listOwner.dataProvider.editField(index.itemIndex, colName, someVal);


CellRenderer.getPreferredHeight()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.getPreferredHeight()

Parameters

None.

Returns

The correct height for the cell.

Description

Method; the preferred height of a cell. This is especially important for getting the right height of text within the cell. If you set this value higher than the rowHeight property of the component, cells will bleed above and below the rows.

Example

This example returns the value 20, which indicates that the cell wants to be 20 pixels high:

function getPreferredHeight(Void) :Number
{
   return 20;
}


CellRenderer.getPreferredWidth()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.getPreferredWidth()

Parameters

None.

Returns

Nothing.

Description

Method; the preferred width of a cell. If you specify more width than the component has, the cell may be cut off.

Example

This example returns the value 3, which indicates that the cell wants to be three times as big as the length of the string it is rendering:

function getPreferredWidth(Void) : Number
{
   return myString.length*3;
}


CellRenderer.listOwner

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.listOwnner

Description

Property; a reference to the list that owns the cell. That list can be a DataGrid, Tree, or List.

Example

This example finds the list's selected item in a cell:

var s = listOwner.selectedItem;


CellRenderer.setSize()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.setSize(width, height)

Parameters

width A number that indicates the width at which to lay out the component.

height A number that indicates the height at which to lay out the component.

Returns

Nothing.

Description

Method; allows the list to tell its cells at what size they should lay themselves out. The CellRenderer should do layout so that it fits within the area described, or visual display from the cell may bleed into other parts of the list and appear broken.

Example

This example sizes an image within the cell to fit within the bounds specified by the list:

function setSize(w:Number, h:Number) : Void
{
   image._width = w-2;
   image._height = w-2;
   image._x = image._y = 1;
}


CellRenderer.setValue()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.setValue(suggested, item, selected)

Parameters

suggested A value to be used for the cell renderer's text, if any is needed.

item An object that is the entire item to be rendered. The cell renderer can use any properties of this object it wants for rendering.

selected A Boolean value that indicates whether the row the cell is on is selected (true) or not (false).

Returns

Nothing.

Description

Method; takes the values given and creates a representation of them within the cell. This clears up any difference in what was displayed in the cell and what needs to be displayed in the cell for the new item. It is important to remember that any cell could display many values during its time in the list. This is the most important method in any cell renderer.

Example

This example loads an image in a loader component within the cell, depending on the value passed:

function setValue(suggested, item, selected) : Void
{
   //clear the loader
   loader.contentPath = undefined;
   // the list has URLs for different images in its data provider
   if (suggested!=undefined)
   loader.contentPath = suggested;
}


About the CheckBox component

A check box is a square box that can be either selected or deselected. When it is selected, a check appears in the box. You can add a text label to a check box and place it to the left, right, top, or bottom.

A check box can be enabled or disabled in an application. If a check box is enabled and a user clicks it or its label, the check box receives input focus and displays its pressed appearance. If a user moves the pointer outside the bounding area of a check box or its label while pressing the mouse button, the component's appearance returns to its original state and it retains input focus. The state of a check box does not change until the mouse is released over the component. Additionally, the checkbox has two disabled states, selected and deselected, which do not allow mouse or keyboard interaction.

If a check box is disabled it displays its disabled appearance, regardless of user interaction. In the disabled state, a button doesn't receive mouse or keyboard input.

A CheckBox instance receives focus if a user clicks it or tabs to it. When a CheckBox instance has focus, you can use the following keys to control it:

Key | Description
Shift + Tab | Moves focus to the previous element.
Spacebar | Selects or deselects the component and triggers the click event.
Tab | Moves focus to the next element.

For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each CheckBox instance reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring.

When you add the CheckBox component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility:

mx.accessibility.CheckBoxAccImpl.enableAccessibility();

You only enable accessibility for a component once no matter how many instances you have of the component. For more information, see Creating Accessible Content.


Using the CheckBox component

A check box is a fundamental part of any form or web application. You can use check boxes wherever you need to gather a set of true or false values that aren't mutually exclusive. For example, a form collecting personal information about a customer could have a list of hobbies for the customer to select; each hobby would have a check box beside it.

See also:

  • CheckBox parameters
  • Creating an application with the CheckBox component
  • Using styles with the CheckBox component
  • Using skins with the CheckBox component

CheckBox parameters

The following are authoring parameters that you can set for each CheckBox component instance in the Property inspector or in the Component Inspector panel:

label sets the value of the text on the check box; the default value is defaultValue.

selected sets the initial value of the check box to checked (true) or unchecked (false).

labelPlacement orients the label text on the check box. This parameter can be one of four values: left, right, top, or bottom; the default value is right. For more information, see CheckBox.labelPlacement.

You can write ActionScript to control these and additional options for CheckBox components using its properties, methods, and events. For more information, see CheckBox class.

Creating an application with the CheckBox component

The following procedure explains how to add a CheckBox component to an application while authoring. The following example is a form for an online dating application. The form is a query that searches for possible dating matches for the customer. The query form must have a check box labeled "Restrict Age" permitting the customer to restrict his or her search to a specified age group. When the "Restrict Age" check box is selected, the customer can then enter the minimum and maximum ages into two text fields that are enabled only when "Restrict Age" is selected.

To create an application with the CheckBox component, do the following:

  1. Drag two TextInput components from the Components panel to the Stage.
  2. In the Property inspector, enter the instance names minimumAge and maximumAge.
  3. Drag a CheckBox component from the Components panel to the Stage.
  4. In the Property inspector, do the following:
    • Enter restrictAge for the instance name.
    • Enter Restrict Age for the label parameter.
  5. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code:
    restrictAgeListener = new Object();
restrictAgeListener.click = function (evt){
  minimumAge.enabled = evt.target.selected;
  maximumAge.enabled = evt.target.selected;
}
restrictAge.addEventListener("click", restrictAgeListener);

    This code creates a click event handler that enables and disables the minimumAge and maximumAge text field components, that have already been placed on Stage. For more information about the click event, see CheckBox.click. For more information about the TextInput component, see TextInput component.


Customizing the CheckBox component

You can transform a CheckBox component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (UIObject.setSize()) or any applicable properties and methods of the CheckBox class (see CheckBox class). Resizing the check box does not change the size of the label or the check box icon; it only changes the size of the bounding box.

The bounding box of a CheckBox instance is invisible and also designates the hit area for the instance. If you increase the size of the instance, you also increase the size of the hit area. If the bounding box is too small to fit the label, the label clips to fit.

Using styles with the CheckBox component

You can set style properties to change the appearance of a CheckBox instance. If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

A CheckBox component that uses the Halo theme supports the following styles:

Style | Description
themeColor | The background of a component. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style: either "normal", or "italic".
fontWeight | The font weight: either "normal", or "bold".
textDecoration | The text decoration: either "none", or "underline".

Using skins with the CheckBox component

The CheckBox component uses symbols in the Library panel to represent the button states. To skin the CheckBox component while authoring, modify symbols in the Library panel. The CheckBox component skins are located in the Flash UI Components 2/Themes/MMDefault/CheckBox Assets/states folder in the library of either the HaloTheme.fla file or the SampleTheme.fla file. For more information, see About skinning components.

A CheckBox component uses the following skin properties:

Property | Description
falseUpSkin | The up state. Default is RectBorder.
falseDownSkin | The pressed state. Default is RectBorder.
falseOverSkin | The over state. Default is RectBorder.
falseDisabledSkin | The disabled state. Default is RectBorder.
trueUpSkin | The toggled state. Default is RectBorder.
trueDownSkin | The pressed-toggled state. Default is RectBorder.
trueOverSkin | The over-toggled state. Default is RectBorder.
trueDisabledSkin | The disabled-toggled state. Default is RectBorder.


CheckBox class

Inheritance UIObject > UIComponent > SimpleButton > Button > CheckBox

ActionScript Class Name mx.controls.CheckBox

The properties of the CheckBox class allow you to create a text label and position it to the left, right, top, or bottom of a check box at runtime.

Setting a property of the CheckBox class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

The CheckBox component uses the FocusManager to override the default Flash Player focus rectangle and draw a custom focus rectangle with rounded corners. For more information, see Creating custom focus navigation.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.CheckBox.version);

Note: The following code returns undefined: trace(myCheckBoxInstance.version);.

Method summary for the CheckBox class

Inherits all methods from UIObject and UIComponent.

Property summary for the CheckBox class

Property | Description
CheckBox.label | Specifies the text that appears next to a check box.
CheckBox.labelPlacement | Specifies the orientation of the label text in relation to a check box.
CheckBox.selected | Specifies whether the check box is selected (true) or deselected (false).

Inherits all properties from UIObject and UIComponent.

Event summary for the CheckBox class

Event | Description
CheckBox.click | Triggered when the mouse is pressed over a button instance.

Inherits all events from UIObject and UIComponent.


CheckBox.click

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(click){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.click = function(eventObject){
  ...
}
checkBoxInstance.addEventListener("click", listenerObject)

Description

Event; broadcast to all registered listeners when the mouse is clicked (released) over the check box or if the check box has focus and the Spacebar is pressed.

The first usage example uses an on() handler and must be attached directly to a CheckBox component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the check box myCheckBox, sends "_level0.myCheckBox" to the Output panel:

on(click){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (checkBoxInstance) dispatches an event (in this case, click) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. The event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the addEventListener() method (see UIEventDispatcher.addEventListener()) on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when a button called checkBoxInstance is clicked. The first line of code creates a listener object called form. The second line defines a function for the click event on the listener object. Inside the function is a trace action that uses the event object that is automatically passed to the function (in this example, eventObj) to generate a message. The target property of an event object is the component that generated the event (in this example, checkBoxInstance). The CheckBox.selected property is accessed from the event object's target property. The last line calls the addEventListener() method from checkBoxInstance and passes it the click event and the form listener object as parameters, as in the following:

form = new Object();
form.click = function(eventObj){
  trace("The selected property has changed to " + eventObj.target.selected);
}
checkBoxInstance.addEventListener("click", form);

The following code also sends a message to the Output panel when checkBoxInstance is clicked. The on() handler must be attached directly to checkBoxInstance, as in the following:

on(click){
  trace("check box component was clicked");
}

See also

UIEventDispatcher.addEventListener()


CheckBox.label

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

checkBoxInstance.label

Description

Property; indicates the text label for the check box. By default, the label appears to the right of the check box. Setting this property overrides the label parameter specified in the clip parameters panel.

Example

The following code sets the text that appears beside the CheckBox component and sends the value to the Output panel:

checkBox.label = "Remove from list";
trace(checkBox.label)

See also

CheckBox.labelPlacement


CheckBox.labelPlacement

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

checkBoxInstance.labelPlacement

Description

Property; a string that indicates the position of the label in relation to the check box. The following are the four possible values (the dotted lines represent the bounding area of the component; they are invisible in a document):

  • "right" The check box is pinned to the upper left corner of the bounding area. The label is set to the right of the check box. This is the default value.

  • "left" The check box is pinned to the top right corner of the bounding area. The label is set to the left of the check box.

  • "bottom" The label is set below the check box. The check box and label grouping are centered horizontally and vertically.

  • "top" The label is placed below the check box. The check box and label grouping are centered horizontally and vertically.

    You can change the bounding area of component while authoring by using the Transform command or at runtime using the UIObject.setSize() property. For more information, see Customizing the CheckBox component.

Example

The following example sets the placement of the label to the left of the check box:

checkBox_mc.labelPlacement = "left";

See also

CheckBox.label


CheckBox.selected

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

checkBoxInstance.selected

Description

Property; a Boolean value that selects (true) or deselects (false) the check box.

Example

The following example selects the instance checkbox1:

checkbox1.selected = true;


About the Collection interface

The Collection interface allows you to programmatically manage a group of related items, called collection items. In addition, the Collection interface is inspectable. Components can expose properties as collections, which can then be manipulated during authoring using the Values editor. For more on Collections and collection items, see Collection.


Using the Collection interface

You typically use the Collection interface with components that use the Collection metadata keyword to establish Collection properties. While you can create, access, and delete Collection instances programmatically, collections are most often used in the context of a component. Flash MX Professional 2004 provides implementations of both collection-related interfaces (CollectionImpl for Collection, and IteratorImpl for Iterator).

ActionScript Class Name mx.utils.Collection

Method summary for the Collection interface

Method | Description
Collection.addItem() | Adds a new item to the end of the collection.
Collection.contains() | Indicates whether the collection contains the specified item.
Collection.clear() | Removes all elements from the collection.
Collection.getItemAt() | Returns an item within the collection using its index.
Collection.getIterator() | Returns an iterator to the elements in the collection.
Collection.getLength() | Returns the number of items in the collection.
Collection.isEmpty() | Indicates whether the collection is empty.
Collection.removeItem() | Removes the specified item from the collection.


Collection.addItem()

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

collection.addItem(item)

Parameters

item Object to be added to the collection. If item is null it is not added to the collection.

Returns

A Boolean value that contains true if the collection was changed as a result of the operation.

Description

Method; adds a new item to the end of the collection.

Example

The following example calls the addItem() method:

on (click) {
import CompactDisk;

  var myColl:mx.utils.Collection;
  myColl = _parent.thisShelf.MyCompactDisks;
  myCD = new CompactDisk();
  myCD.Artist = "John Coltrane";
  myCD.Title = "Giant Steps";

  var wasAdded:Boolean = myColl.addItem(myCD);
}


Collection.contains()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

collection.contains(item)

Parameters

item Object whose presence in the collection is to be tested.

Returns

A Boolean value that contains true if the collection contains item.

Description

Method; indicates whether the collection contains the specified item. For Flash to consider the objects as equal, they must refer to the same object. If item is a different object, Collection.contains() returns false, even if the object's properties are all equal.

Example

The following example calls the contains() method:

//...
var myColl:mx.utils.Collection;
myColl = _parent.thisShelf.MyCompactDisks;

var itr:mx.utils.Iterator = myColl.getIterator();
while (itr.hasNext()) {
  var cd:CompactDisk = CompactDisk(itr.next());
  var title:String = cd.Title;
  var artist:String = cd.Artist;

  if(myColl.contains(cd)) {
    trace("myColl contains " + title);
  }
  else {
    trace("myColl does not contain " + title);
  }
//...


Collection.clear()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

collection.clear()

Returns

Nothing.

Description

Method; removes all of the elements from the collection.

Example

The following example calls the clear() method:

on (click) {
  var myColl:mx.utils.Collection;
  myColl = _parent.thisShelf.MyCompactDisks;
  myColl.clear();
}


Collection.getItemAt()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

collection.getItemAt(index)

Parameters

index Number indicating the location of item within the collection. This is a zero-based index, so 0 retrieves the first item, 1 retrieves the second item, and so on.

Returns

An object containing a reference to the specified collection item or null if index is out of bounds.

Description

Method; returns an item within the collection using its index.

Example

The following example calls the getItemAt() method:

//...
  var myColl:mx.utils.Collection;
  myColl = _parent.thisShelf.MyCompactDisks;
  var myCD = CompactDisk(myColl.getItemAt(0));
  if (myCD !=null) {
    trace("Retrieved " + myCD.Title);
  }
//...


Collection.getIterator()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

collection.getIterator()

Returns

An Iterator object that you can use to step through the collection.

Description

Method; returns an Iterator over the elements in the collection. There are no guarantees concerning the order in which the elements are returned (unless this collection is an instance of a class that provides a guarantee).

Example

The following example calls the getIterator() method:

on (click) {
  var myColl:mx.utils.Collection;
  myColl = _parent.thisShelf.MyCompactDisks;

  var itr:mx.utils.Iterator = myColl.getIterator();
  while (itr.hasNext()) {
    var cd:CompactDisk = CompactDisk(itr.next());
    var title:String = cd.Title;
    var artist:String = cd.Artist;

    trace("Title: " + title + " - Artist: " + artist);
  }
}


Collection.getLength()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

collection.getLength()

Returns

The number of items in the collection.

Description

Method; returns the number of items in the collection.

Example

The following example calls the getLength() method:

//...
var myColl:mx.utils.Collection;
myColl = _parent.thisShelf.MyCompactDisks;
trace ("Collection size is: " + myColl.getLength());
//...


Collection.isEmpty()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

collection.isEmpty()

Returns

A Boolean value that contains true if the collection is empty.

Description

Method; indicates whether the collection is empty.

Example

The following example calls the isEmpty() method:

on (click) {
  var myColl:mx.utils.Collection;
  myColl = _parent.thisShelf.MyCompactDisks;
  if (myColl.isEmpty()) {
    trace("No CDs in the collection");
  }
//...


Collection.removeItem()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

collection.removeItem(item)

Parameters

item Object containing the item to be removed from this collection.

Returns

A Boolean value that contains true if item was removed successfully.

Description

Method; removes the specified item from the collection. Because Collection.removeItem() dynamically reduces the size of the Collection, do not call this method while looping through an Iterator.

Example

The following example calls the removeItem() method:

//...
  var myColl:mx.utils.Collection;
  myColl = _parent.thisShelf.MyCompactDisks;

  // Get this from a text input box.
  var removeArtist:String = _parent.tArtistToRemove.text;
  var removeSize:Number = 0;

  if (myColl.isEmpty()) {
    trace("No CDs in the collection");
  }
  else {
    var toRemove:Array = new Array();
    var itr:mx.utils.Iterator = myColl.getIterator();
    var cd:CompactDisk = new CompactDisk();
    var title:String = "";
    var artist:String = "";
    while (itr.hasNext()) {
      cd = CompactDisk(itr.next());
      title = cd.Title;
      artist = cd.Artist;
      if(artist == removeArtist) {
        // Mark this artist for deletion
        removeSize = toRemove.push(cd);
        trace("*** Marked for deletion: " + artist + "|" + title);
      }
    }
    // After while loop, remove the bad ones.
    var removeCD:CompactDisk = new CompactDisk();
    for(i = 0; i < removeSize; i++) {
      removeCD = toRemove[i];
      trace("Removing: " + removeCD.Artist + "|" + removeCD.Title);
      myColl.removeItem(removeCD);
    }
  }

}


About the ComboBox component

A combo box can be static or editable. A static combo box allows a user to make a single selection from a drop-down list. An editable combo box allows a user to enter text directly into a text field at the top of the list, as well as selecting an item from a drop-down list. If the drop-down list hits the bottom of the document, it opens up instead of down. The combo box is composed of three subcomponents: a Button component, a TextInput component, and a List component.

When a selection is made in the list, the label of the selection is copied to the text field at the top of the combo box. It doesn't matter if the selection is made with the mouse or the keyboard.

A ComboBox component receives focus if you click the text box or the button. When a ComboBox component has focus and is editable, all keystrokes go to the text box and are handled according to the rules of the TextInput component (see TextInput component), with the exception of the following keys:

Key | Description
Control+Down | Opens the drop-down list and gives it focus.
Shift +Tab | Moves focus to the previous object.
Tab | Moves focus to the next object.

When a ComboBox component has focus and is static, alphanumeric keystrokes move the selection up and down the drop-down list to the next item with the same first character. You can also use the following keys to control a static combo box:

Key | Description
Control+Down | Opens the drop-down list and gives it focus.
Control+Up | Closes the drop-down list, if open in the Stand alone and Browser versions of the Flash Player.
Down | Selection moves down one item.
End | Selection moves to the bottom of the list.
Escape | Closes the drop-down list and returns focus to the combo box in Test Movie mode.
Enter | Closes the drop-down list and returns focus to the combo box.
Home | Selection moves to the top of the list.
Page Down | Selection moves down one page.
Page Up | Selection moves up one page.
Shift +Tab | Moves focus to the previous object.
Tab | Moves focus to the next object.

When the drop-down list of a combo box has focus, alphanumeric keystrokes move the selection up and down the drop-down list to the next item with the same first character. You can also use the following keys to control a drop-down list:

Key | Description
Control+Up | If the drop-down list is open, focus returns to the text box and the drop-down list closes in the Stand alone and Browser versions of the Flash Player.
Down | Selection moves down one item.
End | The insertion point moves to the end of the text box.
Enter | If the drop-down list is open, focus returns to the text box and the drop-down list closes.
Escape | If the drop-down list is open, focus returns to the text box and the drop-down list closes in Test Movie mode.
Home | The insertion point moves to the beginning of the text box.
Page Down | Selection moves down one page.
Page Up | Selection moves up one page.
Tab | Moves focus to the next object.
Shift-End | Selects the text from the insertion point to the End position.
Shift-Home | Selects the text from the insertion point to the Home position.
Shift-Tab | Moves focus to the previous object.
Up | Selection moves up one item.

Note: The page size used by the Page Up and Page Down keys is one less than the number of items that fit in the display. For example, paging down through a ten-line drop-down list will show items 0-9, 9-18, 18-27, and so on, with one item overlapping per page.

For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each ComboBox component instance on the Stage reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring. However, the drop-down list does not open in the live preview and the first item displays as the selected item.

When you add the ComboBox component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility:

mx.accessibility.ComboBoxAccImpl.enableAccessibility();

You only enable accessibility for a component once no matter how many instances you have of the component. For more information, see Creating Accessible Content.


Using the ComboBox component

You can use a ComboBox component in any form or application that requires a single choice from a list. For example, you could provide a drop-down list of states in a customer address form. You can use an editable combo box for more complex scenarios. For example, in a driving directions application you could use an editable combo box for a user to enter her origin and destination addresses. The drop-down list would contain her previously entered addresses.

See also:

  • ComboBox parameters
  • Creating an application with the ComboBox component
  • Using styles with the ComboBox component
  • Using skins with the ComboBox component
  • Customizing the ComboBox component
  • ComboBox class

ComboBox parameters

The following are authoring parameters that you can set for each ComboBox component instance in the Property inspector or in the Component Inspector panel:

editable determines if the ComboBox component is editable (true) or only selectable (false). The default value is false.

labels populates the ComboBox component with an array of text values.

data associates a data value with each item in the ComboBox component. The data parameter is an array.

rowCount sets the maximum number of items that can be displayed at one time without using a scroll bar. The default value is 5.

You can write ActionScript to set additional options for ComboBox instances using the methods, properties, and events of the ComboBox class. For more information, see ComboBox class.

Creating an application with the ComboBox component

The following procedure explains how to add a ComboBox component to an application while authoring. In this example, the combo box presents a list of cities to select from in its drop-down list.

To create an application with the ComboBox component, do the following:

  1. Drag a ComboBox component from the Components panel to the Stage.
  2. Select the Transform tool and resize the component on the Stage.

    The combo box can only be resized on the Stage while authoring. Typically, you would only change the width of a combo box to fit its entries.

  3. Select the combo box and, in the Property inspector, enter the instance name comboBox.
  4. In the Component Inspector panel or the Property inspector, do the following:
    • Enter Minneapolis, Portland, and Keene for the label parameter. Double-click the label parameter field to open the Values dialog. Then click the plus sign to add items.
    • Enter MN.swf, OR.swf, and NH.swf for the data parameter.

      These are imaginary SWF files that, for example, you could load when a user selects a city from the combo box.

  5. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code:
    form = new Object();
form.change = function (evt){
  trace(evt.target.selectedItem.label);
}
comboBox.addEventListener("change", form);

    The last line of code adds a change event handler to the ComboBox instance. For more information, see ComboBox.change.


Customizing the ComboBox component

You can transform a ComboBox component horizontally and vertically while authoring. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands.

If text is too long to fit in the combo box, the text clips to fit. You must resize the combo box while authoring to fit the label text.

In editable combo boxes, only the button is the hit area—not the text box. For static combo boxes, the button and the text box constitute the hit area.

Using styles with the ComboBox component

You can set style properties to change the appearance of a ComboBox component. If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

The combo box has two unique styles. Other styles are passed to the button, text box, and drop-down list of the combo box through those individual components, as follows:

  • The button is a Button instance and uses its styles. (See Using styles with the Button component.)
  • The text is a TextInput instance and uses its styles. (See Using styles with the TextInput component.)
  • The drop-down list is an List instance and uses its styles. (See Using styles with the List component.)

A ComboBox component uses the following Halo styles:

Style | Description
themeColor | The background of a component. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style: either "normal", or "italic".
fontWeight | The font weight: either "normal", or "bold".
textDecoration | The text decoration: either "none", or "underline".
openDuration | The number of milliseconds to open the drop-down list. The default value is 250.
openEasing | A reference to a tweening function that controls the drop-down list animation. Defaults to sine in/out. For more equations, download a list from Robert Penner's website at www.robertpenner.com/easing/.

Using skins with the ComboBox component

The ComboBox component uses symbols in the Library panel to represent the button states. The ComboBox has skin variables for the down arrow. Other than that, it uses scroll bar and list skins. To skin the ComboBox component while authoring, modify symbols in the Library panel and re-export the component as a SWC. The CheckBox component skins are located in the Flash UI Components 2/Themes/MMDefault/ComboBox Assets/states folder in the library of either the HaloTheme.fla file or the SampleTheme.fla file. For more information, see About skinning components.

A ComboBox component uses the following skin properties:

Property | Description
ComboDownArrowDisabledName | The down arrow's disabled state. Default is RectBorder.
ComboDownArrowDownName | The down arrow's down state. Default is RectBorder.
ComboDownArrowUpName | The down arrow's up state. Default is RectBorder.
ComboDownArrowOverName | The down arrow's over state. Default is RectBorder.


ComboBox class

Inheritance UIObject > UIComponent > ComboBase > ComboBox

ActionScript Class Name mx.controls.ComboBox

The ComboBox component combines three separate subcomponents: Button, TextInput, and List. Most of the APIs of each subcomponent are available directly from ComboBox component and are listed in the Method, Property, and Event tables for the ComboBox class.

The drop-down list in a combo box is provided either as an Array or as a DataProvider object. If you use a DataProvider object, the list changes at runtime. The source of the ComboBox data can be changed dynamically by switching to a new Array or DataProvider object.

Items in a combo box list are indexed by position, starting with the number 0. An item can be one of the following:

  • A primitive data type.
  • An object that contains a label property and a data property.

    Note: An object may use the ComboBox.labelFunction or ComboBox.labelField property to determine the label property.

If the item is a primitive data type other than string, it is converted to a string. If an item is an object, the label property must be a string and the data property can be any ActionScript value.

ComboBox component methods to which you supply items have two parameters, label and data, that refer to the properties above. Methods that return an item return it as an Object.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.ComboBox.version);

Note: The following code returns undefined: trace(myComboBoxInstance.version);.

Method summary for the ComboBox class

Property | Description
ComboBox.addItem() | Adds an item to the end of the list.
ComboBox.addItemAt() | Adds an item to the end of the list at the specified index.
ComboBox.close() | Closes the drop-down list.
ComboBox.getItemAt() | Returns the item at the specified index.
ComboBox.open() | Opens the drop-down list.
ComboBox.removeAll() | Removes all items in the list.
ComboBox.removeItemAt() | Removes an item from the list at the specified location.
ComboBox.replaceItemAt() | Replaces an item in the list with another specified item.

Inherits all methods from UIObject and UIComponent.

Property summary for the ComboBox class

Property | Description
ComboBox.dataProvider | The data model for the items in the list.
ComboBox.dropdown | Returns a reference to the List component contained by the combo box.
ComboBox.dropdownWidth | The width of the drop-down list, in pixels.
ComboBox.editable | Indicates whether or not a combo box is editable.
ComboBox.labelField | Indicates which data field to use as the label for the drop-down list.
ComboBox.labelFunction | Specifies a function to compute the label field for the drop-down list.
ComboBox.length | Read-only. The length of the drop-down list.
ComboBox.rowCount | The maximum number of list items to display at one time.
ComboBox.selectedIndex | The index of the selected item in the drop-down list.
ComboBox.selectedItem | The value of the selected item in the drop-down list.
ComboBox.text | The string of the text in the text box.
ComboBox.textField | A reference to the TextInput component in the combo box.
ComboBox.value | The value of the text box (editable) or drop-down list (static).

Inherits all properties from UIObject and UIComponent.

Event summary for the ComboBox class

Event | Description
ComboBox.change | Broadcast when the value of the combo box changes as a result of user interaction.
ComboBox.close | Broadcast when the drop-down list begins to close.
ComboBox.enter | Broadcast when the Enter key is pressed.
ComboBox.itemRollOut | Broadcast when the pointer rolls off a drop-down list item.
ComboBox.itemRollOver | Broadcast when a drop-down list item is rolled over.
ComboBox.open | Broadcast when the drop-down list begins to open.
ComboBox.scroll | Broadcast when the drop-down list is scrolled.

Inherits all events from UIObject and UIComponent.


ComboBox.addItem()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

comboBoxInstance.addItem(label[, data])

Usage 2:

comboBoxInstance.addItem({label:label[, data:data]})

Usage 3:

comboBoxInstance.addItem(obj);

Parameters

label A string that indicates the label for the new item.

data The data for the item; can be of any data type. This parameter is optional.

obj An object with a label property and an optional data property.

Returns

The index at which the item was added.

Description

Method; adds a new item to the end of the list.

Example

The following code adds an item to the myComboBox instance:

myComboBox.addItem("this is an Item");


ComboBox.addItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

comboBoxInstance.addItemAt(index, label[, data])

Parameters

index A number 0 or greater that indicates the position at which to insert the item (the index of the new item).

label A string that indicates the label for the new item.

data The data for the item; can be any data type. This parameter is optional.

Returns

The index at which the item was added.

Description

Method; adds a new item to the end of the list at the index specified by the index parameter. Indices greater than ComboBox.length are ignored.

Example

The following code inserts an item at index 3, which is the fourth position in the combo box list (0 is the first position):

myBox.addItemAt(3, "this is the fourth Item");


ComboBox.change

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(change){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.change = function(eventObject){
  // your code here
}
comboBoxInstance.addEventListener("change", listenerObject)

Description

Event; broadcast to all registered listeners when the value of the combo box changes as a result of user interaction.

The first usage example uses an on() handler and must be attached directly to a ComboBox component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox component instance myBox, sends "_level0.myBox" to the Output panel:

on(change){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the addEventListener() method (see UIEventDispatcher.addEventListener()) on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example sends the instance name of the component that generated the change event to the Output panel:

form.change = function(eventObj){
  trace("Value changed to " + eventObj.target.value);
}
myCombo.addEventListener("change", form);

See also

UIEventDispatcher.addEventListener()


ComboBox.close()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.close()

Parameters

None.

Returns

Nothing.

Description

Method; closes the drop-down list.

Example

The following example closes the drop-down list of the myBox combo box:

myBox.close();

See also

ComboBox.open()


ComboBox.close

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(close){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.close = function(eventObject){
  // your code here
}
comboBoxInstance.addEventListener("close", listenerObject)

Description

Event; broadcast to all registered listeners when the list of the combo box begins to retract.

The first usage example uses an on() handler and must be attached directly to a ComboBox component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox component instance myBox, sends "_level0.myBox" to the Output panel:

on(close){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, close) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example sends a message to the Output panel when the drop-down list begins to close:

form.close = function(){
  trace("The combo box has closed");
}
myCombo.addEventListener("close", form);

See also

UIEventDispatcher.addEventListener()


ComboBox.dataProvider

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

comboBoxInstance.dataProvider

Description

Property; the data model for items viewed in a list. The value of this property can be an array or any object that implements the DataProvider interface. The default value is []. This is a property of the List component but can be accessed directly from an instance of the ComboBox component.

The List component, and other data-aware components, add methods to the Array object's prototype so that they conform to the DataProvider interface (see DataProvider.as for details). Therefore, any array that exists at the same time as a list automatically has all the methods (addItem(), getItemAt(), and so on) needed for it to be the model of a list, and can be used to broadcast model changes to multiple components.

If the array contains objects, the labelField or labelFunction properties are accessed to determine what parts of the item to display. The default value is "label", so if such a field exists, it is chosen for display; if not, a comma separated list of all fields is displayed.

Note: If the array contains strings at each index, and not objects, the list is not able to sort the items and maintain the selection state. Any sorting will lose the selection.

Any instance that implements the DataProvider interface is eligible as a data provider for a List. This includes Flash Remoting RecordSets, Firefly DataSets, and so on.

Example

This example uses an array of strings to populate the drop-down list:

comboBox.dataProvider = ["Ground Shipping","2nd Day Air","Next Day Air"];

This example creates a data provider array and assigns it to the dataProvider property, as in the following:

myDP = new Array();
list.dataProvider = myDP;

for (var i=0; i<accounts.length; i++) {
  // these changes to the DataProvider will be broadcast to the list
  myDP.addItem({ label: accounts[i].name,
                 data:  accounts[i].accountID });
}


ComboBox.dropdown

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.dropdown

Description

Property (read-only); returns a reference to the List component contained by the combo box. The List subcomponent isn't instantiated in the combo box until it needs to be displayed. However, when you access the dropdown property, the list is created.

See also

ComboBox.dropdownWidth


ComboBox.dropdownWidth

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.change

Description

Property; the width limit in pixels of the drop-down list. The default value is the width of the ComboBox component (the TextInput instance plus the SimpleButton instance).

Example

The following code sets the dropdownWidth to 150 pixels:

myComboBox.dropdownWidth = 150;

See also

ComboBox.dropdown


ComboBox.editable

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.editable

Description

Property; indicates whether the combo box is editable (true) or not (false). An editable combo box can have values entered into the text box that do not show up in the drop-down list. If a combo box is not editable, only values listed in the drop-down list can be entered into the text box. The default value is false.

Setting a combo box to editable clears the combo box text field. It also sets the selected index (and item) to undefined. To make a combo box editable and still retain the selected item, use the following code:

var ix = myComboBox.selectedIndex;
myComboBox.editable = true; // clears the text field.
myComboBox.selectedIndex = ix; // copies the label back into the text field.

Example

The following code makes myComboBox editable:

myComboBox.editable = true;


ComboBox.enter

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(enter){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.enter = function(eventObject){
  // your code here
}
comboBoxInstance.addEventListener("enter", listenerObject)

Description

Event; broadcast to all registered listeners when the Enter key has been pressed in the text box. This event is only broadcast from editable combo boxes. This is a TextInput event that is broadcast from a combo box. For more information, see TextInput.enter.

The first usage example uses an on() handler and must be attached directly to a ComboBox component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox component instance myBox, sends "_level0.myBox" to the Output panel:

on(enter){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, enter) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example sends a message to the Output panel when the drop-down list begins to close:

form.enter = function(){
  trace("The combo box enter event was triggered");
}
myCombo.addEventListener("enter", form);

See also

UIEventDispatcher.addEventListener()


ComboBox.getItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

comboBoxInstance.getItemAt(index)

Parameters

index A number greater than or equal to 0, and less than ComboBox.length. The index of the item to retrieve.

Returns

The indexed item object or value. The value is undefined if the index is out of range.

Description

Method; retrieves the item at a specified index.

Example

The following code displays the item at index position 4:

trace(myBox.getItemAt(4).label);


ComboBox.itemRollOut

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(itemRollOut){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.itemRollOut = function(eventObject){
  // your code here
}
comboBoxInstance.addEventListener("itemRollOut", listenerObject)

Event Object

In addition to the standard properties of the event object, the itemRollOut event has an additional property: index. The index is the number of the item that was rolled out.

Description

Event; broadcast to all registered listeners when the pointer rolls out of drop-down list items. This is a List event that is broadcast from a combo box. For more information, see List.itemRollOut.

The first usage example uses an on() handler and must be attached directly to a ComboBox component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox component instance myBox, sends "_level0.myBox" to the Output panel:

on(itemRollOut){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, itemRollOut) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

Example

The following example sends a message to the Output panel that indicates which item index number has been rolled off of:

form.itemRollOut = function (eventObj) {
  trace("Item #" + eventObj.index + " has been rolled out of.");
}
myCombo.addEventListener("itemRollOut", form);

See also

ComboBox.itemRollOver, UIEventDispatcher.addEventListener()


ComboBox.itemRollOver

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(itemRollOver){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.itemRollOver = function(eventObject){
  // your code here
}
comboBoxInstance.addEventListener("itemRollOver", listenerObject)

Event Object

In addition to the standard properties of the event object, the itemRollOver event has an additional property: index. The index is the number of the item that was rolled over.

Description

Event; broadcast to all registered listeners when the drop-down list items are rolled over. This is a List event that is broadcast from a combo box. For more information, see List.itemRollOver.

The first usage example uses an on() handler and must be attached directly to a ComboBox component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox component instance myBox, sends "_level0.myBox" to the Output panel:

on(itemRollOver){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, itemRollOver) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

Example

The following example sends a message to the Output panel that indicates which item index number has been rolled over:

form.itemRollOver = function (eventObj) {
  trace("Item #" + eventObj.index + " has been rolled over.");
}
myCombo.addEventListener("itemRollOver", form);

See also

ComboBox.itemRollOut, UIEventDispatcher.addEventListener()


ComboBox.labelField

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.labelField

Description

Property; the name of the field in dataProvider array objects to use as the label field. This is a property of the List component that is available from a ComboBox component instance. For more information, see List.labelField.

The default value is undefined.

Example

The following example sets the dataProvider property to an array of strings and sets the labelField property to indicate that the name field should be used as the label for the drop-down list:

myComboBox.dataProvider = [
  {name:"Gary", gender:"male"},
  {name:"Susan", gender:"female"} ];

myComboBox.labelField = "name";

See also

List.labelFunction


ComboBox.labelFunction

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.labelFunction

Description

Property; a function that computes the label of a dataProvider item. You must define the function. The default value is undefined.

Example

The following example creates a data provider and then defines a function to specify what to use as the label in the drop-down list:

myComboBox.dataProvider  = [
  {firstName:"Nigel", lastName:"Pegg", age:"really young"},
  {firstName:"Gary", lastName:"Grossman", age:"young"},
  {firstName:"Chris", lastName:"Walcott", age:"old"},
  {firstName:"Greg", lastName:"Yachuk", age:"really old"} ];

myComboBox.labelFunction = function(itemObj){
  return (itemObj.lastName + ", " + itemObj.firstName);
}

See also

List.labelField


ComboBox.length

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.length

Description

Property (read-only); the length of the drop-down list. This is a property of the List component that is available from an instance of ComboBox. For more information, see List.length. The default value is 0.

Example

The following example stores the value of length to a variable:

dropdownItemCount = myBox.length;


ComboBox.open()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.open()

Parameters

None.

Returns

Nothing.

Description

Property; opens the drop-down list.

Example

The following code opens the drop-down list for the combo1 instance:

combo1.open();

See also

ComboBox.close()


ComboBox.open

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(open){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.open = function(eventObject){
  // your code here
}
comboBoxInstance.addEventListener("open", listenerObject)

Description

Event; broadcast to all registered listeners when the drop-down list begins to appear.

The first usage example uses an on() handler and must be attached directly to a ComboBox component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox component instance myBox, sends "_level0.myBox" to the Output panel:

on(open){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, open) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

Example

The following example sends a message to the Output panel that indicates which item index number has been rolled out:

form.open = function () {
  trace("The combo box has opened with text " + myBox.text);
}
myBox.addEventListener("open", form);

See also

ComboBox.close, UIEventDispatcher.addEventListener()


ComboBox.removeAll()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

comboBoxInstance.removeAll()

Parameters

None.

Returns

Nothing.

Description

Method; removes all items in the list. This is a method of the List component that is available from an instance of the ComboBox component.

Example

The following code clears the list:

myCombo.removeAll();

See also

ComboBox.removeItemAt(), ComboBox.replaceItemAt()


ComboBox.removeItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.removeItemAt(index)

Parameters

index A number that indicates the position of the item to remove. This value is zero-based.

Returns

An object; the removed item (undefined if no item exists).

Description

Method; removes the item at the specified index position. The list indices after the index indicated by the index parameter collapse by one. This is a method of the List component that is available from an instance of the ComboBox component.

Example

The following code removes the item at index position 3:

myCombo.removeItemAt(3);

See also

ComboBox.removeAll(), ComboBox.replaceItemAt()


ComboBox.replaceItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

comboBoxInstance.replaceItemAt(index, label[, data])

Parameters

index A number 0 or greater that indicates the position at which to insert the item (the index of the new item).

label A string that indicates the label for the new item.

data The data for the item. This parameter is optional.

Returns

Nothing.

Description

Method; replaces the content of the item at the index specified by the index parameter. This is a method of the List component that is available from the ComboBox component.

Example

The following example changes the third index position:

myCombo.replaceItemAt(3, "new label");

See also

ComboBox.removeAll(), ComboBox.removeItemAt()


ComboBox.rowCount

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.rowCount

Description

Property; the maximum number of rows visible in the drop-down list. The default value is 5.

If the number of items in the drop-down list is greater than or equal to the rowCount property, it resizes and a scroll bar is displayed if necessary. If the drop-down list contains fewer items than the rowCount property, it resizes to the number of items in the list.

This behavior differs from the List component, which always shows the number of rows specified by its rowCount property, even if some empty space is shown.

If the value is negative or fractional, the behavior is undefined.

Example

The following example specifies that the combo box should have 20 or fewer rows visible:

myComboBox.rowCount = 20;


ComboBox.scroll

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(scroll){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.scroll = function(eventObject){
  // your code here
}
comboBoxInstance.addEventListener("scroll", listenerObject)

Event Object

Along with the standard event object properties, the scroll event has one additional property, direction. It is a string with two possible values "horizontal" or "vertical". For a ComboBox scroll event, the value is always "vertical".

Description

Event; broadcast to all registered listeners when the drop-down list is scrolled. This is a List component event that is available to the ComboBox.

The first usage example uses an on() handler and must be attached directly to a ComboBox component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ComboBox component instance myBox, sends "_level0.myBox" to the Output panel:

on(scroll){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (comboBoxInstance) dispatches an event (in this case, scroll) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

Example

The following example sends a message to the Output panel that indicates which item index number has been scrolled to:

form.scroll = function (eventObj) {
  trace("The list had been scrolled to item # " + eventObj.target.vPosition);
}
myCombo.addEventListener("scroll", form);

See also

UIEventDispatcher.addEventListener()


ComboBox.selectedIndex

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.selectedIndex

Description

Property; the index (number) of the selected item in the drop-down list. The default value is 0. Assigning this property clears the current selection, selects the indicated item, and displays that label of the indicated item in the combo box's text box.

Assigning a selectedIndex that is out of range is ignored. Entering text into the text field of an editable combo box sets selectedIndex to undefined.

Example

The following selects the last item in the list:

myComboBox.selectedIndex = myComboBox.length-1;

See also

ComboBox.selectedItem


ComboBox.selectedItem

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.selectedItem

Description

Property; the value of the selected item in the drop-down list.

If the combo box is editable selectedItem returns undefined if you enter any text in the text box. It will only have a value if you select an item from the drop-down list, or the value is set via ActionScript. If the combo box is static, the value of selectedItem is always valid.

Example

The following example shows selectedItem if the data provider contains primitive types:

var item = myComboBox.selectedItem;
trace("You selected the item " + item);

The following example shows selectedItem if the data provider contains objects with label and data properties:

var obj = myComboBox.selectedItem;
trace("You have selected the color named: " + obj.label);
trace("The hex value of this color is: " + obj.data);

See also

ComboBox.dataProvider, ComboBox.selectedIndex


ComboBox.text

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.text

Description

Property; the text of the text box. You can get and set this value for editable combo boxes. For static combo boxes, the value is read-only.

Example

The following example sets the current text value of an editable combo box:

myComboBox.text = "California";


ComboBox.textField

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.textField

Description

Property (read-only); a reference to the TextInput component contained by the ComboBox.

This property allows you to access the underlying TextInput component so that you can to manipulate it. For example, you might want to change the selection of the text box or restrict the characters that can be entered into it.

Example

The following code restricts the text box of myComboBox to only accept numbers:

myComboBox.textField.restrict = "0-9";


ComboBox.value

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

myComboBox.value

Description

Property (read-only); if the combo box is editable, value returns the value of the text box. If the combo box is static, value returns the value of the drop-down list. The value of the drop-down list is the data field, or, if the data field doesn't exist, the label field.

Example

The following example puts the data into the combo box by setting the dataProvider property. It then displays the value in the Output panel. Finally, it selects "California" and displays it in the text box, as follows:

cb.dataProvider = [
  {label:"Alaska", data:"AZ"},
  {label:"California", data:"CA"},
  {label:"Washington", data:"WA"}];
cb.editable = true;
cb.selectedIndex = 1;
trace('Editable value is "California": '+ cb.value);
cb.editable = false;
cb.selectedIndex = 1;
trace('Non-editable value is "CA": '+ cb.value);


About Data binding classes

The data binding classes provide the runtime functionality for the data binding feature in Flash MX Professional 2004. You can visually create and configure data bindings in the Flash authoring environment using the Bindings tab in the Component Inspector panel, or you can programmatically create and configure bindings using the classes in the mx.data.binding package.

For an overview of data binding, and how to visually create data bindings in the Flash authoring tool, see Data binding (Flash Professional only).See also:

  • Making data binding classes available at runtime (Flash Professional only)
  • Classes in the mx.data.binding package (Flash Professional only)
  • Binding class (Flash Professional only)


Making data binding classes available at runtime (Flash Professional only)

In order to make the data binding service classes available at runtime, the DataBindingClasses component must be in your FLA file's library. When you visually create bindings in the Flash authoring environment, this component is automatically added to your document's library. But if you're only using ActionScript to create bindings at runtime, then you have to add this component manually to your document's library. For information on how to add this component to your document, see Working with data binding and web services at runtime (Flash Professional only).


Classes in the mx.data.binding package (Flash Professional only)

The following table lists the classes in the mx.data.binding package.

Class | Description
Binding class (Flash Professional only) | Creates a binding between two endpoints.
ComponentMixins class (Flash Professional only) | Adds data binding-specific functionality to components.
CustomFormatter class (Flash Professional only) | Base class for creating custom formatter classes.
CustomValidator class (Flash Professional only) | Base class for creating custom validator classes.
DataType class (Flash Professional only) | Provides read and write access to data fields of a component property.
EndPoint class (Flash Professional only) | Defines the source or destination of a binding.
TypedValue class (Flash Professional only) | Contains a data value and information about the value's data type.


Binding class (Flash Professional only)

ActionScript Class Name mx.data.binding.Binding

The Binding class defines an association between two endpoints, a source and a destination. It listens for changes to the source endpoint and copies the changed data to the destination endpoint each time the source changes.

You can write custom bindings using the Binding class (and supporting classes), or use the Bindings tab in the Component Inspector panel (Window > Development Panels > Component Inspector).

Note: To make this class available at runtime, you must include the DataBindingClasses component in your FLA document. For more information, see Working with data binding and web services at runtime (Flash Professional only).

For an overview of the classes in the mx.data.binding package, see Data binding classes (Flash Professional only).

Method summary for the Binding class

Method | Description
Binding.execute() | Fetches the data from the source component, formats it, and assigns it to the destination component.

Constructor for the Binding class

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

new Binding(source, destination, [format], [isTwoWay])

Parameters

source A source endpoint of the binding. This parameter is nominally of type mx.data.binding.EndPoint, but can be any ActionScript object that has the required Endpoint fields (see EndPoint class (Flash Professional only)).

destination The destination endpoint of the binding. This parameter is nominally of type mx.data.binding.EndPoint, but can be any ActionScript object that has the required Endpoint fields (see EndPoint class (Flash Professional only)).

format (Optional) An object that contains formatting information. The object must have the following properties:

  • cls An ActionScript class that extends the class mx.data.binding.DataAccessor.
  • settings An object whose properties provide optional settings for the formatter class specified by cls.

isTwoWay (Optional) A Boolean value that specifies whether the new Binding object is bidirectional (true) or not (false). The default value is false.

Returns

Nothing.

Description

Constructor; creates a new Binding object. You can bind data to any ActionScript object that has properties and emits events including, but not limited to, components.

A binding object exists as long as the inner-most movie clip contains both the source and destination components. For example, if movie clip named "A" contains components "X" and "Y", and there is a binding between "X" and "Y", then the binding is in effect as long as movie clip A exists.

Note: It's not necessary to retain a reference to the new Binding object, although you can. As soon as the Binding object is created it immediately begins listening for "changed" events emitted by either EndPoint. In some cases, however, you might want to save a reference to the new Binding object, so that you can call its execute() method at a later time (see Binding.execute()).

Example

Example #1: In this example, the text property of a TextInput component (src_txt) is bound to the text property of another TextInput component (dest_txt). When the src_txt text field loses focus (that is, when the focusOut event is generated), the value of its text property is copied into dest_txt.text.

import mx.data.binding.*;
var src = new EndPoint();
src.component = src_txt;
src.property = "text";
src.event = "focusOut";

var dest= new EndPoint();
dest.component = dest_txt;
dest.property = "text";

new Binding(src, dest);

Example #2: This example demonstrates how to create a Binding object that uses a custom formatter class. For more information on creating custom formatter classes, see CustomFormatter class (Flash Professional only).

import mx.data.binding.*;
var src = new EndPoint();
src.component = src_txt;
src.property = "text";
src.event = "focusOut";

var dest= new EndPoint();
dest.component = text_dest;
dest.property = "text";

new Binding(src, dest, {cls: mx.data.formatters.Custom, settings: {classname: "com.mycompany.SpecialFormatter"}});


Binding.execute()

Availability

Flash Player 6.

Edition

Flash MX Professional 2004.

Usage

myBinding.execute([reverse])

Parameters

reverse A Boolean value that specifies whether the binding should also be executed from the destination to the source (true), or only from the source to the destination (false). By default, this value is false.

Returns

A null value if the binding executed successfully; otherwise, returns an array of error messages (strings) that describe the error, or errors, that prevented the binding from executing.

Description

Method; fetches the data from the source component and assigns it to the destination component. If the binding uses a formatter, then the data is formatted before being assigned to the destination.

This method also validates the data and causes either a valid or invalid event to be emitted by the destination and source components. Data is assigned to the destination even if it's invalid, unless the destination is read-only.

If the reverse parameter is set to true, and the binding is two-way, then the binding is executed in reverse (from the destination to the source).

Example

The following code, attached to a Button component instance, executes the binding in reverse (from the destination component to the source component) when the button is clicked.

on(click) {
  _root.myBinding.execute(true);
}


CustomFormatter class (Flash Professional only)

ActionScript Class Name mx.data.binding.CustomFormatter

The CustomFormatter class defines two methods, format() and unformat(), that provide the ability to transform data values from a specific data type to String, and vice versa. By default, these methods do nothing; you must implement them in a subclass of mx.data.binding.CustomFormatter.

To create your own custom formatter, you first create a subclass of CustomFormatter that implements format() and unformat() methods. You can then assign that class to a binding between components either by creating a new Binding object with ActionScript (see Binding class (Flash Professional only)), or by using the Bindings tab in the Component Inspector panel. For information on assigning a formatter class using the Component Inspector, see Schema formatters (Flash Professional only).

You can also assign a formatter class to a component property on the Component Inspector panel's Schema tab. However, in that case, the formatter will only get used when the data is needed in the form of a string. In contrast, formatters assigned using the Bindings panel, or created with ActionScript, are used whenever when the binding is executed.

For an example of writing and assigning a custom formatter using ActionScript, see Sample custom formatter.

Note: To make this class available at runtime, you must include the DataBindingClasses component in your FLA document. For more information, see Working with data binding and web services at runtime (Flash Professional only).

For an overview of the classes in the mx.data.binding package, see Data binding classes (Flash Professional only).

Sample custom formatter

The following example demonstrates how to create a custom formatter class and then apply it to a binding between two components using ActionScript. In this example, the current value of a NumericStepper component (its value property) is bound to the current value of a TextInput component (its text property). The custom formatter class formats the current numeric value of the NumericStepper component (for example, 1, 2, or 3) as its English word equivalent (for example, "one", "two", or "three") before assigning it to the TextInput component.

To create and use a custom formatter:

  1. In Flash MX Professional 2004, create a new ActionScript file.
  2. Add the following code to the file:
    // NumberFormatter.as
class NumberFormatter extends mx.data.binding.CustomFormatter {
  // Format a Number, return a String
  function format(rawValue) {
    var returnValue;
    var strArray = new Array('one', 'two', 'three');
    var numArray = new Array(1, 2, 3);
    returnValue = 0;
    for (var i = 0; i<strArray.length; i++) {
      if (rawValue == numArray[i]) {
        returnValue = strArray[i];
        break;
      }
    }
    return returnValue;
  }  // convert a formatted value, returns a raw value
  function unformat(formattedValue) {
    var returnValue;
    var strArray = new Array('one', 'two', 'three');
    var numArray = new Array(1, 2, 3);
    returnValue = "invalid";
    for (var i = 0; i<strArray.length; i++) {
      if (formattedValue == strArray[i]) {
        returnValue = numArray[i];
        break;
      }
    }
    return returnValue;
  }
}
  3. Save the ActionScript file as NumberFormatter.as.
  4. Create a new Flash (FLA) document.
  5. Open the Components panel (Window > Development Panels > Components).
  6. Drag a TextInput component to the Stage and name it textInput.
  7. Drag a NumericStepper component to the Stage and name it stepper.
  8. Open the Timeline (Window > Timeline) and select the first frame on Layer 1.
  9. Open the Actions panel (Window > Development Panels > Actions).
  10. Add the following code to the Actions panel:
    import mx.data.binding.*;
var x:NumberFormatter;
var customBinding = new Binding({component:stepper, property:"value", event:"change"}, {component:textInput, property:"text", event:"enter,change"}, {cls:mx.data.formatters.Custom, settings:{classname:"NumberFormatter"}});

    The second line of code (var x:NumberFormatter) ensures that the byte code for your custom formatter class is included in the compiled SWF file.

  11. Select Window > Panels > Other Panels > Classes to open the Classes library.
  12. Open your document's library by selecting Window > Library.
  13. Drag the DataBindingClasses component from the Classes library to your document's library.

    This makes the data binding runtime classes available for your document. For more information, see Working with data binding and web services at runtime (Flash Professional only).

  14. Save the FLA file to the same folder that contains NumberFormatter.as.
  15. Test the file (Control > Test Movie).

    Click the buttons on the NumericStepper component and watch the contents of the TextInput component update.

Method summary for the CustomFormatter class

Method | Description
CustomFormatter.format() | Converts from a raw data type to a text string.
CustomFormatter.unformat() | Converts from a text string to a raw data type.


CustomFormatter.format()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

This method is called automatically; you don't invoke it directly.

Parameters

rawData The data to be formatted.

Returns

A formatted value.

Description

Method; converts from a raw data type to a new object.

This method is not implemented by default. You must define this method in your subclass of mx.data.binding.CustomFormatter.

Example

See Sample custom formatter.


CustomFormatter.unformat()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

This method is called automatically; you don't invoke it directly.

Parameters

formattedData The formatted data to convert back to the raw data type.

Returns

An unformatted value.

Description

Method; converts from a string, or other data type, to the raw data type. This transformation should perform the exact inverse transformation of the CustomFormatter.format().

This method is not implemented by default. You must define this method in your subclass of mx.data.binding.CustomFormatter.

For more information, see Sample custom formatter.


CustomValidator class (Flash Professional only)

ActionScript Class Name mx.data.binding.CustomValidator

You use the CustomValidator class when you want to perform custom validation of a data field contained by a component.

To create a custom validation class, you first create a subclass of mx.data.binding.CustomValidator that implements a method named validate(). This method is automatically passed a value to be validated. For more information about how to implement this method, see CustomValidator.validate().

Next, you assign your custom validator class to a field of a component using the Component Inspector panel's Schema tab. For an example of creating and using a custom validator class, see the Example section in the entry for CustomValidator.validate().

To assign a custom validator, do the following:

  1. In the Component Inspector panel (Window > Component Inspector), select the Schema tab.
  2. Select the field you want to validate, and then select Custom from the Data Type pop-up menu.
  3. Select the Validation Options field (at the bottom of the Schema tab), and click the magnifying glass icon to open the Custom Validation Settings dialog box.
  4. In the ActionScript Class text box enter the name of the custom validation class you created.

    In order for the class you specify to be included in the published SWF file, it must be in the classpath.

Note: To make this class available at runtime, you must include the DataBindingClasses component in your FLA document. For more information, see Working with data binding and web services at runtime (Flash Professional only).

For an overview of the classes in the mx.data.binding package, see Data binding classes (Flash Professional only).

Method summary for the CustomValidator class

Method | Description
CustomValidator.validate() | Performs validation on data.
CustomValidator.validationError() | Reports validation errors.


CustomValidator.validate()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

This method is called automatically; you don't invoke it directly.

Parameters

value The data to be validated; it can be of any type.

Returns

Nothing.

Description

Method; called automatically to validate the data contained by the value parameter. You must implement this method in your subclass of CustomValidator; the default implementation does nothing.

You can use any ActionScript code you like to examine and validate the data. If the data is not valid, this method should call this.validationError() with an appropriate message. You can call this.validationError() more than once if there are several validation problems with the data.

Since the validate() method might be called repeatedly, you should avoid adding code to this method that takes a long time to complete. Your implementation of this method should only check for validity, and then report any errors using CustomValidator.validationError(). Similarly, your implementation should not take any action as a result of the validation test, such as alerting the end user. Instead, create event listeners for valid and invalid events and alert the end user from those event listeners (see example below).

Example

The following procedure demonstrates how to create and use a custom validation class. The validate() method of the CustomValidator class, OddNumbersOnly.as, determines as invalid any value that not an odd number. The validation occurs whenever the value of a NumericStepper component changes, which is bound to the text property of a Label component.

To create and use a custom validator class:

  1. In Flash MX Professional 2004, create a new ActionScript (AS) file.
  2. Add the following code to the AS file:
    class OddNumbersOnly extends mx.data.binding.CustomValidator
{
  public function validate(value) {
    // make sure the value is a Number
    var n = Number(value);
    if (String(n) == "NaN") {
      this.validationError("'" + value + "' is not a number.");
      return;
    }
    // make sure the number is odd
    if (n % 2 == 0) {
      this.validationError("'" + value + "' is not a odd number.");
      return;
    }
    // data is ok, no need to do anything, just return
  }
}
  3. Save the AS file as OddNumbersOnly.as.

    Note: The name of the AS file must match the name of the class.

  4. Create a new Flash (FLA) document.
  5. Open the Components panel (Window > Development Panels > Components).
  6. Drag a NumericStepper component from the Components panel to the Stage and name it stepper.
  7. Drag a Label component to the Stage and name it textLabel.
  8. Drag a TextArea component to the Stage and name it status.
  9. Select the NumericStepper component, and open the Component Inspector panel (Window > Development Panels > Component Inspector).
  10. Select the Bindings tab in the Component Inspector panel and click the Add Binding (+) button.
  11. Select the Value property (the only one) in the Add Bindings dialog, then click OK
  12. In the Component Inspector panel, double-click Bound To in the Binding Attributes pane of the Bindings tab to open the Bound To dialog box.
  13. In the Bound To dialog box, select the Label component in the Component Path pane and the its text property in the Schema Location pane. Click OK.
  14. Select the Label component on the Stage and click the Schema tab in the Component Inspector panel.
  15. In the Schema Attributes pane, select Custom from the Data Type pop-up menu.
  16. Double-click the Validation Options field in the Schema Attributes pane to open the Custom Validation Settings dialog box.
  17. In the ActionScript Class text box, enter OddNumbersOnly, which is the name of the ActionScript class you created previously. Click OK.
  18. Open the Timeline (Window > Timeline) and select the first frame on Layer 1.
  19. Open the Actions panel (Window > Actions).
  20. Add the following code to the Actions panel:
    function dataIsInvalid(evt) {
  if (evt.property == "text") {
    status.text = evt.messages;
  }
}

function dataIsValid(evt) {
  if (evt.property == "text") {
    status.text = "OK";
  }
}

textLabel.addEventListener("valid", dataIsValid);
textLabel.addEventListener("invalid", dataIsInvalid);
  21. Save the FLA file as OddOnly.fla to the same folder that contains OddNumbersOnly.as.
  22. Test the SWF file (Control > Test Movie).

    Click the arrows on the NumericStepper component to change its value. Notice the message that appears in the TextArea component when you choose even and odd numbers.


CustomValidator.validationError()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

this.validationError(errorMessage)

Note: This method can be invoked only from inside a custom validator class; the keyword this refers to the current CustomValidator object.

Parameters

errorMessage A string that contains the error message to be reported.

Returns

Nothing.

Description

Method; you call this method from the validate() method of your subclass of CustomValidator to report validation errors. If you don't call this method, then a valid event is generated when validate() completes. If you call this method one or more times from within the validate() method then an invalid event is generated after validate() returns.

Each message you pass to validationError() is available in the "messages" property of the event object that passed to the invalid event handler.

Example

See the Example section for CustomValidator.validate().


EndPoint class (Flash Professional only)

ActionScript Class Name mx.data.binding.EndPoint

The EndPoint class defines the source or destination of a binding. EndPoint objects define a constant value, component property, or a particular field of a component property, from which you can get data, or to which you can assign data. They can also define an event, or list of events, that a Binding object listens for; when the specified event occurs, the binding executes.

When you create a new binding with the Binding class constructor, you pass it two EndPoint objects: one for the source and one for the destination.

new mx.data.binding.Binding(srcEndPoint, destEndPoint);

The EndPoint objects, srcEndPoint and destEndPoint, might be defined as follows:

var srcEndPoint = new mx.data.binding.EndPoint();
var destEndPoint = new mx.data.binding.EndPoint();
srcEndPoint.component = source_txt;
srcEndPoint.property = "text";
srcEndPoint.event = "focusOut";
destEndPoint.component = dest_txt;
destEndPoint.property = "text";

In English, the above code means "when the source text field loses focus, copy the value of its text property into the text property of the destination text field".

You can also pass generic ActionScript objects to the Binding constructor, rather than passing explicitly constructed EndPoint objects. The only requirement is that the objects define the required EndPoint properties, namely component and property. The following code is equivalent to that shown above.

var srcEndPoint = {component:source_txt, property:"text"};
var destEndPoint = {component:dest_txt, property:"text"};
new mx.data.binding.Binding(srcEndPoint, destEndPoint);

Note: To make this class available at runtime, you must include the DataBindingClasses component in your FLA document. For more information, see Working with data binding and web services at runtime (Flash Professional only).

For an overview of the classes in the mx.data.binding package, see Data binding classes (Flash Professional only).

Property summary for the EndPoint class

Method | Description
EndPoint.constant | A constant value.
EndPoint.component | A reference to a component instance.
EndPoint.property | The name of a property of the component instance specified by EndPoint.component.
EndPoint.location | The location of a data field within the property of the component instance.
EndPoint.event | The name of an event, or list of events, the component instance will emit when the data changes.

Constructor for the EndPoint class

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

new EndPoint()

Returns

Nothing.

Description

Constructor; creates a new EndPoint object.

Example

This example creates a new EndPoint object named source_txt and assigns values to its component and property properties.

var source_obj = new mx.data.binding.EndPoint();
source_obj.component = myTextField;
source_obj.property = "text";


EndPoint.constant

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

endPoint_src.constant

Description

Property; a constant value assigned to an EndPoint object. This property can only be applied to EndPoints that are the source, not the destination, of a binding between components. The value can be any data type that is compatible with the destination of the binding. If specified, all other EndPoint properties for the specified EndPoint object are ignored.

Example

In this example, the string constant value "hello" is assigned to an EndPoint object's constant property.

var sourceEndPoint = new mx.data.binding.EndPoint();
sourceEndPoint.constant="hello";


EndPoint.component

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

endPointObj.component

Description

Property; a reference to a component instance.

Example

This example assigns an instance of the List component (listBox1) as the component parameter of a EndPoint object.

var sourceEndPoint = new mx.data.binding.EndPoint();
sourceEndPoint.component=listBox1;


EndPoint.property

Availability

Flash Player 6 r79

Edition

Flash MX Professional 2004.

Usage

endPointObj.property

Description

Property; specifies a property name of the component instance specified by EndPoint.component that contains the bindable data.

Note: EndPoint.component and EndPoint.property must combine to form a valid ActionScript object/property combination.

Example

This example binds the text property of one TextInput component (text_1) to the same property in another TextInput component (text_2).

var sourceEndPoint = {component:text_1, property:"text"};
var destEndPoint = {component:text_2, property:"text"};
new Binding(sourceEndPoint, destEndPoint);


EndPoint.location

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

endPointObj.location

Description

Property; specifies the location of a data field within the property of the component instance. There are four ways to specify a location: as a string that contains either an XPath expression or an ActionScript path, an array of strings, or an object.

XPath expressions can only be used when the data is an XML object. For a list of supported XPath expressions, see Supported XPath expressions. (See Example 1 below.)

For XML and ActionScript objects you can also specify a string that contains an ActionScript path. An ActionScript path contains the names of fields separated by dots (for example, "a.b.c").

You can also specify an array of strings as a location. Each string in the array "drills down" another level of nesting. You can use this technique with both XML and ActionScript data. (See Example 2 below.) When used with ActionScript data, an array of strings is equivalent to using an ActionScript; that is, the array ["a","b","c"] is equivalent to "a.b.c".

If you specify an object as the location, the object must specify two properties: path and indices. The path property is an array of strings, as discussed above, except that one or more of the specified strings may be the special token "[n]". For each occurrence of this token in path, there must be a corresponding index item in indices. As the path is being evaluated, the indices are used to index into arrays. The index item can be any EndPoint. This type of location can be applied to ActionScript data only—not XML. (See Example 3 below.)

Example

Example 1: This example uses an XPath expression to specify the location of a node named zip in an XML object.

var sourceEndPoint = new mx.databinding.EndPoint();
var sourcObj=new Object();
sourceObj.xml=new XML("<zip>94103</zip>");
sourceEndPoint.component=sourceObj;
sourceEndPoint.property="xml";
sourceEndPoint.location="/zip";//

Example 2: This example uses an array of string to "drill down" to a nested movie clip property.

var sourceEndPoint = new mx.data.binding.EndPoint();
//assume movieClip1.ball.position exists
ssourceEndPoint.component=movieClip1;
sourceEndPoint.property="ball";
//access movieClip1.ball.position.x
sourceEndPoint.location=["position","x"];

Example 3: This example shows how to use an object to specify the location of a data field in a complex data structure.

var city=new Object();
city.theaters = [{theater: "t1", movies: [{name: "Good,Bad,Ugly"}, {name:"Matrix Reloaded"}]}, {theater: "t2", movies: [{name: "Gladiator"}, {name: "Catch me if you can"}]}];
var srcEndPoint = new EndPoint();
srcEndPoint.component=city;
srcEndPoint.property="theaters";
srcEndPoint.location = {path: ["[n]","movies","[n]","name"], indices: [{constant:0},{constant:0}]};


EndPoint.event

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

endPointObj.event

Description

Property; specifies the name of an event, or an array of event names, generated by the component when data assigned to the bound property changes. When the event occurs, the binding executes.

The specified event only applies to components that are used as the source of a binding, or as the destination of a two-way binding. For more information about creating two-way bindings, see Binding class (Flash Professional only).

Example

In this example, the text property of one TextInput (src_txt) component is bound to the same property of another TextInput component (dest_txt). The binding is executed when either the focusOut or enter events are emitted by the src_txt component.

var source = {component:src_txt, property:"text", event:["focusOut", "enter"]};
var dest = {component:myTextArea, property:"text"};
var newBind = new mx.data.binding.Binding(source, dest);


ComponentMixins class (Flash Professional only)

ActionScript Class Name mx.data.binding.ComponentMixins

The ComponentMixins class defines properties and methods that are automatically added to any object that is the source or destination of a binding, or to any component that's the target of a ComponentMixins.initComponent() method call. These properties and methods do not affect normal component functionality; rather, they add functionality that is useful with data binding.

Note: To make this class available at runtime, you must include the DataBindingClasses component in your FLA document. For more information, see Working with data binding and web services at runtime (Flash Professional only).

For an overview of the classes in the mx.data.binding package, see Data binding classes (Flash Professional only).

Method summary for the ComponentMixins class

Method | Description
ComponentMixins.getField() | Returns an object for getting and setting the value of a field at a specific location in a component property.
ComponentMixins.initComponent() | Adds the ComponentMixin methods to a component.
ComponentMixins.refreshFromSources() | Executes all bindings that have this component as the destination EndPoint.
ComponentMixins.refreshDestinations() | Executes all the bindings that have this object as the source EndPoint.
ComponentMixins.validateProperty() | Checks to see if the data in the indicated property is valid.


ComponentMixins.getField()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.getField(propertyName, [location])

Parameters

propertyName A string that contains the name of a property of the specified component.

location (Optional) The location of a field within the component property. This is useful if the component property specified by propertyName is a complex data structure and you are interested in a particular field of that structure. This property can take one of the following three forms:

  • A string that contains a XPath expression. This is only valid for XML data structures. For a list of supported XPath expressions, see Supported XPath expressions.
  • A string that contains field names, separated by dots, for example "a.b.c". This form is permitted for any complex data (ActionScript or XML).
  • An array of strings, where each string is a field name, for example ["a", "b", "c"]. This form is permitted for any complex data (ActionScript or XML).

Returns

A DataType object.

Description

Method; returns a DataType object whose methods you can use to get or set the data value in the component property at the specified field location. For more information, see DataType class (Flash Professional only).

Example

This example uses the DataType.setAsString() method to set the value of a field located in a component's property. In this case the property (results) is a complex data structure.

import mx.data.binding.*;
var field : DataType = myComponent.getField("results", "po.address.name1");
field.setAsString("Teri Randall");

See also

DataType.setAsString()


ComponentMixins.initComponent()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mx.data.binding.ComponentMixins.initComponent(componentInstance)

Parameters

componentInstance A reference to a component instance.

Returns

Nothing.

Description

Method (static); adds all the ComponentMixins methods to the component specified by componentInstance. This method is called automatically for all components involved in a data binding. To make the ComponentMixins methods available for a component not involved in a data binding, you must explicitly call this method for that component.

Example

The following code makes the ComponentMixins methods available to a DataSet component.

mx.data.binding.ComponentMixins.initComponent(_root.myDataSet);


ComponentMixins.refreshFromSources()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.refreshSources()

Returns

Nothing.

Description

Method; executes all bindings for which componentInstance is the destination EndPoint object. This method lets you execute bindings that have constant sources, or sources that do not emit any "data changed" event.

Example

The following example executes all the bindings for which the ListBox component instance named cityList is the destination EndPoint object.

cityList.refreshFromSources();


ComponentMixins.refreshDestinations()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.refreshDestinations()

Returns

Nothing.

Description

Method; executes all the bindings for which componentInstance is the source EndPoint. This method lets you execute bindings whose sources do not emit a "data changed" event.

Example

The following example executes all the bindings for which the DataSet component instance named user_data is the source EndPoint object.

user_data.refreshDestinations();


ComponentMixins.validateProperty()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.validateProperty(propertyName)

Parameters

propertyName A string that contains the name of a property belonging to componentInstance.

Returns

An array, or null.

Description

Method; determines if the data in propertyName is valid based on the property's schema settings. The property's schema settings are those specified on the Schema tab in the Component Inspector panel.

The method returns null if the data is valid; otherwise, returns an array of error messages as strings.

Validation only applies to fields that have schema information available. If a field is an object that contains other fields, then each "child" field will be validated, and so on, recursively. Each individual field will dispatch a valid or invalid event, as necessary. For each data field contained by propertyName, this function dispatches valid or invalid events, as follows:

  • If the value of the field is null, and is not required, the method returns null. No events are generated.
  • If the value the field is null, and is required, an error is returned and an invalid event is generated.
  • If the value of the field is non-null and the field's schema does not have a validator, the method returns null; no events are generated.
  • If the value is non-null and the field's schema does define a validator, then the data is processed by the validator object. If the data is valid, a valid event is generated and null is returned; otherwise, an invalid event is generated and an array of error strings is returned.

Example

The following examples shows how to use validateProperty() to make sure that text entered by a user is of a valid length. You'll determine what a valid length is by setting the Validation Options for the String DataType in the Component Inspector panel's Schema tab. If the user enters a string in the text field of an invalid length, the error messages returned by the validateProperty() method are displayed in the Output panel.

To validate text entered by a user in a TextInput component:

  1. Drag a TextInput component from the Components panel (Window > Development Panels > Components) to the Stage, and name it zipCode_txt.
  2. Select the TextInput component and, in the Component Inspector panel (Window > Development Panels > Components), click the Schema tab.
  3. In the Schema Tree pane (the top pane of the Schema tab) select the text property.
  4. In the Schema Attributes pane (the bottom pane of the Schema tab), select ZipCode from the Data Type pop-up menu.
  5. Open the Timeline, if not already open, by choosing Window > Timeline.
  6. Click the first frame on Layer 1 in the Timeline, and open the Actions panel (Window > Actions).
  7. Add the following code to the Actions panel:
    // Add ComponentMixin methods to TextInput component.
// Note that this step is only necessary if the component
// isn't already involved in a data binding,
// either as the source or destination.
mx.data.binding.ComponentMixins.initComponent(zipCode_txt);
// Define event listener function for component:
validateResults = function (eventObj) {
  var errors:Array = eventObj.target.validateProperty("text");
  if (errors != null) {
    trace(errors);
  }
};
// Register listener function with component:
zipCode_txt.addEventListener("enter", validateResults);
  8. Select Window > Other Panels > Common Libraries > Classes to open the Classes library.
  9. Open your document's library by choosing Window > Library.
  10. Drag the DataBindingClasses component from the Classes library to your document's Library panel.

    This step is required to make the data binding runtime classes available to the SWF file at runtime. For more information, see Working with data binding and web services at runtime (Flash Professional only).

  11. Test the SWF file by choosing Control > Test Movie.

    In the TextInput component on the Stage, enter an invalid United States zip code—for example, one that contains all letters, or one that contains less than five numbers. Notice the error messages displayed in the Output panel.


DataType class (Flash Professional only)

ActionScript Class Name mx.data.binding.DataType

The DataType class provides read and write access to data fields of a component property. To get a DataType object, you call the ComponentMixins.getField() function on a component. You can then call methods of the DataType object to get and set the value of the field.

The difference between getting and setting field values using DataType object methods, and getting or setting the same values directly on the component instance, is that the latter case provides the data in its "raw" form. In contrast, when you get or set field values using methods of the DataType class, those values are processed according to the field's schema settings.

For example, the following code gets the value of a component's property directly and assigns it to a variable. The variable, propVar, contains whatever "raw" value is the current value of the property propName.

var propVar = myComponent.propName;

The next example gets the value of the same property using the DataType.getAsString() method. In this case, the value assigned to stringVar is the value of propName after being processed according to its schema settings, and then returned as a string.

var dataTypeObj:mx.data.binding.DataType = myComponent.getField("propName");
var stringVar: String = dataTypeObj.getAsString();

For more information about how to specify a field's schema settings, see Working with schemas in the Schema tab (Flash Professional only).

You can also use the methods of the DataType class to get or set fields in various data types. The DataType class automatically converts the raw data to the requested type, if possible. For example, in the code example above, the data that's retrieved is converted to String type, even if the raw data is a different type.

The ComponentMixins.getField() method is available for components that have been included in a data binding (either as a source, destination, or an index), or that have been initialized using the ComponentMixins.initComponent() method. For more information, see ComponentMixins class (Flash Professional only).

Note: To make this class available at runtime, you must include the DataBindingClasses component in your FLA document. For more information, see Working with data binding and web services at runtime (Flash Professional only).

For an overview of the classes in the mx.data.binding package, see Data binding classes (Flash Professional only).

Method summary for the DataType class

Method | Description
DataType.getAsBoolean() | Fetches the current value of the field as a Boolean.
DataType.getAsNumber() | Fetches the current value of the field as a Number.
DataType.getAsString() | Fetches the current value of the field as a String value.
DataType.getAnyTypedValue() | Fetches the current value of the field.
DataType.getTypedValue() | Fetches the current value of the field in the form of the requested DataType.
DataType.setAnyTypedValue() | Sets a new value into the field.
DataType.setAsBoolean() | Sets the field to the new value, which is given as a Boolean.
DataType.setAsNumber() | Sets the field to the new value, which is given as a Number.
DataType.setAsString() | Sets the field to the new value, which is given as a String.
DataType.setTypedValue() | Sets a new value into the field.

Property summary for the DataType class

Property | Description
DataType.encoder | Provide a reference to the Encoder object associated with this field.
DataType.formatter | Provides a reference to the Formatter object associated with this field.
DataType.kind | Provides a reference to the Kind object associated with this field.


DataType.encoder

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.encoder

Description

Property; provides a reference to the encoder object associated with this field, if one exists. You can use this property to access any properties and methods defined by the specific encoder applied to the field in the Schema tab of the Component Inspector panel.

If no encoder was applied to the field in question, then this property will return undefined.

For more information about the encoders provided with Flash MX Professional 2004, see Schema encoders (Flash Professional only).

Example

The following example assumes that the field being accessed (isValid) uses the Boolean encoder (mx.data.encoders.Bool). This encoder is provided with Flash MX Professional 2004 and contains a property named trueStrings that specifies which strings should be interpreted as true Boolean values. The code below sets the trueStrings property for a field's encoder to be the strings "yes" and "si".

var myField:mx.data.binding.DataType = dataSet.getField("isValid");
myField.encoder.trueStrings = "Yes,Oui";


DataType.formatter

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.formatter

Description

Property; provides a reference to the formatter object associated with this field, if one exists. You can use this property to access any properties and methods for the formatter object applied to the field in the Schema tab of the Component Inspector panel.

If no formatter was applied to the field in question, then this property will return undefined.

For more information about the formatters provided with Flash MX Professional 2004, see Schema formatters (Flash Professional only).

Example

This example assumes that the field being accessed is using the Number Formatter (mx.data.formatters.NumberFormatter) provided with Flash MX Professional 2004. This formatter contains a property named precision that specifies how many digits to display after the decimal point. This code sets the precision property to two decimal places for a field using this formatter.

var myField:DataType = dataGrid.getField("currentBalance");
myField.formatter.precision = 2;


DataType.getAsBoolean()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.getAsBoolean()

Returns

A Boolean value.

Description

Method; fetches the current value of the field as a Boolean. The value is converted to Boolean form, if necessary.

Example

In this example, a field named propName that belongs to a component named myComponent is retrieved as a Boolean value, and assigned to a variable.

var dataTypeObj:mx.data.binding.DataType = myComponent.getField("propName");
var propValue:Boolean = dataTypeObj.getAsBoolean();


DataType.getAsNumber()

Availability

Flash Player 6.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.getAsNumber()

Returns

A number.

Description

Method; fetches the current value of the field as a number. The value is converted to Number form, if necessary.

Example

In this example, a field named propName that belongs to a component named myComponent is retrieved as a number, and assigned to a variable.

var dataTypeObj:mx.data.binding.DataType = myComponent.getField("propName");
var propValue:Number = dataTypeObj.getAsNumber();

See also

DataType.getAnyTypedValue()


DataType.getAsString()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.getAsString()

Returns

A string.

Description

Method; fetches the current value of the field as a string. The value is converted to String form, if necessary.

Example

In this example, a property of a component named propName that belongs to a component named myComponent is retrieved as a string and assigned to a variable.

var dataTypeObj:mx.data.binding.DataType = myComponent.getField("propName");
var propValue:String = dataTypeObj.getAsString();

See also

DataType.getAnyTypedValue()


DataType.getAnyTypedValue()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.getAnyTypedValue(suggestedTypes)

Parameters

suggestedTypes An array of strings that specify, in descending order of desirability, the preferred data types you'd like for the field. For more information, see the Description section below.

Returns

The current value of the field, in the form of one of the data types specified in the suggestedTypes array.

Description

Method; fetches the current value of the field, using the information in the field's schema to process the value. If the field is able to provide a value as the first data type specified in the suggestedTypes array, then the method returns the field's value as that data type. If not, the method attempts to extract the field's value as the second data type specified in the suggestedTypes array, and so on.

If you specify null as one of the items in the suggestedTypes array, then the method returns the value of the field in the data type specified in the Schema panel. Specifying null will always result in a value being returned, so only use null at the end of the array.

If a value can't be returned in the form of the one of the suggested types, then it is returned in the type specified in the Schema panel.

Example

This example attempts to get the value of a field (productInfo.available) in an XMLConnector component's results property first as a Number or, if that fails, as a String.

import mx.data.binding.DataType;
import mx.data.binding.TypedValue;
var f: DataType = myXmlConnector.getField("results", "productInfo.available");
var b: TypedValue = f.getAnyTypedValue(["Number", "String"]);

See also

ComponentMixins.getField()


DataType.getTypedValue()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.getTypedValue(requestedType)

Parameters

requestedType A string containing the name of a data type, or null.

Returns

A TypedValue object (see TypedValue class (Flash Professional only))

Description

Method; returns the value of the field in the form specified by requestedType, if specified and if the field can provide its value in that form. If the field isn't able to provide its value in the requested form then the method returns null.

If null is specified as the requestedType then the method returns the value of the field in its default type.

Example

var bool:TypedValue = field.getTypedValue("Boolean");


DataType.kind

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.kind

Description

Property; provides a reference to the Kind object associated with this field. You can use this to access properties and methods of the Kind object.


DataType.setAnyTypedValue()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.setAnyTypedValue(newTypedValue)

Parameters

newValue A TypedValue object value to set into the field.

For more information about TypedValue objects, see TypedValue class (Flash Professional only).

Returns

An array of strings describing any errors that occurred while attempting to set the new value. Errors can occur under any of the following conditions:

  • The data provided cannot be converted to the data type of this field (for example, "abc" cannot be converted to Number).
  • The data is an acceptable type but does not meet the validation criteria of the field.
  • The field is read-only.

Note: The actual text of the message(s) will vary depending on the data type, formatters, and encoders that are defined in the field's schema.

Description

Method; sets a new value into the field, using the information in the field's schema to process the field.

This method operates by first calling DataType.setTypedValue() to set the value. If that fails, the method checks to see if the destination object is willing to accept String, Boolean, or Number data, and if so, attempts to use the corresponding ActionScript conversion functions.

Example

This example creates a new TypedValue object (a Boolean), and then assigns that value to a DataType object named field. Any errors that occur are assigned to the errors array.

import mx.data.binding.*;
var t:TypedValue = new TypedValue (true, "Boolean");
var errors: Array = field.setAnyTypedValue (t);

See also

DataType.setTypedValue()


DataType.setAsBoolean()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.setAsBoolean(newBooleanValue)

Parameters

newBooleanValue A Boolean value.

Returns

Nothing.

Description

Method; sets the field to the new value, which is given as a Boolean. The value is converted to, and stored as, the data type that is appropriate for this field.

Example

var bool: Boolean = true;
field.setAsBoolean (bool);


DataType.setAsNumber()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.setAsNumber(newNumberValue)

Parameters

newNumberValue A Number.

Returns

Nothing.

Description

Method; sets the field to the new value, which is given as a Number. The value is converted to, and stored as, the data type that is appropriate for this field.

Example

var num: Number = 32;
field.setAsNumber (num);


DataType.setAsString()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.setAsString(newStringValue)

Parameters

newStringValue A String.

Returns

Nothing.

Description

Method; sets the field to the new value, which is given as a String. The value is converted to, and stored as, the data type that is appropriate for this field.

Example

var stringVal: String = "The new value";
field.setAsString (stringVal);


DataType.setTypedValue()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataTypeObject.setTypedValue(newTypedValue)

Parameters

newValue A TypedValue object value to set into the field.

For more information about TypedValue objects, see TypedValue class (Flash Professional only).

Returns

An array of strings describing any errors that occurred while attempting to set the new value. Errors can occur under any of the following conditions:

  • The data provided is not an acceptable type.
  • The data provided cannot be converted to the data type of this field (for example, "abc" cannot be converted to Number).
  • The data is an acceptable type but does not meet the validation criteria of the field.
  • The field is read-only.

Note: The actual text of the message(s) will vary depending on the data type, formatters, and encoders that are defined in the field's schema.

Description

Method; sets a new value into the field, using the information in the field's schema to process the field. This method behaves similarly to DataType.setAnyTypedValue(), except that it doesn't try as hard to convert the data to an acceptable data type. For more information, see DataType.setAnyTypedValue().

Example

This example creates a new TypedValue object (a Boolean), and then assigns that value to a DataType object named field. Any errors that occur are assigned to the errors array.

import mx.data.binding.*;
var bool:TypedValue = new TypedValue (true, "Boolean");
var errors: Array = field.setTypedValue (bool);

See also

DataType.setTypedValue()


TypedValue class (Flash Professional only)

ActionScript Class Name mx.data.binding.TypedValue

A TypedValue is an object that contains a data value, along with information about the value's data type. TypedValue objects are provided as parameters to, and are returned from, various methods of the DataType class. The data type information in the TypedValue object helps DataType objects decide when and how they need to do type conversion.

Note: To make this class available at runtime, you must include the DataBindingClasses component in your FLA document. For more information, see Working with data binding and web services at runtime (Flash Professional only).

For an overview of the classes in the mx.data.binding package, see Data binding classes (Flash Professional only).

Property summary for the TypedValue class

Property | Description
TypedValue.type | Contains the schema associated with the TypedValue object's value.
TypedValue.typeName | Contains the name of the DataType of the TypedValue object's value.
TypedValue.value | Contains the data value of the TypedValue object.

Constructor for the TypedValue class

Availability

Flash Player 6 r79.

Usage

new mx.data.binding.TypedValue(value, typeName, [type])

Parameters

value A data value. This can be any type.

typeName A String that contains the name of the DataType of the value.

type (Optional) A Schema object that describes in more detail the schema of the data. This field is only required in certain circumstances, such as when setting data into a DataSet component's dataProvider property.

Description

Constructor; creates a new TypedValue object.


TypedValue.type

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

typedValueObject.type

Description

Property; contains the schema associated with the TypedValue object's value. It is only used in certain circumstances.

Example

This example will display "null" in the Output panel.

var t: TypedValue = new TypedValue (true, "Boolean", null);
trace(t.type);


TypedValue.typeName

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

typedValueObject.typeName

Description

Property; contains the name of the DataType of the TypedValue object's value.

Example

This example will display "Boolean" in the Output panel.

var t: TypedValue = new TypedValue (true, "Boolean", null);
trace(t.typeName);


TypedValue.value

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

typedValueObject.value

Description

Property; contains the data value of the TypedValue object.

Example

This example will display "true" in the Output panel.

var t: TypedValue = new TypedValue (true, "Boolean", null);
trace(t.value);


About the DataGrid component (Flash Professional only)

The DataGrid component allows you to create powerful data-enabled displays and applications. You can use the DataGrid component to instantiate a recordset (retrieved from a database query in ColdFusion, Java, or .Net) using Macromedia Flash Remoting and display it in columns. You can also use data from a data set or from an array to fill a DataGrid component. The v2 DataGrid component has been improved to include horizontal scrolling, better event support (including event support for editable cells), enhanced sorting capabilities, and performance optimizations.

You can resize and customize characteristics such as the font, color, and borders of columns in a grid. You can use a custom movie clip as a "cell renderer" for any column in a grid. (A cell renderer displays the contents of a cell.) You can use scroll bars to move through data in a grid; you can also turn off scroll bars and use the DataGrid methods to create a page view style display.

When you add the DataGrid component to an application, you can use the Accessibility panel to make the component accessible to screen readers. First, you must add the following line of code to enable accessibility for the DataGrid component:

mx.accessibility.DataGridAccImpl.enableAccessibility();

You enable accessibility for a component only once, no matter how many instances you have of the component. For more information, see Creating Accessible Content.


Interacting with the DataGrid component (Flash Professional only)

You can use the mouse and the keyboard to interact with a DataGrid component.

If DataGrid.sortableColumns is true and DataGridColumn.sortOnHeaderRelease is true, clicking within a column header causes the grid to sort based on the column's cell values.

If DataGrid.resizableColumns is true, clicking in the area between columns allows you to resize columns.

Clicking within an editable cell sends focus to that cell; clicking a non-editable cell has no effect on focus. An individual cell is editable when both the DataGrid.editable and DataGridColumn.editable properties of the cell are true.

When a DataGrid instance has focus either from clicking or tabbing, you can use the following keys to control it:

Key | Description
Down arrow | When a cell is being edited, the insertion point shifts to the end of the cell's text. If a cell is not editable, the down arrow handles selection as the List component does.
Up arrow | When a cell is being edited, the insertion point shifts to the beginning of the cell's text. If a cell is not editable, the up arrow handles selection as the List component does.
Right arrow | When a cell is being edited, the insertion point shifts one character to the right. If a cell is not editable, the right arrow does nothing.
Left arrow | When a cell is being edited, the insertion point shifts one character to the left. If a cell is not editable, the left arrow does nothing.
Return/Enter/Shift+Enter | When a cell is editable, the change is committed, and the insertion point is moved to the cell on the same column, next row (up or down, depending on the shift toggle).
Shift+Tab/Tab | Moves focus to the previous item. When the Tab key is pressed, focus wraps from the last column in the grid to the first column on the next line. When Shift+Tab is pressed, wrapping is reversed.


Using the DataGrid component (Flash Professional only)

You can use the DataGrid component as the foundation for numerous types of data-driven applications. You can easily display a formatted tabular view of a database query (or other data), but you can also use the cell renderer capabilities to build more sophisticated and editable user interface pieces. The following are practical uses for the DataGrid component:

  • A webmail client
  • Search results pages
  • Spreadsheet applications such as loan calculators and tax form applications

The DataGrid component consists of two sets of APIs: the DataGrid class and the DataGridColumn class.

Understanding the DataGrid component: data model and view

Conceptually, the DataGrid component is composed of a data model and a view that displays the data. The data model consists of three main parts:

  • DataProvider

    This is a list of items with which to fill the data grid. Any array in the same frame as a DataGrid component is automatically given methods (from the DataProvider API) that allow you to manipulate data and broadcast changes to multiple views. Any object that implements the DataProvider interface can be assigned to the DataGrid.dataProvider property (including recordsets, data sets, and so on). The following code creates a data provider called myDP:

    myDP = new Array({name:"Chris", price:"Priceless"}, {name:"Nigel", price:"Cheap"});
  • Item

    This is an ActionScript object used for storing the units of information in the cells of a column. A data grid is really a list that can display more than one column of data. A list can be thought of as an array; each indexed space of the list is an item. For the DataGrid component, each item consists of fields. In the following code, the contents between curly braces ({}) is an item:

    myDP = new Array({name:"Chris", price:"Priceless"}, {name:"Nigel", price:"Cheap"});
  • Field

    Identifiers that indicate the names of the columns within the items. This corresponds to the columnNames property within the columns list. In the List component, the fields are usually label and data, but in the DataGrid component the fields can be any identifier. In the following code, the fields are name and price:

    myDP = new Array({name:"Chris", price:"Priceless"}, {name:"Nigel", price:"Cheap"});

The view consists of three main parts:

  • Row

    This is a view object responsible for rendering the items of the grid by laying out cells. Each row is laid out horizontally below the previous one.

  • Column

    This consists of the view objects (instances of the DataGridColumn class) responsible for displaying each column, for example, width, color, size, and so on.

    There are three ways to add columns to a data grid: assign a DataProvider object to DataGrid.dataProvider (this automatically generates a column for each field in the first item), set DataGrid.columnNames to specify which fields will be displayed, or use the constructor for the DataGridColumn class to create columns and call DataGrid.addColumn() to add them to the grid.

    To format columns, either set up style properties for the entire data grid, or define DataGridColumn objects, set up their style formats individually, and add them to the data grid.

  • Cell

    This is a view object responsible for rendering the individual fields of each item. To communicate with the data grid, these components must implement the CellRenderer interface (see CellRenderer API). For a basic data grid, a cell is a built-in ActionScript TextField object.

DataGrid parameters

The following are authoring parameters that you can set for each DataGrid component instance in the Property inspector or in the Component Inspector panel:

multipleSelection A Boolean value that indicates whether multiple items can be selected (true) or not (false). The default value is false.

rowHeight The height of each row, in pixels. Changing the font size does not change the row height. The default value is 20.

editable A Boolean value that indicates whether the grid is editable (true) or not (false). The default value is false.

You can write ActionScript to control these and additional options for the DataGrid component using its properties, methods, and events. For more information, see DataGrid class (Flash Professional only).

Creating an application with the DataGrid component

To create an application with the DataGrid component, you must first determine where your data is coming from. The data for a grid can come from a recordset that is fed from a database query in Macromedia ColdFusion, Java, or .Net using Flash Remoting. Data can also come from a data set or an array. To pull the data into a grid, you set the DataGrid.dataProvider property to the recordset, data set, or array. You can also use the methods of the DataGrid and DataGridColumn classes to create data locally. Any Array object in the same frame as a DataGrid component copies the methods, properties, and events of the DataProvider class.

To use Flash Remoting to add a DataGrid component to an application:

  1. In Flash, select File > New and select Flash Document.
  2. In the Components panel, double-click the DataGrid component to add it to the Stage.
  3. In the Property inspector, enter the instance name myDataGrid.
  4. In the Actions panel on Frame 1, enter the following code:
    myDataGrid.dataProvider = recordSetInstance;

    The Flash Remoting recordset recordSetInstance is assigned to the dataProvider property of myDataGrid.

  5. Select Control > Test Movie.

To use a local data provider to add a DataGrid component to an application:

  1. In Flash, select File > New and select Flash Document.
  2. In the Components panel, double-click the DataGrid component to add it to the Stage.
  3. In the Property inspector, enter the instance name myDataGrid.
  4. In the Actions panel on Frame 1, enter the following code:
    myDP = new Array({name:"Chris", price:"Priceless"}, {name:"Nigel", price:"Cheap"});
myDataGrid.dataProvider = myDP;

    The name and price fields are used as the column headings, and their values fill the cells in each row.

  5. Select Control > Test Movie.


Customizing the DataGrid component (Flash Professional only)

You can transform a DataGrid component horizontally and vertically during authoring and runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()). If there is no horizontal scroll bar, column widths adjust proportionally. If column (and therefore, cell) size adjustment occurs, then text in the cells may be clipped.

Using styles with the DataGrid component

You can set style properties to change the appearance of a DataGrid component. The DataGrid component inherits Halo styles from the List component. (For more information, see Using styles with the List component.) The DataGrid component also supports the following Halo styles:

Style | Description
backgroundColor | The background color can be set for the whole grid or for each column.
labelStyle | The font style can be set for the whole grid or for each column.
headerStyle | A CSS Style Declaration for the column header that can be applied to a grid or column.
vGridLines | A Boolean value that indicates whether to show vertical grid lines (true) or not (false).
hGridLines | A Boolean value that indicates whether to show horizontal grid lines (true) or not (false).
vGridLineColor | The color of the vertical grid lines.
hGridLineColor | The color of the horizontal grid lines.
headerColor | The color of the column headers.

If the above table indicates that a style can be set for a column, you can use the following syntax to set the style:

grid.getColumnAt(3).setStyle("backgroundColor", 0xff00aa)

Using skins with the DataGrid component

The skins that the DataGrid component uses to represent its visual states are included in the subcomponents from which the data grid is composed (ScrollPane and RectBorder). For information about their skins, see Using skins with the ScrollPane component and Using skins with the List component.

The rollover and selection underlays, however, use the ActionScript Drawing API. To skin these portions of the data grid while authoring, modify the ActionScript code in the skin symbols in the Flash UI Components 2/Themes/MMDefault/datagrid/ skins states folder in the library of one of the themes FLA files. For more information, see About skinning components.


DataGrid class (Flash Professional only)

Inheritance mx.core.UIObject > mx.core.UIComponent > mx.core.View > mx.core.ScrollView > mx.controls.listclasses.ScrollSelectList > mx.controls.List

ActionScript Class Name mx.controls.DataGrid

Each component class has a version property, which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.DataGrid.version);

Note: The following code returns undefined: trace(myDataGridInstance.version);.

Method summary for the DataGrid class

Method | Description
DataGrid.addColumn() | Adds a column to the data grid.
DataGrid.addColumnAt() | Adds a column to the data grid at a specific location.
DataGrid.addItem() | Adds an item to the data grid.
DataGrid.addItemAt() | Adds an item to the data grid at a specific location.
DataGrid.editField() | Replaces the cell data at a specified location.
DataGrid.getColumnAt() | Gets a reference to a column at a specified location.
DataGrid.getColumnIndex() | Gets the index of the column.
DataGrid.removeAllColumns() | Removes all columns from a data grid.
DataGrid.removeColumnAt() | Removes a column from a data grid at a specified location.
DataGrid.replaceItemAt() | Replaces an item at a specified location with another item.
DataGrid.spaceColumnsEqually() | Spaces all columns equally.

Inherits all properties from UIObject and UIComponent.

Property summary for the DataGrid class

Property | Description
DataGrid.columnCount | Read-only. The number of columns that are displayed.
DataGrid.columnNames | An array of field names within each item that are displayed as columns.
DataGrid.dataProvider | The data model for a data grid.
DataGrid.editable | A Boolean value that indicates whether the data grid is editable (true) or not (false).
DataGrid.focusedCell | Defines the cell that has focus.
DataGrid.headerHeight | The height of the column headers, in pixels.
DataGrid.hScrollPolicy | Indicates whether a horizontal scroll bar is present ("on"), not present ("off"), or appears when necessary ("auto").
DataGrid.resizableColumns | A Boolean value that indicates whether the columns are resizable (true) or not (false).
DataGrid.selectable | A Boolean value that indicates whether the data grid is selectable (true) or not (false).
DataGrid.showHeaders | A Boolean value that indicates whether the column headers are visible (true) or not (false).
DataGrid.sortableColumns | A Boolean value that indicates whether the columns are sortable (true) or not (false).

Event summary for the DataGrid class

Event | Description
DataGrid.cellEdit | Broadcast when the cell value has changed.
DataGrid.cellFocusIn | Broadcast when a cell receives focus.
DataGrid.cellFocusOut | Broadcast when a cell loses focus.
DataGrid.cellPress | Broadcast when a cell is pressed.
DataGrid.change | Broadcast when an item has been selected.
DataGrid.columnStretch | Broadcast when a column is resized by a user.
DataGrid.headerRelease | Broadcast when a user presses and releases a header.


DataGrid.addColumn()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.addColumn(dataGridColumn)
myDataGrid.addColumn(name)

Parameters

dataGridColumn An instance of the DataGridColumn class.

name A string that indicates the name of a new DataGridColumn object to be inserted.

Returns

A reference to the DataGridColumn object that was added.

Description

Method; adds a new column to the end of the data grid. For more information, see DataGridColumn class (Flash Professional only).

Example

The following code adds a new DataGridColumn object named Purple:

import mx.controls.gridclasses.DataGridColumn;
myGrid.addColumn(new DataGridColumn("Purple"));


DataGrid.addColumnAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

myDataGrid.addColumnAt(index, name)

Usage 2:

myDataGrid.addColumnAt(index, dataGridColumn)

Parameters

index The index position at which the DataGridColumn object is added. The first position is 0.

name A string that indicates the name of the DataGridColumn object. You must specify either the index parameter or the dataGridColumn parameter.

dataGridColumn An instance of the DataGridColumn class.

Returns

A reference to the DataGridColumn object that was added.

Description

Method; adds a new column at the specified position. Columns are shifted to the right and their indexes are incremented. For more information, see DataGridColumn class (Flash Professional only).

Example

The following example inserts a new DataGridColumn object called "Green" at the second and fourth columns:

import mx.controls.gridclasses.DataGridColumn;
myGrid.addColumnAt(1, "Green");
myGrid.addColumnAt(3, new DataGridColumn("Purple"));


DataGrid.addItem()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.addItem(item)

Parameters

item An instance of an object to be added to the grid.

Returns

A reference to the instance that was added.

Description

Method; adds an item to the end of the grid (after the last item index).

Note: This differs from the List.addItem() method in that an object is passed rather than a string.

Example

The following example adds a new object to the grid myGrid:

var anObject= {name:"Jim!!", age:30};
var addedObject = myGrid.addItem(anObject);


DataGrid.addItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.addItemAt(index, item)

Parameters

index The order (among the child nodes) in which the node should be added. The first position is 0.

item A string that displays the node.

Returns

A reference to the object instance that was added.

Description

Method; adds an item to the grid at the position specified.

Example

The following example inserts an object instance to the grid at index position 4:

var anObject= {name:"Jim!!", age:30};
var addedObject = myGrid.addItemAt(4, anObject);


DataGrid.cellEdit

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.cellEdit = function(eventObject){
  // insert your code here
}
myDataGridInstance.addEventListener("cellEdit", listenerObject)

Description

Event; broadcast to all registered listeners when cell value has changed.

V2 components use a dispatcher/listener event model. The DataGrid component dispatches a cellEdit event when the value of a cell has changed, and the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.cellEdit event's event object has four additional properties:

columnIndex A number that indicates the index of the target column.

itemIndex A number that indicates the index of the target row.

oldValue The previous value of the cell.

type The string "cellEdit".

For more information, see Event Objects.

Example

In the following example, a handler called myDataGridListener is defined and passed to the myDataGrid.addEventListener() method as the second parameter. The event object is captured by the cellEdit handler in the eventObject parameter. When the cellEdit event is broadcast, a trace statement is sent to the Output panel, as follows:

myDataGridListener = new Object();
myDataGridListener.cellEdit = function(event){
  var cell = "(" + event.columnIndex + ", " + event.itemIndex + ")";
  trace("The value of the cell at " + cell + " has changed");
}
myDataGrid.addEventListener("cellEdit", myDataGridListener);

Note: The grid must be editable for the above code to work.


DataGrid.cellFocusIn

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.cellFocusIn = function(eventObject){
  // insert your code here
}
myDataGridInstance.addEventListener("cellFocusIn", listenerObject)

Description

Event; broadcast to all registered listeners when a particular cell receives focus. This event is broadcast after any previously edited cell's editCell and cellFocusOut events are broadcast.

V2 components use a dispatcher/listener event model. When a DataGrid component dispatches a cellFocusIn event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.cellFocusIn event's event object has three additional properties:

columnIndex A number that indicates the index of the target column.

itemIndex A number that indicates the index of the target row.

type The string "cellFocusIn".

For more information, see Event Objects.

Example

In the following example, a handler called myListener is defined and passed to the grid.addEventListener() method as the second parameter. The event object is captured by the cellFocusIn handler in the eventObject parameter. When the cellFocusIn event is broadcast, a trace statement is sent to the Output panel, as follows:

var myListener = new Object();
myListener.cellFocusIn = function(event) {
    var cell = "(" + event.columnIndex + ", " + event.itemIndex + ")";
    trace("The cell at " + cell + " has gained focus");
};
grid.addEventListener("cellFocusIn", myListener);

Note: The grid must be editable for the above code to work.


DataGrid.cellFocusOut

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.cellFocusOut = function(eventObject){
  // insert your code here
}
myDataGridInstance.addEventListener("cellFocusOut", listenerObject)

Description

Event; broadcast to all registered listeners whenever a user moves off a cell that has focus. You can use the event object properties to isolate the cell that was left. This event is broadcast after the cellEdit event and before any subsequent cellFocusIn events are broadcast by the next cell.

V2 components use a dispatcher/listener event model. When a DataGrid component dispatches a cellFocusOut event, the event is handled by a function (also called a handler) that is attached to a listener object that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.cellFocusOut event's event object has three additional properties:

columnIndex A number that indicates the index of the target column. The first position is 0.

itemIndex A number that indicates the index of the target row. The first position is 0.

type The string "cellFocusOut".

For more information, see Event Objects.

Example

In the following example, a handler called myListener is defined and passed to the grid.addEventListener() method as the second parameter. The event object is captured by the cellFocusOut handler in the eventObject parameter. When the cellFocusOut event is broadcast, a trace statement is sent to the Output panel, as follows:

var myListener = new Object();
myListener.cellFocusOut = function(event) {
    var cell = "(" + event.columnIndex + ", " + event.itemIndex + ")";
    trace("The cell at " + cell + " has lost focus");
};
grid.addEventListener("cellFocusOut", myListener);

Note: The grid must be editable for the above code to work.


DataGrid.cellPress

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.cellPress = function(eventObject){
  // insert your code here
}
myDataGridInstance.addEventListener("cellPress", listenerObject)

Description

Event; broadcast to all registered listeners when a user presses the mouse button on a cell.

V2 components use a dispatcher/listener event model. When a DataGrid component broadcasts a cellPress event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.cellPress event's event object has three additional properties:

columnIndex A number that indicates the index of the target column. The first position is 0.

itemIndex A number that indicates the index of the target row. The first position is 0.

type The string "cellPress".

For more information, see Event Objects.

Example

In the following example, a handler called myListener is defined and passed to the grid.addEventListener() method as the second parameter. The event object is captured by the cellPress handler in the eventObject parameter. When the cellPress event is broadcast, a trace statement is sent to the Output panel, as follows:

var myListener = new Object();
myListener.cellPress = function(event) {
    var cell = "(" + event.columnIndex + ", " + event.itemIndex + ")";
    trace("The cell at " + cell + " has been clicked");
};
grid.addEventListener("cellPress", myListener);


DataGrid.change

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.change = function(eventObject){
  // insert your code here
}
myDataGridInstance.addEventListener("change", listenerObject)

Description

Event; broadcast to all registered listeners when an item has been selected.

V2 components use a dispatcher/listener event model. When a DataGrid component dispatches a change event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.change event's event object has one additional property, type, and its value is "change". For more information, see Event Objects.

Example

In the following example, a handler called myListener is defined and passed to the grid.addEventListener() method as the second parameter. The event object is captured by change handler in the eventObject parameter. When the change event is broadcast, a trace statement is sent to the Output panel, as follows:

var myListener = new Object();
myListener.change = function(event) {
    trace("The selection has changed to " + event.target.selectedIndex);
};
grid.addEventListener("change", myListener);


DataGrid.columnCount

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.columnCount

Description

Property (read-only); the number of columns displayed.

Example

The following example gets the number of displayed columns in the DataGrid instance grid:

var c = grid.columnCount;


DataGrid.columnNames

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.columnNames

Description

Property; an array of field names within each item that are displayed as columns.

Example

The following example tells the grid instance to display only these three fields as columns:

grid.columnNames = ["Name", "Description", "Price"];


DataGrid.columnStretch

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.columnStretch = function(eventObject){
  // insert your code here
}
myDataGridInstance.addEventListener("columnStretch", listenerObject)

Description

Event; broadcast to all registered listeners when a user horizontally resizes a column.

V2 components use a dispatcher/listener event model. When a DataGrid component dispatches a columnStretch event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.columnStretch event's event object has two additional properties:

columnIndex A number that indicates the index of the target column. The first position is 0.

type The string "columnStretch".

For more information, see Event Objects.

Example

In the following example, a handler called myListener is defined and passed to the grid.addEventListener() method as the second parameter. The event object is captured by the columnStretch handler in the eventObject parameter. When the columnStretch event is broadcast, a trace statement is sent to the Output panel, as follows:

var myListener = new Object();
myListener.columnStretch = function(event) {
    trace("column " + event.columnIndex + " was resized");
};
grid.addEventListener("columnStretch", myListener);


DataGrid.dataProvider

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.dataProvider

Description

Property; the data model for items viewed in a DataGrid component.

The data grid adds methods to the prototype of the Array class so that each Array object conforms to the DataProvider interface (see DataProvider.as in the Classes/mx/controls/listclasses folder). Any array that exists in the same frame or screen as a data grid automatically has all the methods (addItem(), getItemAt(), and so on) needed for it to be the data model of a data grid, and can be used to broadcast data model changes to multiple components.

In a DataGrid component you specify fields for display in the DataGrid.columnNames property.

If you don't define the column set (by setting the DataGrid.columnNames property or by calling the DataGrid.addColumn() method) for the data grid before the DataGrid.dataProvider property has been set, the data grid generates columns for each field in the data provider's first item, once that item arrives.

Any object that implements the DataProvider interface can be used as a data provider for a data grid (including Flash Remoting recordsets, data sets, and arrays).

Example

The following example creates an array to be used as a data provider and assigns it directly to the dataProvider property:

grid.dataProvider = [{name:"Chris", price:"Priceless"}, {name:"Nigel", Price:"cheap"}];

The following example creates a new Array object that is decorated with the DataProvider class. It uses a for loop to add 20 items to the grid:

myDP = new Array();
for (var i=0; i<20; i++)
  myDP.addItem({name:"Nivesh", price:"Priceless"});
list.dataProvider = myDP


DataGrid.editable

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.editable

Description

Property; determines whether the data grid can be edited by a user (true) or not (false). This property must be true in order for individual columns to be editable and for any cell to receive focus. The default value is false.

Example

The following example sets the scroll position to the top of the display:

myDataGrid.editable = true;


DataGrid.editField()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.editField(index, colName, data)

Parameters

index The index of the target cell. This number is zero-based.

colName A string indicating the name of the column (field) that contains the target cell.

data The value to be stored in the target cell. This parameter can be of any data type.

Returns

The data that was in the cell.

Description

Method; replaces the cell data at the specified location.

Example

The following example places a value in the grid:

var prevValue = myGrid.editField(5, "Name", "Neo");


DataGrid.focusedCell

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.focusedCell

Description

Property; in editable mode only, an object instance that defines the cell that has focus. The object must have the fields columnIndex and itemIndex, which are both integers that indicate the index of the column and item of the cell. The origin is (0,0). The default value is undefined.

Example

The following example sets the focused cell to the third column, fourth row:

grid.focusedCell = {columnIndex:2, itemIndex:3};


DataGrid.getColumnAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index)

Parameters

index The index of the DataGridColumn object to be returned. This number is zero-based.

Returns

A DataGridColumn object.

Description

Method; gets a reference to the DataGridColumn object at the specified index.

Example

The following example gets the DataGridColumn object at index 4:

var aColumn = myGrid.getColumnAt(4);


DataGrid.getColumnIndex()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnIndex(index)

Parameters

index The index of the DataGridColumn object to be returned.

Returns

A DataGridColumn object.

Description

Method; gets a reference to the DataGridColumn object at the specified index.


DataGrid.headerHeight

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.headerHeight

Description

Property; the height of the header bar of the data grid. The default value is 20.

Example

The following example sets the scroll position to the top of the display:

myDataGrid.headerHeight = 30;


DataGrid.headerRelease

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.headerRelease = function(eventObject){
  // insert your code here
}
myDataGridInstance.addEventListener("headerRelease", listenerObject)

Description

Event; broadcast to all registered listeners when a column header has been released. You can use this event with the DataGridColumn.sortOnHeaderRelease property to prevent automatic sorting and to allow you to sort as you like.

V2 components use a dispatcher/listener event model. When the DataGrid component dispatches a headerRelease event, the event is handled by a function (also called a handler) that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The DataGrid.headerRelease event's event object has two additional properties:

columnIndex A number that indicates the index of the target column.

type The string "headerRelease".

For more information, see Event Objects.

Example

In the following example, a handler called myListener is defined and passed to the grid.addEventListener() method as the second parameter. The event object is captured by the headerRelease handler in the eventObject parameter. When the headerRelease event is broadcast, a trace statement is sent to the Output panel, as follows:

var myListener = new Object();
myListener.headerRelease = function(event) {
    trace("column " + event.columnIndex + " header was pressed");
};
grid.addEventListener("headerRelease", myListener);


DataGrid.hScrollPolicy

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.hScrollPolicy

Description

Property; specifies whether the data grid has a horizontal scroll bar. This property can have one of three values: "on", "off", and "auto". The default value is "off".

If you set hScrollPolicy to "off", columns scale proportionally to accommodate the finite width.

Example

The following example sets horizontal scroll policy to automatic:

myDataGrid.hScrollPolicy = "auto";


DataGrid.removeAllColumns()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.removeAllColumns()

Parameters

None.

Returns

Nothing.

Description

Method; removes all DataGridColumn objects from the data grid. Calling this method has no effect on the data provider.

Example

The following example removes all DataGridColumn objects from myDataGrid:

myDataGrid.removeAllColumns();


DataGrid.removeColumnAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.removeColumnAt(index)

Parameters

index The index of the column to remove.

Returns

A reference to the DataGridColumn object that was removed.

Description

Method; removes the DataGridColumn object at the specified index.

Example

The following example removes the DataGridColumn object at index 2 in myDataGrid:

myDataGrid.removeColumnAt(2);


DataGrid.replaceItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.replaceItemAt(index, item)

Parameters

index The index of the item to be replaced.

item An object that is the item value to use as a replacement.

Returns

The previous value.

Description

Method; replaces the item at a specified index.

Example

The following example replaces the item at index 4 with the item defined in aNewValue:

var aNewValue = {name:"Jim", value:"tired"};
var prevValue = myGrid.replaceItemAt(4, aNewValue);


DataGrid.resizableColumns

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.resizableColumns

Description

Property; a Boolean value that determines whether the columns of the grid can be stretched by the viewer (true) or not (false). This property must be true for individual columns to be resizable. The default value is true.

Example

The following example prevents users from resizing columns:

myDataGrid.resizableColumns = false;


DataGrid.selectable

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.selectable

Description

Property; a Boolean value that determines whether a user can select the data grid (true) or not (false). The default value is true.

Example

The following example prevents the grid from being selected:

myDataGrid.selectable = false;


DataGrid.showHeaders

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.showHeaders

Description

Property; a Boolean value that indicates whether the data grid displays the column headers (true) or not (false). Column headers are shaded to differentiate them from the other rows in a grid. Users can click column headers to sort the contents of the column if DataGrid.sortableColumns is set to true. The default value is true.

Example

The following example hides the column headers:

myDataGrid.showHeaders = false;

See also

DataGrid.sortableColumns


DataGrid.sortableColumns

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.sortableColumns

Description

Property; a Boolean value that determines whether the columns of the data grid can be sorted (true) or not (false) when a user clicks the column headers. This property must be true for individual columns to be sortable. This property must be set to true in order to broadcast the headerRelease event. The default value is true.

Example

The following example turns off sorting:

myDataGrid.sortableColumns = false;

See also

DataGrid.headerRelease


DataGrid.spaceColumnsEqually()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.spaceColumnsEqually()

Parameters

None.

Returns

Nothing.

Description

Method; respaces the columns equally.

Example

The following example respaces the columns of myGrid when any column header is pressed and released:

myGrid.showHeaders = true
myGrid.dataProvider = [{guitar:"Flying V", name:"maggot"}, {guitar:"SG", name:"dreschie"}, {guitar:"jagstang", name:"vitapup"}];
gridLO = new Object();
gridLO.headerRelease = function(){
  myGrid.spaceColumnsEqually();
}
myGrid.addEventListener("headerRelease", gridLO);


DataGridColumn class (Flash Professional only)

ActionScript Class Name mx.controls.gridclassesDataGridColumn

You can create and configure DataGridColumn objects to use as columns of a data grid. Many of the methods of the DataGrid class are dedicated to managing DataGridColumn objects. DataGridColumn objects are stored in an zero-based array in the data grid; 0 is the leftmost column. After columns have been added or created, you can call DataGrid.getColumnAt(index) to access them.

There are three ways to add or create columns in a grid. If you want to configure your columns, it is best to use either the second or third way before you add data to a data grid so you don't have to create columns twice.

  • Adding a DataProvider or an item with multiple fields to a grid that has no configured DataGridColumn objects automatically generates columns for every field in the reverse order of the for..in loop.
  • DataGrid.columnNames takes in the field names of the desired item fields and generates DataGridColumn objects, in order, for each field listed. This approach allows you to select and order columns quickly with a minimal amount of configuration. This approach removes any previous column information.
  • The most flexible way to add columns is to prebuild them as DataGridColumn objects and add them to the data grid using DataGrid.addColumn(). This approach is useful because it lets you add columns with proper sizing and formatting before the columns ever reach the grid (which reduces processor demand). For more information, see Constructor for the DataGridColumn class.

Property summary for the DataGridColumn class

Property | Description
DataGridColumn.cellRenderer | The linkage identifier of a symbol to be used to display the cells in this column.
DataGridColumn.columnName | Read-only. The name of the field associated with the column.
DataGridColumn.editable | A Boolean value that indicates whether a column is editable (true) or not (false).
DataGridColumn.headerRenderer | The name of a class to be used to display the header of this column.
DataGridColumn.headerText | The text for the header of this column.
DataGridColumn.labelFunction | A function that determines which field of an item to display.
DataGridColumn.resizable | A Boolean value that indicates whether a column is resizable (true) or not (false).
DataGridColumn.sortable | A Boolean value that indicates whether a column is sortable (true) or not (false).
DataGridColumn.sortOnHeaderRelease | A Boolean value that indicates whether a column is sorted (true) or not (false) when a user presses a column header.
DataGridColumn.width | The width of a column, in pixels.

Constructor for the DataGridColumn class

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

new DataGridColumn(name)

Parameters

name A string that indicates the name of the DataGridColumn object. This parameter is the field of each item to display.

Returns

Nothing.

Description

Constructor; creates a DataGridColumn object. Use this constructor to create columns to add to a DataGrid component. After you create the DataGridColumn objects, you can add them to a data grid by calling DataGrid.addColumn().

Example

The following example creates a DataGridColumn object called Location:

import mx.controls.gridclasses.DataGridColumn;
var column = new DataGridColumn("Location");


DataGridColumn.cellRenderer

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).cellRenderer

Description

Property; a linkage identifier for a symbol to be used to display cells in this column. Any class used for this property must implement the CellRenderer interface (see CellRenderer API.) The default value is undefined.

Example

The following example uses a linkage identifier to set a new cell renderer:

myGrid.getColumnAt(3).cellRenderer = "MyCellRenderer";


DataGridColumn.columnName

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).columnName

Description

Property (read-only); the name of the field associated with this column. The default value is the name called in the DataGridColumn constructor.

Example

The following example assigns the column name of the column at the third index position to the variable name:

var name = myGrid.getColumnAt(3).columnName;

See also

Constructor for the DataGridColumn class


DataGridColumn.editable

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).editable

Description

Property; determines whether the column can be edited by a user (true) or not (false). The DataGrid.editable property must be true in order for individual columns to be editable, even when DataGridColumn.editable is set to true. The default value is true.

Example

The following example makes the first column in a grid uneditable:

myDataGrid.getColumnAt(0).editable = false;

See also

DataGrid.editable


DataGridColumn.headerRenderer

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).headerRenderer

Description

Property; a string that indicates a class name to be used to display the header of this column. Any class used for this property must implement the CellRenderer interface (see CellRenderer API). The default value is undefined.

Example

The following example uses a linkage identifier to set a new header renderer:

myGrid.getColumnAt(3).headerRenderer = "MyHeaderRenderer";


DataGridColumn.headerText

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).headerText

Description

Property; the text in the column header. The default value is the column name.

Example

The following example sets the column header text to "The Price":

var myColumn = new DataGridColumn("price");
myColumn.headerText = "The Price";


DataGridColumn.labelFunction

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).labelFunction

Description

Property; specifies a function to determine which field (or field combination) of each item to display. This function receives one parameter, item, which is the item being rendered, and must return a string representing the text to display. This property can be used to create virtual columns that have no equivalent field in the item.

Example

The following example creates a virtual column:

var myCol = myGrid.addColumn("Subtotal");
myCol.labelFunction = function(item) {
  return "$" + (item.price + (item.price * salesTax));
};


DataGridColumn.resizable

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).resizable

Description

Property; a Boolean value that indicates whether a column can be resized by a user (true) or not (false). The DataGrid.resizableColumns property must be set to true for this property to take effect. The default value is true.

Example

The following example prevents the column at index 1 from being resized:

myGrid.getColumnAt(1).resizable = false;


DataGridColumn.sortable

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).sortable

Description

Property; a Boolean value that indicates whether a column can be sorted by a user (true) or not (false). The DataGrid.sortableColumns property must be set to true for this property to take effect. The default value is true.

Example

The following example prevents the column at index 1 from being sorted:

myGrid.getColumnAt(1).sortable = false;


DataGridColumn.sortOnHeaderRelease

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).sortOnHeaderRelease

Description

Property; a Boolean value that indicates whether the column is sorted automatically (true) or not (false) when a user clicks on a header. This property can be set to true only if DataGridColumn.sortable is set to true. If DataGridColumn.sortOnHeaderRelease is set to false, you can catch the headerRelease event and perform your own sort.

The default value is true.

Example

The following example allows you to catch the headerRelease event to perform your own sort:

myGrid.getColumnAt(7).sortOnHeaderRelease = false;


DataGridColumn.width

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDataGrid.getColumnAt(index).width

Description

Property; a number that indicates the width of the column, in pixels. The default value is 50.

Example

The following example makes a column half the size of the default value:

myGrid.getColumnAt(4).width = 25;


About the DataHolder component (Flash Professional only)

The DataHolder component is a repository for data and a means of generating events when that data has changed. Its main purpose is to hold data and act as connector between other components using data binding.

Initially, the DataHolder component has a single bindable property named data. You can add more properties using the Schema tab in the Component Inspector panel (Window > Development Panels > Component Inspector). For more information on using the Schema tab, see Working with schemas in the Schema tab (Flash Professional only).

You can assign any type of data to a DataHolder property, either by creating a binding between the data and another property, or by using your own ActionScript code. Whenever the value of that data changes, the DataHolder component emits an event whose name is the same as the property, and any bindings associated with that property are executed.

The DataHolder component is useful when you can't directly bind components (such as connectors, user interface components, or DataSet components) together. Below are some scenarios in which you might use a DataHolder component:

  • If a data value is generated by ActionScript, you might want to bind it to some other components. In this case, you could have a DataHolder component that contains properties that are bound as desired. Whenever new values are assigned to those properties (by means of ActionScript, for example) those values will be distributed to the data-bound object.
  • You might have a data value that results from a complex indexed data binding, as in the following diagram.

    In this case it is convenient to bind the data value to a DataHolder component (called DataModel in this illustration) and then use that for bindings to the user interface.


Creating an application with the DataHolder component (Flash Professional only)

In this example, you add an array property to a DataHolder component's schema (an array) whose value is determined by ActionScript code that you write. You then bind that array property to the dataProvider property of a DataGrid component by using the Bindings tab in the Component Inspector panel.

To use the DataHolder component in a simple application:

  1. In Flash MX Professional 2004, create a new file.
  2. Open the Components panel (Window > Development Panels > Components), drag a DataHolder component to the Stage, and name it dataHolder.
  3. Drag a DataGrid component to the Stage and name it namesGrid.
  4. Select the DataHolder component and open the Component Inspector panel (Window > Development Panels > Component Inspector).
  5. Click the Schema tab in the Component Inspector panel.
  6. Click the Add Component Property button (+) located in the top pane of the Schema tab.
  7. In the bottom pane of the Schema tab, type namesArray in the Field Name field, and select Array from the Data Type pop-up menu.
  8. Click the Bindings tab in the Component Inspector panel, and add a binding between the namesArray property of the DataHolder component and the dataProvider property of the DataGrid component.

    For more information on creating bindings with the Bindings tab, see Working with bindings in the Bindings tab (Flash Professional only).

  9. In the Timeline (Window > Timeline), select the first frame on Layer 1 and open the Actions panel (Window > Development Panels > Actions).
  10. Enter the following code in the Actions panel:
    dataHolder.namesArray= [{name:"Tim"},{name:"Paul"},{name:"Jason"}];

    This code populates the namesArray array with several objects. When this variable assignment executes, the binding that you established previously between the DataHolder component and the DataGrid component executes.

  11. Test the file by selecting Control > Test Movie.

Property summary for the DataHolder class

Property | Description
DataHolder.data | Default bindable property for DataHolder component.


DataHolder.data

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

dataHolder.data

Description

Property; the default item in a DataHolder object's schema. This property is not a "permanent" member of the DataHolder component. Rather, it is the default bindable property for each instance of the component. You can add your own bindable properties, or delete the default data property, by using the Schema tab in the Component Inspector panel.

For more information on using the Schema tab, see Working with schemas in the Schema tab (Flash Professional only).

Example

For an example of using this component, see Creating an application with the DataHolder component (Flash Professional only).


About the DataProvider API

ActionScript class name mx.controls.listclasses.DataProvider

The DataProvider API is a set of methods and properties that a data source needs to have in order to have a List-based class communicate with it. Arrays, RecordSets, and the DataSet all implement this API. You can create a DataProvider-compliant class by implementing all the methods and properties described in this document. A List-based component could then use that class as a data provider.

The methods of the DataProvider API allow you to query and modify the data in any component that displays data (also called a view). The DataProvider API also broadcasts change events when the data changes. Multiple views can use the same data provider and all receive the change events.

A data provider is a linear collection (like an array) of items. Each item is an object composed of many fields of data. You can access these items through their index (as you can with an array), using DataProvider.getItemAt().

The most common case for using data providers is with arrays. Data-aware components apply all the methods of the DataProvider API to Array.prototype when an Array object is in the same frame or screen as a data-aware component. This allows you to use any existing array as the data for views that have a dataProvider property.

Because of the DataProvider API, the v2 components that provide views for data (DataGrid, List, Tree, and so on) can also display Flash Remoting RecordSets and data from the DataSet component. The DataProvider API is the language with which data-aware components communicate with their data providers.

In the Macromedia Flash documentation, "DataProvider" is the name of the API, dataProvider is a property of each component that acts as a view for data, and "data provider" is the generic term for a data source.

Methods of the DataProvider API

Name | Description
DataProvider.addItem() | Adds an item at the end of the data provider.
DataProvider.addItemAt() | Adds an item to the data provider at the specified position.
DataProvider.editField() | Changes one field of the data provider.
DataProvider.getEditingData() | Gets the data for editing from a data provider.
DataProvider.getItemAt() | Gets a reference to the item at a specified position.
DataProvider.getItemID() | Returns the unique ID of the item.
DataProvider.removeAll() | Removes all items from a data provider.
DataProvider.removeItemAt() | Removes an item from a data provider at a specified position.
DataProvider.replaceItemAt() | Replaces the item at a specified position with another item.
DataProvider.sortItems() | Sorts the items in a data provider.
DataProvider.sortItemsBy() | Sorts the items in a data provider according to a specified compare function.

Properties of the DataProvider API

Name | Description
DataProvider.length | The number of items in a data provider.

Events of the DataProvider API

Name | Description
DataProvider.modelChanged | Broadcast when the data provider is changed.


DataProvider.addItem()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDP.addItem(item)

Parameters

item An object containing data. This comprises an item in a data provider.

Returns

Nothing.

Description

Method; adds a new item at the end of the data provider.

This method triggers the modelChanged event with the event name addItems.

Example

The following example adds an item to the end of the data provider myDP:

myDP.addItem({ label : "this is an Item"});


DataProvider.addItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDP.addItemAt(index, item)

Parameters

index A number greater than or equal to 0. The position at which to insert the item; the index of the new item.

item An object containing the data for the item.

Returns

Nothing.

Description

Method; adds a new item to the data provider at the specified index. Indices greater than the data provider's length are ignored.

This method triggers the modelChanged event with the event name addItems.

Example

The following example adds an item to the data provider myDP at the fourth position:

myDP.addItemAt(3, {label : "this is the fourth Item"});


DataProvider.editField()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDP.editField(index, fieldName, newData)

Parameters

index A number greater than or equal to 0. The index of the item.

fieldName A string indicating the name of the field in the item to modify.

newData The new data to put in the data provider.

Returns

Nothing.

Description

Method; changes one field of the data provider.

This method triggers the modelChanged event with the event name updateField.

Example

The following code modifies the label field of the third item:

myDP.editField(2, "label", "mynewData");


DataProvider.getEditingData()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDP.getEditingData(index, fieldName)

Parameters

index A number greater than or equal to 0 and less than DataProvider.length. The index of the item to retrieve.

fieldName A string indicating the name of the field being edited.

Returns

The editable formatted data to be used.

Description

Method; retrieves data for editing from a data provider. This allows the data model to provide different formats of data for editing and displaying.

Example

The following code gets an editable string for the price field:

trace(myDP.getEditingData(4, "price");


DataProvider.getItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDP.getItemAt(index)

Parameters

index A number greater than or equal to 0 and less than DataProvider.length. The index of the item to retrieve.

Returns

A reference to the retrieved item; undefined if the index is out of range.

Description

Method; retrieves a reference to the item at a specified position.

Example

The following code displays the label of the fifth item:

trace(myDP.getItemAt(4).label);


DataProvider.getItemID()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 Professional.

Usage

myDP.getItemID(index)

Parameters

index A number greater than or equal to 0.

Returns

A number that is the unique ID of the item.

Description

Method; returns a unique ID for the item. This method is primarily used to track selection. This ID is used in data-aware components to keep lists of what items are selected.

Example

This example gets the ID of the fourth item:

var ID = myDP.getItemID(3);


DataProvider.modelChanged

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.modelChanged = function(eventObject){
  // insert your code here
}
myMenu.addEventListener("modelChanged", listenerObject

Description

Event; broadcast to all of its view listeners whenever the data provider is modified. A listener is typically added to a model by assigning its dataProvider property.

V2 components use a dispatcher/listener event model. When a data provider changes in some way, it broadcasts a modelChanged event, and data-aware components catch it to update their displays to reflect the changes in data.

The Menu.modelChanged event's event object has five additional properties:

  • eventName The eventName property is used to subcategorize modelChanged events. Data-aware components use this information to avoid completely refreshing the component instance (view) that is using the data provider. The following are the supported values of the eventName property:
    • updateAll The entire view needs refreshing, excluding scroll position.
    • addItems A series of items have been added.
    • removeItems A series of items have been deleted.
    • updateItems A series of items need refreshing.
    • sort The data has been sorted.
    • updateField A field within an item has to be changed and needs refreshing.
    • updateColumn An entire field's definition within the dataProvider needs refreshing.
    • filterModel The model has been filtered, and the view needs refreshing (reset scrollPosition).
    • schemaLoaded The field's definition of the dataProvider has been declared.
  • firstItem The index of the first affected item.
  • lastItem The index of the last affected item. The value equals firstItem if only one item is affected.
  • removedIDs An array of the item identifiers that were removed.
  • fieldName A string indicating the name of the field that is affected.

For more information about event objects, see Event Objects.

Example

In the following example, a handler called listener is defined and passed to the addEventListener() method as the second parameter. The event object is captured by the modelChanged handler in the evt parameter. When the modelChanged event is broadcast, a trace statement is sent to the Output panel, as follows:

listener = new Object();
listener.modelChanged = function(evt){
    trace(evt.eventName);
}
myList.addEventListener("modelChanged", listener);


DataProvider.length

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDP.length

Description

Property (read-only); the number of items in the data provider.

Example

This example sends the number of items in the myArray data provider to the Output panel:

trace(myArray.length);


DataProvider.removeAll()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDP.removeAll()

Parameters

None.

Returns

Nothing.

Description

Method; removes all items in the data provider.

This method triggers the modelChanged event with the event name removeItems.

Example

This example removes all the items in the data provider:

myDP.removeAll();


DataProvider.removeItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDP.removeItemAt(index)

Parameters

index A number greater than or equal to 0. The index of the item to remove.

Returns

Nothing.

Description

Method; removes the item at the specified index. The indices after the removed index collapse by one.

This method triggers the modelChanged event with the event name removeItems.

Example

This example removes the item at the fourth position:

myDP.removeItemAt(3);


DataProvider.replaceItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDP.replaceItemAt(index, item)

Parameters

index A number greater than or equal to 0. The index of the item to change.

item An object that is the new item.

Returns

Nothing.

Description

Method; replaces the content of the item at the specified index.

This method triggers the modelChanged event with the event name removeItems.

Example

This example replaces the item at index 3 with the item with the label "new label":

myDP.replaceItemAt(3, {label : "new label"});


DataProvider.sortItems()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myDP.sortItems([compareFunc], [optionsFlag])

Parameters

compareFunc A reference to a function that is used to compare two items to determine their sort order. For details, see Array.sort() in ActionScript Dictionary Help. This parameter is optional.

optionsFlag Allows you to perform multiple, different types of sorts on a single array without having to replicate the entire array or resort it repeatedly. This parameter is optional.

The following are possible values for optionsFlag:

  • Array.DESCENDING—sorts highest to lowest.
  • Array.CASEINSENSITIVE—sorts case insensitively.
  • Array.NUMERIC—sorts numerically if the two elements being compared are numbers. If they aren't numbers, use a string comparison (which may be case-insensitive if that flag is specified).
  • Array.UNIQUESORT—if two objects in the array are identical or have identical sort fields, this method returns an error code (0) instead of a sorted array.
  • Array.RETURNINDEXEDARRAY—returns an integer index array that is the result of the sort. For example, the following array, if sorted with the optionsFlag parameter containing the value Array.RETURNINDEXEDARRAY, would return the second line of code and the array would remain unchanged:
    ["a", "d", "c", "b"]
[0, 3, 2, 1]

You can combine these options into one value. For example, the following code combines options 3 and 1:

array.sort (Array.NUMERIC | Array.DESCENDING)

Returns

Nothing.

Description

Method; sorts the items in the data provider according to the compare function specified by the compareFunc parameter or according to one or more of the sort options specified by the optionsFlag parameter.

This method triggers the modelChanged event with the event name sort.

Example

This example sorts based on uppercase labels. The items a and b are passed to the function and contain label and data fields:

myList.sortItems(upperCaseFunc);
function upperCaseFunc(a,b){
    return a.label.toUpperCase() > b.label.toUpperCase();
}


DataProvider.sortItemsBy()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myDP.sortItemsBy(fieldName, order, [optionsFlag])

Parameters

fieldName A string specifying the name of the field to use for sorting. This value is usually "label" or "data".

order A string specifying whether to sort the items in ascending order ("ASC") or descending order ("DESC").

optionsFlag Allows you to perform multiple, different types of sorts on a single array without having to replicate the entire array or resort it repeatedly. This parameter is optional.

The following are possible values for optionsFlag:

  • Array.DESCENDING—sorts highest to lowest.
  • Array.CASEINSENSITIVE—sorts case insensitively.
  • Array.NUMERIC—sorts numerically if the two elements being compared are numbers. If they aren't numbers, use a string comparison (which may be case-insensitive if that flag is specified).
  • Array.UNIQUESORT—if two objects in the array are identical or have identical sort fields, this method returns an error code (0) instead of a sorted array.
  • Array.RETURNINDEXEDARRAY—returns an integer index array that is the result of the sort. For example, the following array, if sorted with the optionsFlag parameter containing the value Array.RETURNINDEXEDARRAY, would return the second line of code and the array would remain unchanged:
    ["a", "d", "c", "b"]
[0, 3, 2, 1]

You can combine these options into one value. For example, the following code combines options 3 and 1:

array.sort (Array.NUMERIC | Array.DESCENDING)

Returns

Nothing.

Description

Method; sorts the items in the data provider alphabetically or numerically, in the specified order, using the specified field name. If the fieldName items are a combination of text strings and integers, the integer items are listed first. The fieldName parameter is usually "label" or "data", but advanced programmers may specify any primitive value. You can optionally use the optionsFlag parameter to specify a sorting style.

This method triggers the modelChanged event with the event name sort.

Example

The following code sorts the items in a list in ascending order using the labels of the list items:

myDP.sortItemsBy("label", "ASC");


About the DataSet component (Flash Professional only)

The DataSet component lets you work with data as collections of objects that can be indexed, sorted, searched, filtered, and modified.

The DataSet component functionality includes DataSetIterator, a set of methods for traversing and manipulating a data collection, and DeltaPacket, a set of interfaces and classes for working with updates to a data collection. In most cases, you don't use these classes and interfaces directly; you use them indirectly through methods provided by the DataSet class.

The items managed by the DataSet component are also called transfer objects. A transfer object exposes business data that resides on the server with public attributes or accessor methods for reading and writing data. The DataSet component allows developers to work with sophisticated client-side objects that mirror their server-side counterparts or, in its simplest form, a collection of anonymous objects with public attributes representing the fields within a record of data. For details on transfer objects, see Core J2EE Patterns Transfer Object.

Note: The DataSet component requires Flash Player 7 or later.

Using the DataSet component (Flash Professional only)

You typically use the DataSet component in an application in combination with other components to manipulate and update a data source: a Connector component for connecting to an external data source, user interface components for displaying data from the data source, and a Resolver component for translating updates made to the data set into the appropriate format for sending to the external data source. You can then use data binding to bind properties of these different components together.

For general information on how to manage data within Flash using the DataSet component, see Data management (Flash Professional only).

DataSet component parameters

The following are parameters that you can set for the DataSet component:

itemClassName A string that is the name of the transfer object class that is instantiated each time a new item is created within the DataSet component.

The DataSet component uses transfer objects to represent the data that you retrieve from an external data source. If you leave this parameter blank, the data set creates an anonymous transfer object for you. If you give this parameter a value, the data set instantiates your transfer object whenever new data is added.

Note: You must make a fully qualified reference to this class somewhere within your code to make sure that it gets compiled into your application (such as private var myItem:my.package.myItem;).

filtered A Boolean value that defaults to false. If this parameter is set to true, a filter is applied to the DataSet component so that it contains only the objects that match the filter criteria.

logChanges A Boolean value that defaults to true. If this parameter is set to true, the data set logs all changes to data or method calls.

readOnly A Boolean value that defaults to false. If this parameter is set to true, the data set cannot be modified.

You can write ActionScript to control these and additional options for the DataSet component using its properties, methods, and events. For more information, see DataSet class (Flash Professional only).

Common workflow for the DataSet component

The typical workflow for the DataSet component is as follows.

To use a DataSet component:

  1. Add an instance of the DataSet component to your application and give it an instance name.
  2. Select the Schema tab for the DataSet component and create component properties to represent the persistent fields of the data set.
  3. Load the DataSet component with data from an external data source. For more information, see About loading the DataSet component.
  4. Use the Bindings tab of the Component Inspector panel to bind the data set fields to UI components within your application.

    The UI controls are notified as a new record (transfer object) is selected within the DataSet component, and they are updated accordingly. In addition, the DataSet component is notified when data is modified within a UI control, and the change is tracked using the DeltaPacket.

  5. Call the methods of the DataSet component within your application to manage your data.

    Note: In addition to these steps, you can also bind the DataSet component to a connector and a resolver component to provide a complete solution for accessing, managing, and updating data from an external data source.

Creating an application with the DataSet component

Typically, you use the DataSet component with other user interface components, and often with a Connector component such as the XMLConnector or WebServiceConnector component. The items in the data set are populated by means of the Connector component, or raw ActionScript data, and then bound to user interface controls (such as List or DataGrid components).

To create an application using the DataSet component:

  1. In Flash MX Professional 2004, select File > New. In the Type column, select Flash Document and click OK.
  2. Open the Components panel (Window > Development Panels > Components) if it's not already open.
  3. Drag a DataSet component from the Components panel to the Stage. In the Property inspector, name it userData.
  4. Drag a DataGrid component to the Stage and name it userGrid.
  5. Resize the DataGrid component to be approximately 300 pixels wide and 100 pixels tall.
  6. Drag a Button component to the Stage and name it nextBtn.
  7. In the Timeline, select the first frame on Layer 1 and open the Actions panel (Window > Development Panels > Actions).
  8. Add the following code to the Actions panel:
    var recData = [{id:0, firstName:"Mick", lastName:"Jones"},
              {id:1, firstName:"Joe", lastName:"Strummer"},
              {id:2, firstName:"Paul", lastName:"Simonon"}];
userData.items = recData;

    This populates the DataSet object's items property with an array of objects, each of which has three properties: firstName, lastName, and id.

  9. To bind the contents of the DataSet component to the contents of the DataGrid component, open the Component Inspector panel (Window > Development Panels > Component Inspector) and click the Bindings tab.
  10. Select the DataGrid component (userGrid) on the Stage, and click the Add Binding (+) button in the Component Inspector panel.
  11. In the Add Binding dialog box, select "dataProvider : Array" and click OK.
  12. Double-click the Bound To field in the Component Inspector panel.
  13. In the Bound To dialog box that appears, select "DataSet <userData>" from the Component Path column and then select "dataProvider : Array" from the Schema Location column.
  14. To bind the selected index of the DataSet component to the selected index of the DataGrid component, click the Add Binding (+) button again in the Component Inspector panel.
  15. In the dialog box that appears, select "selectedIndex : Number". Click OK.
  16. Double-click the Bound To field in the Component Inspector panel to open the Bound To dialog box.
  17. In the Component Path field, select "DataSet <userData>" from the Component Path column and then select "selectedIndex : Number" from the Schema Location column.
  18. Select the Button component (nextBtn) and open the Actions panel (Window > Development Panels > Actions), if it is not already open.
  19. Enter the following code in the Actions panel:
    on(click) {
  _parent.userData.next();
}

    This code uses the DataSet.next() method to navigate to the next item in the DataSet object's collection of items. Since you had previously bound the selectedIndex property of the DataGrid object to the same property of the DataSet object, changing the current item in the DataSet object will change the current (selected) item in the DataGrid object, as well.

  20. Save the file, and select Control > Test Movie to test the SWF file.

    The DataGrid object is populated with the specified items. Notice how clicking the button changes the selected item in the DataGrid object.

For a step-by-step example that uses the DataSet component and a resolver component to send updates to a relational database, see Web Service Tutorial: Update the Stock Quote Web Service (Flash Professional Only).


DataSet class (Flash Professional only)

ActionScript Class Name mx.data.components.DataSet

Method summary for the DataSet class

Method | Description
DataSet.addItem() | Adds the specified item to the collection.
DataSet.addSort() | Creates a new sorted view of the items in the collection.
DataSet.applyUpdates() | Notifies listeners that changes made to the DataSet object are ready.
DataSet.changesPending() | Indicates whether there are items in the DeltaPacket object.
DataSet.clear() | Clears all items from the current view of the collection.
DataSet.createItem() | Returns a newly initialized collection item.
DataSet.disableEvents() | Stops sending DataSet events to listeners.
DataSet.enableEvents() | Resumes sending DataSet events to listeners.
DataSet.find() | Locates an item in the current view of the collection.
DataSet.findFirst() | Locates the first occurrence of an item in the current view of the collection.
DataSet.findLast() | Locates the last occurrence of an item in the current view of the collection.
DataSet.first() | Moves to the first item in the current view of the collection.
DataSet.getItemId() | Returns the unique ID for the specified item.
DataSet.getIterator() | Returns a clone of the current iterator.
DataSet.hasNext() | Indicates whether the current iterator is at the end of its view of the collection.
DataSet.hasPrevious() | Indicates whether the current iterator is at the beginning of its view of the collection.
DataSet.hasSort() | Indicates whether the specified sort exists.
DataSet.isEmpty() | Indicates whether the collection contains any items.
DataSet.last() | Moves to the last item in the current view of the collection.
DataSet.loadFromSharedObj() | Retrieves the contents of a DataSet object from a shared object.
DataSet.locateById() | Moves the current iterator to the item with the specified ID.
DataSet.next() | Moves to the next item in the current view of the collection.
DataSet.previous() | Moves to the previous item in the current view of the collection.
DataSet.removeAll() | Removes all the items from the collection.
DataSet.removeItem() | Removes the specified item from the collection.
DataSet.removeRange() | Removes the current iterator's range settings.
DataSet.removeSort() | Removes the specified sort from the DataSet object.
DataSet.saveToSharedObj() | Saves the data in the DataSet object to a shared object.
DataSet.setIterator() | Sets the current iterator for the DataSet object.
DataSet.setRange() | Sets the current iterator's range settings.
DataSet.skip() | Moves forward or backward by a specified number of items in the current view of the collection.
DataSet.useSort() | Makes the specified sort the active one.

Property summary for the DataSet class

Property | Description
DataSet.currentItem | Returns the current item in the collection.
DataSet.dataProvider | Returns the DataProvider interface.
DataSet.deltaPacket | Returns changes made to the collection, or assigns changes to be made to the collection.
DataSet.filtered | Indicates whether items are filtered.
DataSet.filterFunc | User-defined function for filtering items in the collection.
DataSet.items | Items in the collection.
DataSet.itemClassName | Object to create when assigning items.
DataSet.length | Specifies the number of items in the current view of the collection.
DataSet.logChanges | Indicates whether changes made to the collection, or its items, are recorded.
DataSet.properties | Contains the properties (fields) for any transfer object within this collection.
DataSet.readOnly | Indicates whether the collection can be modified.
DataSet.schema | Specifies the collection's schema in XML format.
DataSet.selectedIndex | Contains the current item's index within the collection.

Event summary for the DataSet class

Event | Description
DataSet.addItem | Broadcast before an item is added to the collection.
DataSet.afterLoaded | Broadcast after the items property is assigned.
DataSet.deltaPacketChanged | Broadcast when the DataSet object's delta packet has been changed and is ready to be used.
DataSet.calcFields | Broadcast when calculated fields should be updated.
DataSet.iteratorScrolled | Broadcast when the iterator's position is changed.
DataSet.modelChanged | Broadcast when items in the collection have been modified in some way.
DataSet.newItem | Broadcast when a new item is constructed by the DataSet object, but before it is added to the collection.
DataSet.removeItem | Broadcast before an item is removed.
DataSet.resolveDelta | Broadcast when a DeltaPacket object is assigned to the DataSet object that contains messages.


DataSet.addItem

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

on(addItem) {
  // insert your code here
}
listenerObject = new Object();
listenerObject.addItem = function (eventObj) {
  // insert your code here
}
dataSet.addEventListener("addItem", listenerObject)

Description

Event; generated just before a new transfer object is inserted into this collection.

If you set the result property of the event object to false, the add operation is canceled; if you set it to true, the add operation is allowed.

The event object (eventObj) contains the following properties:

target The DataSet object that generated the event.

type The string "addItem".

item A reference to the item in the collection to be added.

result A Boolean value that specifies whether the specified item should be added. By default, this value is true.

Example

The following on(addItem) event handler (attached to a DataSet object) cancels the addition of the new item if a user-defined function named userHasAdminPrivs() returns false; otherwise, the item addition is allowed.

on(addItem) {
  if(globalObj.userHasAdminPrivs()) {
    // Allow the item addition.
    eventObj.result = true;
  } else {
    // Don't allow item addition; user doesn't have admin privileges.
    eventObj.result = false;
  }
}

See also

DataSet.removeItem


DataSet.addItem()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.addItem([obj])

Parameters

obj An object to add to this collection. This parameter is optional.

Returns

Returns true if the item was added to the collection; otherwise, returns false.

Description

Method; adds the specified transfer object to the collection for management. The newly added item becomes the current item of the data set. If no obj parameter is specified, a new object is created automatically by means of DataSet.createItem().

The location of the new item in the collection depends on whether a sort has been specified for the current iterator. If no sort is in use, the item specified is added to the end of the collection. If a sort is in use, the item is added to the collection according to its position in the current sort.

For more information on initialization and construction of the transfer object, see DataSet.createItem().

Example

myDataSet.addItem(myDataSet.createItem());

See also

DataSet.createItem()


DataSet.addSort()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.addSort(name, fieldList, sortOptions)

Parameters

name A string that specifies the name of the sort.

fieldList An array of strings that specify the fields names to sort on.

sortOptions One or more of the following integer (constant) values, which indicate what options are used for this sort. Separate multiple values using the bitwise OR operator (|). The value(s) must be one of the following:

  • DataSetIterator.Ascending Sorts items in ascending order. This is the default sort option, if none is specified.
  • DataSetIterator.Descending Sorts items in descending order based on item properties specified.
  • DataSetIterator.Unique Prevents the sort if any fields have like values.
  • DataSetIterator.CaseInsensitive Ignores case when comparing two strings during the sort operation. By default, sorts are case sensitive when the property being sorted on is a string.

A DataSetError exception is thrown when DataSetIterator.Unique is specified as a sort option and the data being sorted is not unique, when the specified sort name has already been added, or when a property specified in the fieldList array does not exist in this data set.

Returns

Nothing.

Description

Method; creates a new ascending or descending sort for the current iterator based on the properties specified by the fieldList parameter. The new sort is automatically assigned to the current iterator after it is created and stored in the sorting collection for later retrieval.

Example

The following code creates a new sort named "rank" that performs a descending, case-sensitive, unique sort on the DataSet object's "classRank" field.

myDataSet.addSort("rank", ["classRank"], DataSetIterator.Descending | DataSetIterator.Unique | DataSetIterator.CaseInsensitive);

See also

DataSet.removeSort()


DataSet.afterLoaded

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

on(afterLoaded) {
  // insert your code here
}
listenerObject = new Object();
listenerObject.afterLoaded = function (eventObj) {
  // insert your code here
}
dataSet.addEventListener("afterLoaded", listenerObject)

Description

Event; broadcast immediately after the DataSet.items property has been assigned.

The event object (eventObj) contains the following properties:

target The DataSet object that generated the event

type The string "afterLoaded".

Example

In this example, a form named contactForm (not shown) is made visible once the items in the DataSet contact_ds have been assigned.

contact_ds.addEventListener("afterLoaded", loadListener);
loadListener = new Object();
loadListener.afterLoaded = function (eventObj) {
  if(eventObj.target == "contact_ds") {
    contactForm.visible = true;
  }
}


DataSet.applyUpdates()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.applyUpdates()

Returns

Nothing.

Description

Method; signals that the DataSet.deltaPacket property has a value that you can access using data binding or directly by ActionScript. Before this method is called, the DataSet.deltaPacket property is null. This method has no effect if events have been disabled by means of the DataSet.disableEvents() method.

Calling this method also creates a transaction ID for the current DataSet.deltaPacket property and emits a deltaPacketChanged event. For more information, see DataSet.deltaPacket.

Example

The following code call the applyUpdates() method on myDataSet.

myDataSet.applyUpdates();

See also

DataSet.deltaPacket


DataSet.calcFields

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

on(calcFields) {
  // insert your code here
}
listenerObject = new Object();
listenerObject.calcFields = function (eventObj) {
  // insert your code here
}
dataSet.addEventListener("calcFields", listenerObject)

Description

Event; generated when values of calculated fields for the current item in the collection need to be determined. A calculated field is one whose Kind property is set to Calculated on the Schema tab of the Component Inspector panel. The calcFields event listener that you create should perform the required calculation and set the value for the calculated field.

This event is also called when the value of a noncalculated field (that is, a field with its Kind property set to Data on the Component Inspector panel's Schema tab) is updated.

For more information on the Kind property, see Schema kinds (Flash Professional only).

Caution: Do not change the values of any of noncalculated fields in this event, because this will result in an "infinite loop." Only set the values of calculated fields within the calcFields event.


DataSet.changesPending()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.changesPending()

Returns

A Boolean value.

Description

Method; returns true if the collection, or any item within the collection, has changes pending that have not yet been sent in a DeltaPacket object; otherwise, returns false.

Example

The following code enables a Save Changes button (not shown) if the DataSet collection, or any items with that collection, have had modifications made to them that haven't been committed to a DeltaPacket object.

if( data_ds.changesPending() ) {
  saveChanges_btn.enabled = true;
}


DataSet.clear()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.clear()

Returns

Nothing.

Description

Method; removes the items in the current view of the collection. Which items are considered "viewable" depends on any current filter and range settings on the current iterator. Therefore, calling this method might not clear all of the items in the collection. To clear all of the items in the collection regardless of the current iterator's view, use DataSet.removeAll().

If DataSet.logChanges is set to true when you invoke this method, "remove" entries are added to DataSet.deltaPacket for all items within the collection.

Example

This example removes all items from the current view of the DataSet collection. Because the logChanges property is set to true, the removal of those items is logged.

myDataSet.logChanges= true;
myDataSet.clear();

See also

DataSet.deltaPacket, DataSet.logChanges


DataSet.createItem()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.createItem([itemData])

Parameters

itemData Data associated with the item. This parameter is optional.

Returns

The newly constructed item.

Description

Method; creates an item that isn't associated with the collection. You can specify the class of object created with the DataSet.itemClassName property. If no DataSet.itemClassName value is specified and the itemData parameter is omitted, an anonymous object is constructed. This anonymous object's properties are set to the default values based on the schema currently specified by DataSet.schema.

When this method is invoked, any listeners for the DataSet.newItem event are notified and are able to manipulate the item before it is returned by this method. The optional item data specified is used to initialize the class specified with the DataSet.itemClassName property or is used as the item if DataSet.itemClassName is blank.

A DataSetError exception is thrown when the class specified with the DataSet.itemClassName property cannot be loaded.

Example

contact.itemClassName = "Contact";
var itemData = new XML("<contact_info><name>John Smith</name><phone>555.555.4567</phone><zip><pre>94025</pre><post>0556</post></zip></contact_info>");
contact.addItem(contact.createItem(itemData));

See also

DataSet.itemClassName, DataSet.newItem, DataSet.schema


DataSet.currentItem

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.currentItem

Description

Property (read-only); returns the current item in the DataSet collection, or null if the collection is empty or if the current iterator's view of the collection is empty.

This property provides direct access to the item within the collection. Changes made by directly accessing this object are not tracked (in the DataSet.deltaPacket property), nor are any of the schema settings applied to any properties of this object.

Example

The following example displays the value of the customerName property defined in the current item in the data set named customerData.

trace(customerData.currentItem.customerName);


DataSet.dataProvider

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.dataProvider

Description

Property; the DataProvider interface for this data set. This property provides data to user interface controls, such as the List and DataGrid components.

For more information about the DataProvider API, see DataProvider API.

Example

The following code assigns the dataProvider property of a DataSet object to the corresponding property of a DataGrid component.

myGrid.dataProvider = myDataSet.dataProvider;


DataSet.deltaPacket

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.deltaPacket

Description

Property; returns a DeltaPacket object that contains all of the change operations made to the dataSet collection and its items. This property is null until DataSet.applyUpdates() is called on dataSet.

When DataSet.applyUpdates() is called, a transaction ID is assigned to the DeltaPacket object. This transaction ID is used to identify the DeltaPacket object on an update round trip from the server and back to the client. Any subsequent assignment to the deltaPacket property by a DeltaPacket object with a matching transaction ID is assumed to be the server's response to the changes previously sent. A DeltaPacket object with a matching ID is used to update the collection, and report errors specified within the packet.

Errors or server messages are reported to listeners of the DataSet.resolveDelta event. Note that the DataSet.logChanges settings are ignored when a DeltaPacket object with a matching ID is assigned to DataSet.deltaPacket. A DeltaPacket object without a matching transaction ID updates the collection, as if the DataSet API were used directly. This may create additional delta entries, depending on the current DataSet.logChanges setting of dataSet and the DeltaPacket object.

A DataSetError exception is thrown if a DeltaPacket object is assigned with a matching transaction ID and one of the items in the newly assigned DeltaPacket object cannot be found in the original DeltaPacket object.

See also

DataSet.applyUpdates(), DataSet.logChanges, DataSet.resolveDelta


DataSet.deltaPacketChanged

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

on(deltaPacketChanged) {
  // insert your code here
}
listenerObject = new Object();
listenerObject.deltaPacketChanged = function (eventObj) {
  // insert your code here
}
dataSet.addEventListener("deltaPacketChanged", listenerObject)

Description

Event; broadcast when the specified DataSet object's deltaPacket property has been changed and is ready to be used.

See also

DataSet.deltaPacket


DataSet.disableEvents()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.disableEvents()

Returns

Nothing.

Description

Method; disables events for the DataSet object. While events are disabled, no user interface controls (such as a DataGrid component) are updated when changes are made to items in the collection, or the DataSet object is scrolled to another item in the collection.

To reenable events, you must call DataSet.enableEvents(). The disableEvents() method can be called multiple times, and enableEvents() must be called an equal number of times to reenable the dispatching of events.

Example

In this example, events are disabled before changes are made to items in the collection, so the DataSet object won't try to refresh controls and impact performance.

// Disable events for the data set
myDataSet.disableEvents();
myDataSet.last();
while(myDataSet.hasPrevious()) {
  var price = myDataSet.price;
  price = price * 0.5; // Everything's 50% off!
  myDataSet.price = price;
  myDataSet.previous();
}
// Tell the data set it's time to update the controls now
myDataSet.enableEvents();

See also

DataSet.enableEvents()


DataSet.enableEvents()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.enableEvents()

Returns

Nothing.

Description

Method; reenables events for the DataSet objects after events have been disabled by a call to DataSet.disableEvents(). To reenable events for the DataSet object, the enableEvents() method must be called an equal or greater number of times than disableEvents() was called.

Example

In this example, events are disabled before changes are made to items in the collection, so the DataSet object won't try to refresh controls and impact performance.

// Disable events for the data set
myDataSet.disableEvents();
myDataSet.last();
while(myDataSet.hasPrevious()) {
  var price = myDataSet.price;
  price = price * 0.5; // Everything's 50% off!
  myDataSet.price = price;
  myDataSet.previous();
}
// Tell the dataset it's time to update the controls now
myDataSet.enableEvents();

See also

DataSet.disableEvents()


DataSet.filtered

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.filtered

Description

Property; a Boolean value that indicates whether the data in the current iterator is filtered. When set to true, the filter function specified by DataSet.filterFunc is called for each item in the collection.

Example

In the following example, filtering is enabled on the DataSet object named employee_ds. Suppose that each record in the DataSet collection contains a field named empType. The following filter function returns true if the empType field in the current item is set to "management"; otherwise, it returns false.

employee_ds.filtered = true;
employee_ds.filterFunc = function(item:Object) {
  // filter out those employees who are managers...
  return(item.empType != "management");
}

See also

DataSet.filterFunc


DataSet.filterFunc

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.filterFunc = function(item:Object) {
  // return true|false;
};

Description

Property; specifies a function that determines which items are included in the current view of the collection. When DataSet.filtered is set to true, the function assigned to this property is called for each transfer object in the collection. For each item that is passed to the function, it should return true if the item should be included in the current view, or false if the item should not be included in the current view.

Example

In the following example, filtering is enabled on the DataSet object named employee_ds. The specified filter function returns true if the empType field in each item is set to "management"; otherwise, it returns false.

employee_ds.filtered = true;
employee_ds.filterFunc = function(item:Object) {
  // filter out those employees who are managers...
  return(item.empType != "management");
}

See also

DataSet.filtered


DataSet.find()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.find(searchValues)

Parameters

searchValues An array that contains one or more field values to be found within the current sort.

Returns

Returns true if the values are found; otherwise, returns false.

Description

Method; searches the current view of the collection for an item with the field values specified by searchValues. Which items are in the current view depends on any current filter and range settings. If found, the found item becomes the current item in the DataSet object.

The values specified by searchValues must be in the same order as the field list specified by the current sort (see the example below).

If the current sort is not unique, the transfer object found is nondeterministic. If you want to find the first or last occurrence of a transfer object in a nonunique sort, use DataSet.findFirst() or DataSet.findLast().

Conversion of the data specified is based on the underlying field's type, and that specified in the array. For example, if you specify ["05-02-02"] as a search value, the underlying date field is used to convert the value using the date's DataType.setAsString() method. If you specify [new Date().getTime()], the date's DataType.setAsNumber() method is used.

Example

This example searches for an item in the current collection whose name and id fields contain the values "Bobby" and 105, respectively. If found, the DataSet.getItemId() method is used to get the unique identifier for the item in the collection, and the DataSet.locateById() method is used to position the current iterator on that item.

var studentID:String = null;
studentData.addSort("id", ["name","id"]);
// Locate the transfer object identified by "Bobby" and 105.
// Note that the order of the search fields matches those
// specified in the addSort() method.
if(studentData.find(["Bobby", 105])) {
  studentID = studentData.getItemId();
}
// Now use the locateByID() method to position the current
// iterator on the item in the collection whose ID matches studentID
if(studentID != null) {
  studentData.locateById(studentID);
}

See also

DataSet.applyUpdates(), DataSet.getItemId(), DataSet.locateById()


DataSet.findFirst()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.findFirst(searchValues)

Parameters

searchValues An array that contains one or more field values to be found within the current sort.

Returns

Returns true if the items are found; otherwise, returns false.

Description

Method; searches the current view of the collection for the first item with the field values specified by searchValues. Which items are in the current view depends on any current filter and range settings.

The values specified by searchValues must be in the same order as the field list specified by the current sort (see the example below).

Conversion of the data specified is based on the underlying field's type, and that specified in the array. For example, if the search value specified is ["05-02-02"], the underlying date field is used to convert the value using the date's setAsString() method. If the value specified is [new Date().getTime()], the date's setAsNumber() method is used.

Example

This example searches for the first item in the current collection whose name and age fields contain "Bobby" and "13". If found, DataSet.getItemId() is used to get the unique identifier for the item in the collection, and DataSet.locateById() is used to position the current iterator on that item.

var studentID:String = null;
studentData.addSort("nameAndAge", ["name", "age");
// Locate the first transfer object with the specified values.
// Note that the order of the search fields matches those
// specified in the addSort() method.
if(studentData.findFirst(["Bobby", "13"])) {
  studentID = studentData.getItemId();
}
// Now use the locateByID() method to position the current
// iterator on the item in the collection whose ID matches studentID
if(studentID != null) {
  studentData.locateById(studentID);
}

See also

DataSet.applyUpdates(), DataSet.getItemId(), DataSet.locateById()


DataSet.findLast()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.findLast(searchValues)

Parameters

searchValues An array that contains one or more field values to be found within the current sort.

Returns

Returns true if the items are found; otherwise, returns false.

Description

Method; searches the current view of the collection for the last item with the field values specified by searchValues. Which items are in the current view depends on any current filter and range settings.

The values specified by searchValues must be in the same order as the field list specified by the current sort (see the example below).

Conversion of the data specified is based on the underlying field's type, and that specified in the array. For example, if the search value specified is ["05-02-02"], the underlying date field is used to convert the value using the date's setAsString() method. If the value specified is [new Date().getTime()], the date's setAsNumber() method is used.

Example

This example searches for the last item in the current collection whose name and age fields contain "Bobby" and "13". If found, the DataSet.getItemId() method is used to get the unique identifier for the item in the collection, and the DataSet.locateById() method is used to position the current iterator on that item.

var studentID:String = null;
studentData.addSort("nameAndAge", ["name", "age");
// Locate the last transfer object with the specified values.
// Note that the order of the search fields matches those
// specified in the addSort() method.
if(studentData.findLast(["Bobby", "13"])) {
  studentID = studentData.getItemId();
}
// Now use the locateByID() method to position the current
// iterator on the item in the collection whose ID matches studentID.
if(studentID != null) {
  studentData.locateById(studentID);
}

See also

DataSet.applyUpdates(), DataSet.getItemId(), DataSet.locateById()


DataSet.first()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.first()

Returns

Nothing.

Description

Method; makes the first item in the current view of the collection the current item. Which items are in the current view depends on any current filter and range settings.

Example

The following code positions the DataSet userData at the first item in its collection and then displays the value of the price property contained by that item using the DataSet.currentItem property.

inventoryData.first();
trace("The price of the first item is:" + inventoryData.currentItem.price);

See also

DataSet.last()


DataSet.getItemId()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.getItemId([index])

Parameters

index A number specifying the item in the current view of items to get the ID for. This parameter is optional.

Returns

A string.

Description

Method; returns the identifier of the current item in the collection, or that of the item specified by index. This identifier is unique only within this collection and is assigned automatically by DataSet.addItem().

Example

The following code gets the unique ID for the current item in the collection and then displays it in the Output panel.

var itemNo:String = myDataSet.getItemId();
trace("Employee id("+ itemNo+ ")");

See also

DataSet.addItem()


DataSet.getIterator()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.getIterator()

Returns

A ValueListIterator object.

Description

Method; returns a new iterator for this collection; this iterator is a clone of the current iterator in use, including its current position within the collection. This method is mainly for advanced users who want access to multiple, simultaneous views of the same collection.

Example

myIterator:ValueListIterator = myDataSet.getIterator();
myIterator.sortOn(["name"]);
myIterator.find({name:"John Smith"}).phone = "555-1212";


DataSet.hasNext()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.hasNext()

Returns

A Boolean value.

Description

Method; returns false if the current iterator is at the end of its view of the collection; otherwise, returns true.

Example

This example iterates over all of the items in the current view of the collection (starting at its beginning) and performs a calculation on the price property of each item.

myDataSet.first();
while(myDataSet.hasNext()) {
  var price = myDataSet.currentItem.price;
  price = price * 0.5; // Everything's 50% off!
  myDataSet.currentItem.price = price;
  myDataSet.next();
}

See also

DataSet.currentItem, DataSet.first(), DataSet.next()


DataSet.hasPrevious()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.hasPrevious()

Returns

A Boolean value.

Description

Method; returns false if the current iterator is at the beginning of its view of the collection; otherwise, returns true.

Example

This example iterates over all of the items in the current view of the collection (starting from the its last item) and performs a calculation on the price property of each item.

myDataSet.last();
while(myDataSet.hasPrevious()) {
  var price = myDataSet.currentItem.price;
  price = price * 0.5; // Everything's 50% off!
  myDataSet.currentItem.price = price;
  myDataSet.previous();
}

See also

DataSet.currentItem, DataSet.skip(), DataSet.previous()


DataSet.hasSort()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.hasSort(sortName)

Parameters

sortName A string that contains the name of a sort created with DataSet.addSort()

Returns

A Boolean value.

Description

Method; returns true if the sort specified by sortName exists; otherwise, returns false.

Example

The following code tests if a sort named "customerSort" exists. If the sort already exists, it is made the current sort by means of the DataSet.useSort() method. If a sort by that name doesn't exist, one is created by means of the DataSet.addSort() method.

if(myDataSet.hasSort("customerSort"))
  myDataSet.useSort("customerSort");
} else {
  myDataSet.addSort("customerSort", ["customer"], DataSetIterator.Descending);
}

See also

DataSet.applyUpdates(), DataSet.useSort()


DataSet.isEmpty()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.isEmpty()

Returns

A Boolean value.

Description

Method; returns true if the specified DataSet object doesn't contain any items (that is, if dataSet.length == 0).

Example

The following disables a Delete Record button (not shown) if the DataSet object it applies to is empty.

if(userData.isEmpty()){
    delete_btn.enabled = false;
}

See also

DataSet.length


DataSet.items

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myDataSet.items

Description

Property; an array of items managed by myDataSet.

Example

This example assigns an array of objects to a DataSet object's items property.

var recData = [{id:0, firstName:"Mick", lastName:"Jones"},
              {id:1, firstName:"Joe", lastName:"Strummer"},
              {id:2, firstName:"Paul", lastName:"Simonon"}];
myDataSet.items = recData;


DataSet.itemClassName

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.itemClassName

Description

Property; a string indicating the name of the class that should be created when items are added to the collection. The class you specify must implement the TransferObject interface, shown below.

interface mx.data.to.TransferObject {
  function clone():Object;
  function getPropertyData():Object;
  function setPropertyData(propData:Object):Void;
}

You can also set this property in the Property inspector.

To make the specified class available at runtime, you must also make a fully qualified reference to this class somewhere within your SWF file's code, as in the following code snippet:

var myItem:my.package.myItem;

A DataSetError exception is thrown if you try to modify the value of this property after the DataSet.items array has been loaded.

For more information about the TransferObject interface, see TransferObject interface.


DataSet.iteratorScrolled

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

on(iteratorScrolled) {
  // insert your code here
}
listenerObject = new Object();
listenerObject.iteratorScrolled = function (eventObj) {
  // insert your code here
}
dataSet.addEventListener("iteratorScrolled", listenerObject)

Description

Event; generated immediately after the current iterator has scrolled to a new item in the collection.

The event object (eventObj) contains the following properties:

target The DataSet object that generated the event.

type The string "iteratorScrolled".

scrolled A number that specifies how many items the iterator scrolled; positive values indicate that the iterator moved forward in the collection; negative values indicate that it moved backward in the collection.

Example

In this example, the status bar of an application (not shown) is updated when the position of the current iterator changes.

on(iteratorScrolled) {
  var dataSet:mx.data.components.DataSet = eventObj.target;
  var statusBarText = dataSet.fullname+" Acct #: "+dataSet.getField("acctnum").getAsString();
  setStatusBar(statusBarText);
}


DataSet.last()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.last()

Returns

Nothing.

Description

Method; makes the last item in the current view of the collection the current item.

Example

The following code, attached to a Button component, goes to the last item in the DataSet collection.

function goLast(eventObj:obj) {
  inventoryData.last();
}
goLast_btn.addEventListener("click", goLast);

See also

DataSet.first()


DataSet.length

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.length

Description

Property (read-only); specifies the number of items in the current view of the collection. The viewable number of items is based on the current filter and range settings.

Example

The following example alerts users if they haven't made enough entries in the data set, perhaps using an editable DataGrid component.

if(myDataSet.length < MIN_REQUIRED) {
  alert("You need at least "+MIN_REQUIRED);
}


DataSet.loadFromSharedObj()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.loadFromSharedObj(objName, [localPath])

Parameters

objName A string specifying the name of the shared object to retrieve. The name can include forward slashes (for example, "work/addresses"). Spaces and the following characters are not allowed in the specified name:

~ % & \ ; : " ' , < > ? #

localPath An optional string parameter that specifies the full or partial path to the SWF file that created the shared object. This string is used to determine where the object is stored on the user's computer. The default value is the SWF file's full path.

Returns

Nothing.

Description

Method; loads all of the relevant data needed to restore this DataSet collection from a shared object. To save a DataSet collection to a shared object, use DataSet.saveToSharedObj(). The DataSet.loadFromSharedObject() method overwrites any data or pending changes that might exist within this DataSet collection. Note that the instance name of the DataSet collection is used to identify the data within the specified shared object.

This method throws a DataSetError exception if the specified shared object isn't found or if there is a problem retrieving the data from it.

Example

This example attempts to load a shared object named webapp/customerInfo associated with the data set named myDataSet. The method is called within a try...catch code block.

try {
  myDataSet.loadFromSharedObj("webapp/customerInfo");
}
catch(e:DataSetError) {
  trace("Unable to load shared object.");
}

See also

DataSet.saveToSharedObj()


DataSet.locateById()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.locateById(id)

Parameters

id A string identifier for the item in the collection to be located.

Returns

A Boolean value.

Description

Method; positions the current iterator on the collection item whose ID matches id. This method returns true if the specified ID can be matched to an item in the collection; otherwise, it returns false.

Example

This example uses DataSet.find() to search for an item in the current collection whose name and id fields contain the values "Bobby" and 105, respectively. If found, the DataSet.getItemId() method is used to get the unique identifier for that item, and the DataSet.locateById() method is used to position the current iterator at that item.

var studentID:String = null;
studentData.addSort("id", ["name","id"]);
if(studentData.find(["Bobby", 105])) {
  studentID = studentData.getItemId();
  studentData.locateById(studentID);
}

See also

DataSet.applyUpdates(), DataSet.find(), DataSet.getItemId()


DataSet.logChanges

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.logChanges

Description

Property; a Boolean value that specifies whether changes made to the data set, or its items, should (true) or should not (false) be recorded in DataSet.deltaPacket.

When this property is set to true, operations performed at the collection level and item level are logged. Collection-level changes include the addition and removal of items from the collection. Item-level changes include property changes made to items and method calls made on items by means of the DataSet component.

Example

The following example disables logging for the DataSet object named userData.

userData.logChanges = false;

See also

DataSet.deltaPacket


DataSet.modelChanged

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Description

on(modelChanged) {
  // insert your code here
}
listenerObject = new Object();
listenerObject.modelChanged = function (eventObj) {
  // insert your code here
}
dataSet.addEventListener("modelChanged", listenerObject)

Description

Event; broadcast when the collection changes in some way—for example, when items are removed or added to the collection, when the value of an item's property changes, or when the collection is filtered or sorted.

The event object (eventObj) contains the following properties:

target The DataSet object that generated the event.

type The string "iteratorScrolled".

firstItem The index (number) of the first item in the collection that was affected by the change.

lastItem The index (number) of the last item in the collection that was affected by the change (equals firstItem if only one item was affected).

fieldName A string that contains the name of the field being affected. This property is undefined unless the change was made to a property of the DataSet object.

eventName A string that describes the change that took place. This can be one of the following values:

String value | Description
"addItems" | A series of items has been added.
"filterModel" | The model has been filtered, and the view needs refreshing (reset scroll position).
"removeItems" | A series of items has been deleted.
"schemaLoaded" | The fields definition of the data provider has been declared.
"sort" | The data has been sorted.
"updateAll" | The entire view needs refreshing, excluding scroll position.
"updateColumn" | An entire field's definition within the data provider needs refreshing.
"updateField" | A field within an item has been changed and needs refreshing.
"updateItems" | A series of items needs refreshing.

Example

In this example, a Delete Item button is disabled if the items have been removed from the collection and the target DataSet object has no more items.

on(modelChanged) {
  delete_btn.enabled = ((eventObj.eventName == "removeItems") && (eventObj.target.isEmpty()));
}

See also

DataSet.isEmpty()


DataSet.newItem

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

on(newItem) {
  // insert your code here
}
listenerObject = new Object();
listenerObject.newItem = function (eventObj) {
  // insert your code here
}
dataSet.addEventListener("newItem", listenerObject)

Description

Event; broadcast when a new transfer object is constructed by means of DataSet.createItem(). A listener for this event can make modifications to the item before it is added to the collection.

The event object (eventObj) contains the following properties:

target The DataSet object that generated the event.

type The string "iteratorScrolled".

item A referenece to the item that was created.

Example

This example makes modifications to a newly created item before it's added to the collection.

function newItemEvent(evt:Object):Void {
  var employee:Object = evt.item;
  employee.name = "newGuy";
  // property data happens to be XML
  employee.zip = employee.getPropertyData().firstChild.childNodes[1].attributes.zip;
}
employees_ds.addEventListener("newItem", newItemEvent);


DataSet.next()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.next()

Returns

Nothing.

Description

Method; makes the next item in the current view of the collection the current item. Which items are in the current view depends on any current filter and range settings.

Example

This example loops over all the items in a DataSet object, starting from the first item, and performs a calculation on a field in each item.

myDataSet.first();
while(myDataSet.hasNext()) {
  var price = myDataSet.price;
  price = price * 0.5; // Everything's 50% off!
  myDataSet.price = price;
  myDataSet.next();
}

See also

DataSet.first(), DataSet.hasNext()


DataSet.previous()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.previous()

Returns

Nothing.

Description

Method; makes the previous item in the current view of the collection the current item. Which items are in the current view depends on any current filter and range settings.

This example loops over all the items in the current view of the collection, starting from the last item, and performs a calculation on a field in each item.

myDataSet.last();
while(myDataSet.hasPrevious()) {
  var price = myDataSet.price;
  price = price * 0.5; // Everything's 50% off!
  myDataSet.price = price;
  myDataSet.previous();
}

See also

DataSet.first(), DataSet.hasNext()


DataSet.properties

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.properties

Description

Property (read-only); returns an object that contains all of the exposed properties (fields) for any transfer object within this collection.

Example

This example displays all the names of the properties in the DataSet object named myDataSet.

for(var i in myDataSet.properties) {
  trace("field '"+i+ "' has value "+ myDataSet.properties[i]);
}


DataSet.readOnly

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.readOnly

Description

Property; a Boolean value that specifies whether this collection can be modified (false) or is read-only (true). Setting this property to true will prevent updates to the collection.

You can also set this property in the Property inspector.

Example

The following example makes the DataSet object named myDataSet read-only, and then attempts to change the value of a property that belongs to the current item in the collection. This will throw an exception.

myDataSet.readOnly = true;
// This will throw an exception
myDataSet.currentItem.price = 15;

See also

DataSet.currentItem


DataSet.removeAll()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.removeAll()

Parameters

None.

Returns

Nothing.

Description

Method; removes all items in the DataSet collection.

Example

This example removes all the items in the DataSet collection contact_ds:

contact_ds.removeAll();


DataSet.removeItem

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

on(removeItem) {
  // insert your code here
}
listenerObject = new Object();
listenerObject.removeItem = function (eventObj) {
  // insert your code here
}
dataSet.addEventListener("removeItem", listenerObject)

Description

Event; generated just before a new item is deleted from this collection.

If you set the result property of the event object to false, the delete operation is canceled; if you set it to true, the delete operation is allowed.

The event object (eventObj) contains the following properties:

target The DataSet object that generated the event.

type The string "removeItem".

item A reference to the item in the collection to be removed.

result A Boolean value that specifies whether the item should be removed. By default, this value is true.

Example

In this example, an on(removeItem) event handler cancels the deletion of the new item if a user-defined function named userHasAdminPrivs() returns false; otherwise, the deletion is allowed.

on(removeItem) {
  if(globalObj.userHasAdminPrivs()) {
    // Allow the item deletion.
    eventObj.result = true;
  } else {
    // Don't allow item deletion; user doesn't have admin priviledges.
    eventObj.result = false;
  }
}

See also

DataSet.addItem


DataSet.removeItem()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.removeItem([item])

Parameters

item The item that should be removed. This parameter is optional.

Returns

A Boolean value. Returns true if the item was successfully removed; otherwise, returns false.

Description

Method; removes the specified item from the collection, or removes the current item if the item parameter is omitted. This operation is logged to DataSet.deltaPacket if DataSet.logChanges is true.

Example

The following code, attached to an instance of the Button component, removes the current item in the DataSet object named usersData that resides on the same Timeline as the Button instance.

on(click) {
  _parent.usersData.removeItem();
}

See also

DataSet.deltaPacket, DataSet.logChanges


DataSet.removeRange()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.removeRange()

Returns

Nothing.

Description

Method; removes the current end point settings specified by means of DataSet.setRange() for the current iterator.

Example

myDataSet.addSort("name_id", ["name", "id"]);
myDataSet.setRange(["Bobby", 105],["Cathy", 110]);
while(myDataSet.hasNext()) {
  myDataSet.gradeLevel ="5"; // change all of the grades in this range
  myDataSet.next();
}
myDataSet.removeRange();
myDataSet.removeSort("name_id");

See also

DataSet.applyUpdates(), DataSet.hasNext(), DataSet.next(), DataSet.removeSort(), DataSet.setRange()


DataSet.removeSort()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.removeSort(sortName)

Parameters

sortName A string that specifies the name of the sort to remove.

Returns

Nothing.

Description

Method; removes the specified sort from this DataSet object if the sort exists. If the specified sort does not exist, this method throws a DataSetError exception.

Example

myDataSet.addSort("name_id", ["name", "id"]);
myDataSet.setRange(["Bobby", 105],["Cathy", 110]);
while(myDataSet.hasNext()) {
  myDataSet.gradeLevel ="5"; // change all of the grades in this range
  myDataSet.next();
}
myDataSet.removeRange();
myDataSet.removeSort("name_id");

See also

DataSet.applyUpdates(), DataSet.hasNext(), DataSet.next(), DataSet.removeRange(), DataSet.setRange()


DataSet.resolveDelta

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

on(resolveDelta) {
  // insert your code here
}
listenerObject = new Object();
listenerObject.resolveDelta = function (eventObj) {
  // insert your code here
}
dataSet.addEventListener("resolveDelta", listenerObject)

Description

Event; broadcast when a DeltaPacket object is assigned to DataSet.deltaPacket whose transaction ID matches that of a DeltaPacket object previously retrieved from the DataSet object, and that has messages associated with any of the Delta or DeltaItem objects contained by that DeltaPacket object.

This event gives you the chance to reconcile any error returned from the server while attempting to apply changes previously submitted. Typically, you use this event to display a "reconcile dialog box" with the conflicting values, allowing the user to make appropriate modifications to the data so that it can be resent.

The event object (eventObj) contains the following properties:

target The DataSet object that generated the event.

type The string "resolveDelta".

data An array of Delta and associated DeltaItem objects that have nonzero length messages.

Example

This example displays a form called reconcileForm (not shown) and calls a method on that form object (setReconcileData()) that allows the user to reconcile any conflicting values returned by the server.

myDataSet.addEventListener("resolveDelta", resolveDelta);
function resolveDelta(eventObj:Object) {
  reconcileForm.visible = true;
  reconcileForm.setReconcileData(eventObj.data);
}
// in the reconcileForm code
function setReconcileData(data:Array):Void {
  var di:DeltaItem;
  var ops:Array = ["property", "method"];
  var cl:Array;
  // change list
  var msg:String;
  for (var i = 0; i<data.length; i++) {
    cl = data[i].getChangeList();
    for (var j = 0; j<cl.length; j++) {
      di = cl[j];
      msg = di.getMessage();
      if (msg.length>0) {
        trace("The following problem occurred '"+msg+"' while performing a '"+ops[di.kind]+"' modification on/with '"+di.name+"' current server value ["+di.curValue+"], value sent ["+di.newValue+"] Please fix!");
      }
    }
  }
}


DataSet.saveToSharedObj()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.saveToSharedObj(objName, [localPath])

Parameters

objName A string that specifies the name of the shared object to create. The name can include forward slashes (for example, "work/addresses"). Spaces and the following characters are not allowed in the specified name:

~ % & \ ; : " ' , < > ? #

localPath An optional string parameter that specifies the full or partial path to the SWF file that created the shared object. This string is used to determine where the object will be stored on the user's computer. The default value is the SWF file's full path.

Returns

Nothing.

Description

Method; saves all of the relevant data needed to restore this DataSet collection to a shared object. This allows users to work when disconnected from the source data, if it is a network resource. This method overwrites any data that might exist within the specified shared object for this DataSet collection. To restore a DataSet collection from a shared object, use DataSet.loadFromSharedObj(). Note that the instance name of the DataSet collection is used to identify the data within the specified shared object.

If the shared object can't be created or there is a problem flushing the data to it, this method throws a DataSetError exception.

Example

This example calls saveToSharedObj() in a try..catch block and displays an error if there is a problem saving the data to the shared object.

try {
  myDataSet.saveToSharedObj("webapp/customerInfo");
}
catch(e:DataSetError) {
  trace("Unable to create shared object");
}

See also

DataSet.loadFromSharedObj()


DataSet.schema

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.schema

Description

Property; provides the XML representation of the schema for this DataSet object. The XML assigned to this property must have the following format:

<?xml version="1.0"?>
<properties>
  <property name="propertyName">
    <type name="dataType" />
    <encoder name="dataType">
      <options>
        <dataFormat>format options<dataFormat/>
      <options/>
    <encoder/>
    <kind name="dataKind">
      <options/>
    </kind>
  </property>
  <property> ... </property>
  ...
</properties>

A DataSetError exception is thrown if the XML specified does not follow the above format.

Example

myDataSet.schema = new XML("<properties><property name="billable"> ..etc.. </properties>");


DataSet.selectedIndex

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.selectedIndex

Description

Property; specifies the selected index within the collection. You can bind this property to the selected item in a DataGrid or List component, and vice versa. For a complete example that demonstrates this, see Creating an application with the DataSet component.

Example

The following example sets the selected index of a DataSet object (userData) to the selected index in a DataGrid component (userGrid).

userData.selectedIndex = userGrid.selectedIndex;


DataSet.setIterator()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.setIterator(iterator)

Parameters

iterator An iterator object returned by a call to DataSet.getIterator().

Returns

Nothing.

Description

Method; assigns the specified iterator to this DataSet object and makes it the current iterator. The specified iterator must come from a previous call to DataSet.getIterator() on the DataSet object it is being assigned to; otherwise; a DataSetError exception is thrown.

Example

myIterator:ValueListIterator = myDataSet.getIterator();
myIterator.sortOn(["name"]);
myDataSet.setIterator(myIterator);

See also

DataSet.getIterator()


DataSet.setRange()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.setRange(startValues, endValues)

Parameters

startValues An array of key values of the properties of the first transfer object in the range.

endValues An array of key values of the properties of the last transfer object in the range.

Returns

Nothing.

Description

Method; sets the end points for the current iterator. The end points define a range within which the iterator operates. This is only valid if a valid sort has been set for the current iterator by means of DataSet.applyUpdates().

Setting a range for the current iterator is more efficient than using a filter function if you want a grouping of values (see DataSet.filterFunc).

Example

myDataSet.addSort("name_id", ["name", "id"]);
myDataSet.setRange(["Bobby", 105],["Cathy", 110]);
while(myDataSet.hasNext()) {
  myDataSet.gradeLevel ="5"; // change all of the grades in this range
  myDataSet.next();
}
myDataSet.removeRange();
myDataSet.removeSort("name_id");

See also

DataSet.applyUpdates(), DataSet.hasNext(), DataSet.next(), DataSet.removeRange(), DataSet.removeSort()


DataSet.skip()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.skip(offSet)

Parameters

offSet An integer specifying the number of records by which to move the iterator position.

Returns

Nothing.

Description

Method; moves the current iterator's position forward or backward in the collection by the amount specified by offSet. Positive offSet values move the iterator's position forward; negative values move it backward.

If the specified offset is beyond the beginning (or end) of the collection, the iterator is positioned at the beginning (or end) of the collection.

Example

This example positions the current iterator at the first item in the collection, then moves to the next-to-last item and performs a calculation on a field belonging to that item.

myDataSet.first();
// Move to the item just before the last one
var itemsToSkip = myDataSet.length - 2;
myDataSet.skip(itemsToSkip).price = myDataSet.amount * 10;


DataSet.useSort()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

dataSet.useSort(sortName, order)

Parameters

sortName A string that contains the name of the sort to use.

order An integer value that indicates the sort order for the sort; the value must be DataSetIterator.Ascending or DataSetIterator.Descending.

Returns

Nothing.

Description

Method; switches the sort for the current iterator to the one specified by sortName, if it exists. If the sort specified by sortName does not exist, a DataSetError exception is thrown.

To create a sort, use the DataSet.applyUpdates().

Example

This code uses DataSet.hasSort() to determine if a sort named "customer" exists. If it does, the code calls DataSet.useSort() to make "customer" the current sort. Otherwise, the code creates a sort by that name using DataSet.addSort().

if(myDataSet.hasSort("customer")) {
  myDataSet.useSort("customer");
} else {
  myDataSet.addSort("customer", ["customer"], DataSetIterator.Descending);
}

See also

DataSet.applyUpdates(), DataSet.hasSort()


About the DateChooser component (Flash Professional only)

The DateChooser component is a calendar that allows users to select a date. It has buttons that allow users to scroll through months and click on a date to select it. You can set parameters that indicate the month and day names, the first day of the week, and any disabled dates, as well as highlighting the current date.

A live preview of each DateChooser instance reflects the values indicated by the Property inspector or Component Inspector panel while authoring.

See also:

  • Using the DateChooser component (Flash Professional only)
  • Customizing the DateChooser component (Flash Professional only)
  • DateChooser class (Flash Professional only)


Using the DateChooser component (Flash Professional only)

The DateChooser can be used anywhere you want a user to select a date. For example, you could use a DateChooser component in a hotel reservation system with certain dates selectable and others disabled. You could also use the DateChooser component in an application that displays current events, such as performances or meetings, when a user chooses a date.

See also:

  • DateChooser parameters
  • Creating an application with the DateChooser component

DateChooser parameters

The following are authoring parameters that you can set for each DateChooser component instance in the Property inspector or in the Component Inspector panel:

monthNames sets the month names that are displayed in the heading row of the calendar. The value is an array and the default value is ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"].

dayNames sets the names of the days of the week. The value is an array and the default value is ["S", "M", "T", "W", "T", "F", "S"].

firstDayOfWeek indicates which day of the week (0-6, 0 being the first element of dayNames array) is displayed in the first column of the DateChooser. This property changes the display order of the day columns.

disabledDays indicates the disabled days of the week. This parameter is an array and can have up to 7 values. The default value is [] (an empty array).

showToday indicates whether or not to highlight today's date. The default value is true.

You can write ActionScript to control these and additional options for the DateChooser component using its properties, methods, and events. For more information, see DateChooser class (Flash Professional only).

Creating an application with the DateChooser component

The following procedure explains how to add a DateChooser component to an application while authoring. In this example, the DateChooser allows a user to pick a date for an airline reservation system. All dates before October 15th must be disabled. Also, a range in December must be disabled to create a holiday black-out period and Mondays must be disabled.

To create an application with the DateChooser component, do the following:

  1. Double-click the DateChooser component in the Components panel to add it to the Stage.
  2. In the Property inspector, enter the instance name flightCalendar.
  3. In the Actions panel, enter the following code on Frame 1 of the Timeline to set the range of selectable dates:
    flightCalendar.selectableRange = {rangeStart:new Date(2003, 9, 15), rangeEnd:new Date(2003, 11, 31)}

    This code assigns a value to the selectableRange property in an ActionScript object that contains two Date objects with the variable names rangeStart and rangeEnd. This defines an upper and lower end of a range within which the user can select a date.

  4. In the Actions panel, enter the following code on Frame 1 of the Timeline to set a range of holiday disabled dates:
    flightCalendar.disabledRanges = [{rangeStart: new Date(2003, 11, 15), rangeEnd: new Date(2003, 11, 26)}];
  5. In the Actions panel, enter the following code on Frame 1 of the Timeline to disable Mondays:
    flightCalendar.disabledDays=[1];
  6. Control > Test Movie.


Customizing the DateChooser component (Flash Professional only)

You can transform a DateChooser component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()).

See also:

  • Using styles with the DateChooser component
  • Using skins with the DateChooser component

Using styles with the DateChooser component

You can set style properties to change the appearance of a date chooser instance. If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

A DateChooser component that uses the Halo theme supports the following styles:

Style | Description
themeColor | The glow color for the rollover and selected dates. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style; either "normal", or "italic".
fontWeight | The font weight; either "normal", or "bold".
textDecoration | The text decoration: either "none", or "underline".

Using skins with the DateChooser component

The DateChooser component skins to represent its visual states. To skin the DateChooser component while authoring, modify skin symbols in the Flash UI Components 2/Themes/MMDefault/DateChooser Assets/Elements/Month skins states folder in the library of one of the themes FLA files. For more information, see About skinning components.

Only the month scrolling buttons can be dynamically skinned in this component. A DateChooser component uses the following skin properties:

Property | Description
falseUpSkin | The up state. The default values are fwdMonthUp and backMonthUp.
falseDownSkin | The down state. The default values are fwdMonthDown and backMonthDown.
falseDisabledSkin | The disabled state. The default values are fwdMonthDisabled and backMonthDisabled.


DateChooser class (Flash Professional only)

Inheritance UIObject > UIComponent > DateChooser

ActionScript Class Name mx.controls.DateChooser

The properties of the DateChooser class allow you to access the selected date, and the displayed month and year. You can also set the names of the days and months, indicate disabled dates and selectable dates, set the first day of the week, and indicate whether the current date should be highlighted.

Setting a property of the DateChooser class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.DateChooser.version);

Note: The following code returns undefined: trace(myDC.version);.

Method summary for the DateChooser class

Inherits all methods from UIObject and UIComponent.

Property summary for the DateChooser class

Property | Description
DateChooser.dayNames | An array indicating the names of the days of the week.
DateChooser.disabledDays | An array indicating the days of the week that are disabled for all applicable dates in the date chooser.
DateChooser.disabledRanges | A range of disabled dates or a single disabled date.
DateChooser.displayedMonth | A number indicating an element in the monthNames array to display in the date chooser.
DateChooser.displayedYear | A number indicating the year to display.
DateChooser.firstDayOfWeek | A number indicating an element in the dayNames array to display in the first column of the date chooser.
DateChooser.monthNames | An array of strings indicating the month names.
DateChooser.selectableRange | A single selectable date or a range of selectable dates.
DateChooser.selectedDate | A Date object indicating the selected date.
DateChooser.showToday | A Boolean value indicating whether the current date is highlighted.

Inherits all properties from UIObject and UIComponent.

Event summary for the DateChooser class

Event | Description
DateChooser.change | Broadcast when a date is selected.
DateChooser.scroll | Broadcast when the month buttons are pressed.

Inherits all events from UIObject and UIComponent.


DateChooser.change

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

on(change){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.change = function(eventObject){
  ...
}
chooserInstance.addEventListener("change", listenerObject)

Description

Event; broadcast to all registered listeners when a date is selected.

The first usage example uses an on() handler and must be attached directly to a DateChooser component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date chooser myDC, sends "_level0.myDC" to the Output panel:

on(change){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (chooserInstance) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when a DateChooser called myDC is changed. The first line of code creates a listener object called form. The second line defines a function for the change event on the listener object. Inside the function is a trace() action that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event (in this example myDC). The NumericStepper.maximum property is accessed from the event object's target property. The last line calls the UIEventDispatcher.addEventListener() method from myDC and passes it the change event and the form listener object as parameters, as in the following:

form.change = function(eventObj){
    trace("date selected " +  eventObj.target.selectedDate) ;
}
myDC.addEventListener("change", form);


DateChooser.dayNames

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.dayNames

Description

Property; an array containing the names of the days of the week. Sunday is the first day (at index position 0) and the rest of the day names follow in order. The default value is ["S", "M", "T", "W", "T", "F", "S"].

Example

The following example changes the value of the 5th day of the week (Thursday) from "T" to "R":

myDC.dayNames[4] = "R";


DateChooser.disabledDays

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.disabledDays

Description

Property; an array indicating the disabled days of the week. All the dates in a month that fall on the specified day are disabled. The elements of this array can have values between 0 (Sunday) and 6 (Saturday). The default value is [] (empty array).

Example

The following example disables Sundays and Saturdays so that users can only select weekdays:

myDC.disabledDays = [0, 6];


DateChooser.disabledRanges

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.disabledRanges

Description

Property; disables a single day or a range of days. This property is an Array of objects. Each object in the array must be either a Date object specifying a single day to disable, or an object containing either or both of the properties rangeStart and rangeEnd, each of whose value must be a Date object. The rangeStart and rangeEnd properties describe the boundaries of the date range. If either property is omitted the range is unbounded in that direction.

The default value of disabledRanges is undefined.

Specify a full date when you define dates for the disabledRanges property. For example, new Date(2003,6,24) rather than new Date(). If you don't specify a full date, the time returns as 00:00:00.

Example

The following example defines an array with rangeStart and rangeEnd Date objects that disable the dates between May 7 and June 7:

myDC.disabledRanges = [ {rangeStart: new Date(2003, 4, 7), rangeEnd: new Date(2003, 5, 7)}];

The following example disables all dates after November 7:

myDC.disabledRanges = [ {rangeStart: new Date(2003, 10, 7)} ];

The following example disables all dates before October 7:

myDC.disabledRanges = [ {rangeEnd: new Date(2002, 9, 7)} ];

The following example disables only December 7:

myDC.disabledRanges = [ new Date(2003, 11, 7) ];


DateChooser.displayedMonth

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.displayedMonth

Description

Property; a number indicating which month is displayed. The number indicates an element in the monthNames array, with 0 being the first month. The default value is the month of the current date.

Example

The following example sets the displayed month to December:

myDC.displayedMonth = 11;

See also

DateChooser.displayedYear


DateChooser.displayedYear

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.displayedYear

Description

Property; a four digit number indicating which year is displayed. The default value is the current year.

Example

The following example sets the displayed year to 2010:

myDC.displayedYear = 2010;

See also

DateChooser.displayedMonth


DateChooser.firstDayOfWeek

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.firstDayOfWeek

Description

Property; a number indicating which day of the week (0-6, 0 being the first element of the dayNames array) is displayed in the first column of the DateChooser component. Changing this property changes the order of the day columns but has no effect on the order of the dayNames property. The default value is 0 (Sunday).

Example

The following example sets the first day of the week to Monday:

myDC.firstDayOfWeek = 1;

See also

DateChooser.dayNames


DateChooser.monthNames

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.monthNames

Description

Property; an array of strings indicating the month names at the top of the DateChooser component. The default value is ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"].

Example

The following example sets the month names for the instance myDC:

 myDC.monthNames = ["Jan", "Feb","Mar","Apr", "May", "June","July", "Aug" , "Sept","Oct", "Nov", "Dec"];


DateChooser.scroll

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

on(scroll){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.scroll = function(eventObject){
  ...
}
myDC.addEventListener("scroll", listenerObject)

Description

Event; broadcast to all registered listeners when a month button is pressed.

The first usage example uses an on() handler and must be attached directly to a DateChooser component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the stepper myDC, sends "_level0.myDC" to the Output panel:

on(scroll){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (myDC) dispatches an event (in this case, scroll) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. The scroll event's event object has an additional property, detail, that can have one of the following values: nextMonth, previousMonth, nextYear, previousYear.

Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when a month button is pressed on a DateChooser instance called myDC. The first line of code creates a listener object called form. The second line defines a function for the scroll event on the listener object. Inside the function is a trace action that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event; in this example myDC. The last line calls the UIEventDispatcher.addEventListener() method from myDC and passes it the scroll event and the form listener object as parameters, as in the following:

form = new Object();
form.scroll = function(eventObj){
  trace(eventObj.detail);
}
myDC.addEventListener("scroll", form);


DateChooser.selectableRange

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.selectableRange

Description

Property; sets a single selectable date or a range of selectable dates. The user will not be able to scroll beyond the selectable range. The value of this property is an object that consists of two Date objects named rangeStart and rangeEnd. The rangeStart and rangeEnd properties designate the boundaries of the selectable date range. If only rangeStart is defined, all the dates after rangeStart are enabled. If only rangeEnd is defined, all the dates before rangeEnd are enabled. The default value is undefined.

If you want to enable only a single day, you can use a single Date object as the value of selectableRange.

Specify a full date when you define dates. For example, new Date(2003,6,24) rather than new Date(). If you don't specify a full date, the time returns as 00:00:00.

The value of DateChooser.selectedDate is set to undefined if it falls outside the selectable range.

The value of DateChooser.displayedMonth and DateChooser.displayedYear are set to the the nearest last month in the selectable range if the current month falls outside the selectable range. For example, if the current displayed month is August, and the selectable range is from June, 2003 - July, 2003, the displayed month will change to July, 2003.

Example

The following example defines the selectable range to the dates between and including May 7 and June 7:

myDC.selectableRange = {rangeStart: new Date(2001, 4, 7), rangeEnd: new Date(2003, 5, 7)};

The following example defines the selectable range to the dates after and including May 7:

myDC.selectableRange = {rangeStart: new Date(2003, 4, 7)};

The following example defines the selectable range to the dates before and including June 7:

myDC.selectableRange = {rangeEnd: new Date(2003, 5, 7) };

The following example defines the selectable date as June 7 only:

myDC.selectableRange = new Date(2003, 5, 7);


DateChooser.selectedDate

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.selectedDate

Description

Property; a Date object that indicates the selected date if that value falls within the value of the selectableRange property. The default value is undefined.

The selectedDate property cannot be set inside a disabledRange, outside a selectableRange, or on a day that has been disabled. If the selectedDate property is set to one of the previous dates, the value will be undefined.

Example

The following example sets the selected date to June 7:

myDC.selectedDate = new Date(2003, 5, 7);


DateChooser.showToday

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDC.showToday

Description

Property; this property determines whether the current date is highlighted. The default value is true.

Example

The following example turns off the highlighting on today's date:

myDC.showToday = false;


About the DateField component (Flash Professional only)

The DateField component is a nonselectable text field that displays the date with a calendar icon on its right side. If no date has been selected, the text field is blank and the month of today's date is displayed in the date chooser. When a user clicks anywhere inside the bounding box of the date field, a date chooser pops up and displays the dates in the month of the selected date. When the date chooser is open, users can use the month scroll buttons to scroll through months and years, and select a date. When a date is selected, the date chooser closes.

The live preview of the DateField does not reflect the values indicated by the Property inspector or Component Inspector panel while authoring because it is a pop-up component that is not visible while authoring.

See also:

  • Using the DateField component (Flash Professional only)
  • Customizing the DateField component (Flash Professional only)


Using the DateField component (Flash Professional only)

The DateField component can be used anywhere you want a user to select a date. For example, you could use a DateField component in a hotel reservation system with certain dates selectable and others disabled. You could also use the DateField component in an application that displays current events, such as performances or meetings, when a user chooses a date.

See also:

  • DateField parameters
  • Creating an application with the DateField component

DateField parameters

The following are authoring parameters that you can set for each DateField component instance in the Property inspector or in the Component Inspector panel:

monthNames sets the month names that are displayed in the heading row of the calendar. The value is an array and the default value is ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"].

dayNames sets the names of the days of the week. The value is an array and the default value is ["S", "M", "T", "W", "T", "F", "S"].

firstDayOfWeek indicates which day of the week (0-6, 0 being the first element of dayNames array) is displayed in the first column of the DateChooser. This property changes the display order of the day columns.

The default value is 0, which is "S".

disabledDays indicates the disabled days of the week. This parameter is an array and can have up to 7 values. The default value is [] (an empty array).

showToday indicates whether or not to highlight today's date. The default value is true.

You can write ActionScript to control these and additional options for the DateField component using its properties, methods, and events. For more information, see DateField class (Flash Professional only).

Creating an application with the DateField component

The following procedure explains how to add a DateField component to an application while authoring. In this example, the DateField component allows a user to pick a date for an airline reservation system. All dates before today's date must be disabled. Also, a 15-day range in December must be disabled to create a holiday black-out period. Also, some flights are not available on Mondays, so all Mondays must be disabled for those flights.

To create an application with the DateField component, do the following:

  1. Double-click the DateField component in the Components panel to add it to the Stage.
  2. In the Property inspector, enter the instance name flightCalendar.
  3. In the Actions panel, enter the following code on Frame 1 of the Timeline to set the range of selectable dates:
    flightCalendar.selectableRange = {rangeStart:new Date(2001, 9, 1), rangeEnd:new Date(2003, 11, 1)};

    This code assigns a value to the selectableRange property in an ActionScript object that contains two Date objects with the variable names rangeStart and rangeEnd. This defines an upper and lower end of a range within which the user can select a date.

  4. In the Actions panel, enter the following code on Frame 1 of the Timeline to set the ranges of disabled dates, one during December, and one for all dates before the current date:
    flightCalendar.disabledRanges = [{rangeStart: new Date(2003, 11, 15), rangeEnd: new Date(2003, 11, 31)}, {rangeEnd: new Date(2003, 6, 16)}];
  5. In the Actions panel, enter the following code on Frame 1 of the Timeline to disable Mondays:
    flightCalendar.disabledDays=[1];
  6. Control > Test Movie.


Customizing the DateField component (Flash Professional only)

You can transform a DateField component horizontally both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()). Setting the width does not change the dimensions of the date chooser within the DateField component. However, you can use the pullDown property to access the DateChooser component and set its dimensions.

See also:

  • Using styles with the DateField component
  • Using skins with the DateField component

Using styles with the DateField component

You can set style properties to change the appearance of a date field instance. If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

A DateField component that uses the Halo theme supports the following styles:

Style | Description
themeColor | The glow color for the rollover and selected dates. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style; either "normal", or "italic".
fontWeight | The font weight; either "normal", or "bold".
textDecoration | The text decoration: either "none", or "underline".

Using skins with the DateField component

The DateField component uses skins to represent the visual states of the pop-up icon. To skin the pop-up icon while authoring, modify skin symbols in the Flash UI Components 2/Themes/MMDefault/DateField Elements skins states folder in the library of one of the themes FLA files. For more information, see About skinning components.

Only the pop-up icon button can be skinned in this component. A DateField component uses the following skin properties to dynamically skin the pop-up icon:

Property | Description
openDateUp | The up state of the pop-up icon.
openDateDown | The down state of the pop-up icon.
openDateOver | The over state of the pop-up icon.
openDateDisabled | The disabled state of the pop-up icon.


DateField class (Flash Professional only)

Inheritance UIObject > UIComponent > ComboBase > DateField

ActionScript Class Name mx.controls.DateField

The properties of the DateField class allow you to access the selected date, and the displayed month and year. You can also set the names of the days and months, indicate disabled dates and selectable dates, set the first day of the week, and indicate whether the current date should be highlighted.

Setting a property of the DateField class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.DateField.version);

Note: The following code returns undefined: trace(myDateFieldInstance.version);.

Method summary for the DateField class

Method | Description
DateField.close() | Closes the pop-up date chooser subcomponent.
DateField.open() | Opens the pop-up date chooser subcomponent.

Inherits all methods from UIObject and UIComponent.

Property summary for the DateField class

Property | Description
DateField.dateFormatter | A function that formats the date to be displayed in the text field.
DateField.dayNames | An array indicating the names of the days of the week.
DateField.disabledDays | An array indicating the days of the week that are disabled for all applicable dates in the date chooser.
DateField.disabledRanges | A range of disabled dates or a single disabled date.
DateField.displayedMonth | A number indicating an element in the monthNames array to display in the date chooser.
DateField.displayedYear | A number indicating the year to display.
DateField.firstDayOfWeek | A number indicating an element in the dayNames array to display in the first column of the date chooser.
DateField.monthNames | An array of strings indicating the month names.
DateField.pullDown | A reference to the DateChooser subcomponent. This property is read-only.
DateField.selectableRange | A single selectable date or a range of selectable dates.
DateField.selectedDate | A Date object indicating the selected date.
DateField.showToday | A Boolean value indicating whether the current date is highlighted.

Inherits all properties from UIObject and UIComponent.

Event summary for the DateField class

Event | Description
DateField.change | Broadcast when a date is selected.
DateField.close | Broadcast when the date chooser subcomponent closes.
DateField.open | Broadcast when the date chooser subcomponent opens.
DateField.scroll | Broadcast when the month buttons are pressed.

Inherits all events from UIObject and UIComponent.


DateField.change

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

on(change){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.change = function(eventObject){
  ...
}
myDF.addEventListener("change", listenerObject)

Description

Event; broadcast to all registered listeners when a date is selected.

The first usage example uses an on() handler and must be attached directly to a DateField component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date field myDF, sends "_level0.myDF" to the Output panel:

on(change){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (chooserInstance) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when a date field called myDF is changed. The first line of code creates a listener object called form. The second line defines a function for the change event on the listener object. Inside the function is a trace action that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event, in this example myDF. The DateField.selectedDate property is accessed from the event object's target property. The last line calls the UIEventDispatcher.addEventListener() method from myDF and passes it the change event and the form listener object as parameters, as in the following:

form.change = function(eventObj){
    trace("date selected " +  eventObj.target.selectedDate) ;
}
myDF.addEventListener("change", form);


DateField.close()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.close()

Parameters

None.

Returns

Nothing.

Description

Method; closes the pop-up menu.

Example

The following code closes the date chooser pop-up of the myDF date field instance:

myDF.close();


DateField.close

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

on(close){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.close = function(eventObject){
  ...
}
myDF.addEventListener("close", listenerObject)

Description

Event; broadcast to all registered listeners when the DateChooser subcomponent closes after a user clicks outside the icon or selects a date.

The first usage example uses an on() handler and must be attached directly to a DateField component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date field myDF, sends "_level0.myDF" to the Output panel:

on(close){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (myDF) dispatches an event (in this case, close) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when the date chooser within myDF closes. The first line of code creates a listener object called form. The second line defines a function for the close event on the listener object. Inside the function is a trace action that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event, in this example myDF. The property is accessed from the event object's target property. The last line calls the UIEventDispatcher.addEventListener() method from myDF and passes it the close event and the form listener object as parameters, as in the following:

form.close = function(eventObj){
  trace("PullDown Closed" + eventObj.target.selectedDate);
}
myDF.addEventListener("close", form);


DateField.dateFormatter

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.dateFormatter

Description

Property; a function that formats the date to be displayed in the text field. The function must receive a Date object as parameter, and return a string in the format to be displayed.

Example

The following example sets the function to return the format of the date to be displayed:

myDF.dateFormatter = function(d:Date){
  return d.getFullYear()+"/ "+(d.getMonth()+1)+"/ "+d.getDate();
};


DateField.dayNames

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.dayNames

Description

Property; an array containing the names of the days of the week. Sunday is the first day (at index position 0) and rest of the day names follow in order. The default value is ["S", "M", "T", "W", "T", "F", "S"].

Example

The following example changes the value of the 5th day of the week (Thursday) from "T" to "R":

myDF.dayNames[4] = "R";


DateField.disabledDays

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.disabledDays

Description

Property; an array indicating the disabled days of the week. All the dates in a month that fall on the specified day are disabled. The elements of this array can have values between 0 (Sunday) and 6 (Saturday). The default value is [] (empty array).

Example

The following example disables Sundays and Saturdays so that users can select only weekdays:

myDF.disabledDays = [0, 6];


DateField.disabledRanges

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.disabledRanges

Description

Property; disables a single day or a range of days. This property is an array of objects. Each object in the array must be either a Date object specifying a single day to disable, or an object containing either or both of the properties rangeStart and rangeEnd, each of whose value must be a Date object. The rangeStart and rangeEnd properties describe the boundaries of the date range. If either property is omitted the range is unbounded in that direction.

The default value of disabledRanges is undefined.

Specify a full date when you define dates for the disabledRanges property. For example, new Date(2003,6,24) rather than new Date(). If you don't specify a full date, the time returns as 00:00:00.

Example

The following example defines an array with rangeStart and rangeEnd Date objects that disable the dates between May 7 and June 7:

myDF.disabledRanges = [ {rangeStart: new Date(2003, 4, 7), rangeEnd: new Date(2003, 5, 7)}];

The following example disables all dates after November 7:

myDF.disabledRanges = [ {rangeStart: new Date(2003, 10, 7)} ];

The following example disables all dates before October 7:

myDF.disabledRanges = [ {rangeEnd: new Date(2002, 9, 7)} ];

The following example disables only December 7:

myDF.disabledRanges = [ new Date(2003, 11, 7) ];


DateField.displayedMonth

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.displayedMonth

Description

Property; a number indicating which month is displayed. The number indicates an element in the monthNames array, with 0 being the first month. The default value is the month of the current date.

Example

The following example sets the displayed month to December:

myDF.displayedMonth = 11;

See also

DateField.displayedYear


DateField.displayedYear

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.displayedYear

Description

Property; a number indicating which year is displayed. The default value is the current year.

Example

The following example sets the displayed year to 2010:

myDF.displayedYear = 2010;

See also

DateField.displayedMonth


DateField.firstDayOfWeek

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.firstDayOfWeek

Description

Property; a number indicating which day of the week (0-6, 0 being the first element of dayNames array) is displayed in the first column of the DateField component. Changing this property changes the order of the day columns but has no effect on the order of the dayNames property. The default value is 0 (Sunday).

Example

The following example sets the first day of the week to Monday:

myDF.firstDayOfWeek = 1;

See also

DateField.dayNames


DateField.monthNames

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.monthNames

Description

Property; an array of strings indicating the month names at the top of the DateField component. The default value is ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"].

Example

The following example sets the month names for the instance myDF:

myDF.monthNames = ["Jan", "Feb","Mar","Apr", "May", "June","July", "Aug" , "Sept","Oct", "Nov", "Dec"];


DateField.open()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.open()

Parameters

None.

Returns

Nothing.

Description

Method; opens the pop-up DateChooser subcomponent.

Example

The following code opens the pop-up date chooser of the df instance:

df.open();


DateField.open

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

on(open){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.open = function(eventObject){
  ...
}
myDF.addEventListener("open", listenerObject)

Description

Event; broadcast to all registered listeners when a date chooser subcomponent opens after a user clicks on the icon.

The first usage example uses an on() handler and must be attached directly to a DateField component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date field myDF, sends "_level0.myDF" to the Output panel:

on(open){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (myDF) dispatches an event (in this case, open) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when a stepper called myDF is opened. The first line of code creates a listener object called form. The second line defines a function for the open event on the listener object. Inside the function is a trace action that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event, in this example myDF. The DateField.selectedDate property is accessed from the event object's target property. The last line calls the UIEventDispatcher.addEventListener() method from myDF and passes it the open event and the form listener object as parameters, as in the following:

form.open = function(eventObj){
    trace("Pop-up opened and date selected is " +  eventObj.target.selectedDate) ;
}
myDF.addEventListener("open", form);


DateField.pullDown

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.pullDown

Description

Property (read-only); a reference to the DateChooser component contained by the DateField component. The DateChooser subcomponent is instantiated when a user clicks on the DateField component. However, if the pullDown property is referenced before the user clicks on the component, the DateChooser is instantiated and then hidden.

Example

The following example sets the visibility of the DateChooser subcomponent to false and then sets the size of the DateChooser subcomponent to 300 pixels high and 300 pixels wide:

myDF.pullDown._visible = false;
myDF.pullDown.setSize(300,300);


DateField.scroll

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

on(scroll){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.scroll = function(eventObject){
  ...
}
myDF.addEventListener("scroll", listenerObject)

Description

Event; broadcast to all registered listeners when a month button is pressed.

The first usage example uses an on() handler and must be attached directly to a DateField component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the date field myDF, sends "_level0.myDF" to the Output panel:

on(scroll){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (myDF) dispatches an event (in this case, scroll) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. The scroll event's event object has an additional property, detail, that can have one of the following values: nextMonth, previousMonth, nextYear, previousYear.

Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when a month button is pressed on a DateField instance called myDF. The first line of code creates a listener object called form. The second line defines a function for the scroll event on the listener object. Inside the function is a trace action that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event, in this example myDF. The last line calls the UIEventDispatcher.addEventListener() method from myDateField and passes it the scroll event and the form listener object as parameters, as in the following:

form = new Object();
form.scroll = function(eventObj){
  trace(eventObj.detail);
}
myDF.addEventListener("scroll", form);


DateField.selectableRange

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.selectableRange

Description

Property; sets a single selectable date or a range of selectable dates. The value of this property is an object that consists of two Date objects named rangeStart and rangeEnd. The rangeStart and rangeEnd properties designate the boundaries of the selectable date range. If only rangeStart is defined, all the dates after rangeStart are enabled. If only rangeEnd is defined, all the dates before rangeEnd are enabled. The default value is undefined.

If you want to enable only a single day, you can use a single Date object as the value of selectableRange.

Specify a full date when you define dates. For example, new Date(2003,6,24) rather than new Date(). If you don't specify a full date, the time returns as 00:00:00.

The value of DateField.selectedDate is set to undefined if it falls outside the selectable range.

The value of DateField.displayedMonth and DateField.displayedYear are set to the nearest last month in the selectable range if the current month falls outside the selectable range. For example, if the current displayed month is August, and the selectable range is from June, 2003 - July, 2003, the displayed month will change to July, 2003.

Example

The following example defines the selectable range to the dates between and including May 7 and June 7:

myDF.selectableRange = {rangeStart: new Date(2001, 4, 7), rangeEnd: new Date(2003, 5, 7)};

The following example defines the selectable range to the dates after and including May 7:

myDF.selectableRange = {rangeStart: new Date(2003, 4, 7)};

The following example defines the selectable range to the dates before and including June 7:

myDF.selectableRange = {rangeEnd: new Date(2003, 5, 7) };

The following example defines the selectable date as June 7 only:

myDF.selectableRange = new Date(2003, 5, 7);


DateField.selectedDate

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.selectedDate

Description

Property; a Date object that indicates the selected date if that value falls within the value of the selectableRange property. The default value is undefined.

Example

The following example sets the selected date to June 7:

myDF.selectedDate = new Date(2003, 5, 7);


DateField.showToday

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myDF.showToday

Description

Property; this property determines whether the current date is highlighted. The default value is true.

Example

The following example turns off the highlighting on today's date:

myDF.showToday = false;


About the Delta interface

The Delta interface provides access to the transfer object, collection, and transfer object-level changes. With this interface you can access the new and previous values in a transfer object. You can also access messages returned by the associated server-side process. For more information on client-server interactions, see RDBMSResolver component (Flash Professional only).


Using the Delta interface (Flash Professional only)

Use the Delta interface to examine the DeltaPacket before sending changes to the server and to review messages returned from server-side processing.

ActionScript Interface Name mx.data.components.datasetclasses.Delta

Method summary for the Delta interface

Method | Description
Collection.addItem() | Adds the specified DeltaItem.
Delta.getChangeList() | Returns an array of changes made to the current item.
Delta.getDeltaPacket() | Returns the DeltaPacket that contains the Delta.
Delta.getId() | Returns the unique ID of the current item within the DeltaPacket collection.
Delta.getItemByName() | Returns the specified DeltaItem.
Delta.getMessage() | Returns the message associated with the current item.
Delta.getOperation() | Returns the operation that was performed on the current item within the original collection.
Delta.getSource() | Returns the transfer object that these mutations have been performed on.


Delta.addDeltaItem()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

delta.addDeltaItem(deltaitem)

Parameters

deltaitem DeltaItem instance to add to this Delta.

Returns

Nothing.

Description

Method; adds the specified DeltaItem. If the specified DeltaItem already exists, this method replaces it.

Example

The following example calls the addDeltaItem() method:

//...
var d:Delta = new DeltaImpl( "ID1345678", curItem, DeltaPacketConsts.Added, "", false);
d.addDeltaItem( new DeltaItem( DeltaItem.Property, "ID", {oldValue:15, newValue:16}));
//...


Delta.getChangeList()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

delta.getChangeList()

Parameters

None.

Returns

An array of associated DeltaItem instances.

Description

Method; returns an array of associated DeltaItem instances. Each DeltaItem in the array describes a change made to the item.

Example

The following example calls the getChangeList() method.:

//...
case mx.data.components.datasetclasses.DeltaPacketConsts.Modified: {
  // dpDelta is a variable of type Delta.
  var changes:Array = dpDelta.getChangeList();
  for( var i:Number = 0; i<changes.length; i++ ) {
    // getChangeMessage is a user-defined method.
    changeMsg = _parent.getChangeMessage( changes[i] );
    trace( changeMsg );
  } // for
//...


Delta.getDeltaPacket()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

delta.getDeltaPacket()

Parameters

None.

Returns

The DeltaPacket instance that contains this Delta instance.

Description

Method; returns the DeltaPacket instance that contains this Delta instance. This method allows you to write code that can handle DeltaPackets generically at the Delta level.

Example

The following example uses the getDeltaPacket() method to access the DeltaPacket's data source:

//...
while( dpCursor.hasNext()) {
  dpDelta = Delta(dpCursor.next());
  trace("DeltaPacket source is: " + dpDelta.getDeltaPacket().getSource());
//...


Delta.getId()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

delta.getId()

Parameters

None.

Returns

An object; returns the unique ID of this item within the DeltaPacket collection.

Description

Method; returns a unique identifier for this item within the DeltaPacket collection. Use this ID in the source component for the DeltaPacket to receive updates and make changes to items that the DeltaPacket was generated from. For example, assuming that the DataSet component sends updates to a server and the server returns new key field values, this method allows the DataSet component to examine the resulting DeltaPacket, find the original transfer object, and make the appropriate updates to it.

Example

The following example calls the getId() method:

//...
while( dpCursor.hasNext()) {
  dpDelta = Delta(dpCursor.next());
  trace( "id ["+dpDelta.getId()+"]");
//...


Delta.getItemByName()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

delta.getItemByName(name)

Parameters

name A string that specifies the name of the property or method for the associated DeltaItem.

Returns

The DeltaItem specified by name. If no DeltaItem is found that matches name, this method returns null.

Description

Method; returns the DeltaItem specified by name. This method provides the most efficient access, when method calls or property changes on a transfer object are needed by name.

Example

The following example calls the getItemByName() method:

//...
private function buildFieldTag( deltaObj:Delta, field:Object, isKey:Boolean ):String {
    var chgItem:DeltaItem = deltaObj.getItemByName(field.name);
    var result:String= "<field name=\"" + field.name + "\" type=\"" + field.type.name + "\"";
    var oldValue:String;
    var newValue:String;
    if (deltaObj.getOperation() != DeltaPacketConsts.Added) {
      oldValue = (chgItem != null ? (chgItem.oldValue != null ? encodeFieldValue(field.name, chgItem.oldValue) : __nullValue) : encodeFieldValue(field.name, deltaObj.getSource()[field.name]));
      newValue = (chgItem.newValue != null ? encodeFieldValue(field.name, chgItem.newValue) : __nullValue);
      result+= " oldValue=\""  + oldValue + "\"";
      result+= chgItem != null ? " newValue=\"" + newValue + "\"" : "";
      result+= " key=\"" + isKey.toString() + "\" />";
    }
    else {
      result+= " newValue=\"" +encodeFieldValue(field.name,  deltaObj.getSource()[field.name]) + "\"";
      result+= " key=\"" + isKey.toString() + "\" />";
    }
    return result;
  } //buildFieldTag function
//...


Delta.getMessage()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

delta.getMessage()

Parameters

None.

Returns

A string; returns the message associated with Delta.

Description

Method; returns the associated message for this delta. Typically this message is only populated if the DeltaPacket has been returned from a server in response to attempted updates. For more information, see RDBMSResolver component (Flash Professional only).

Example

The following example calls the getMessage() method:

//...
var dpi:Iterator = dp.getIterator();
var d:Delta;
while( dpi.hasNext()) {
  d= dpi.next();
  trace( d.getMessage());
}
//...


Delta.getOperation()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

delta.getOperation()

Parameters

None.

Returns

A number; returns the operation that was performed on the item within the original collection

Description

Method; returns the operation that was performed on this item within the original collection. Valid values for this are as follows:

  • DeltaPacketConsts.Added
  • DeltaPacketConsts.Removed
  • DeltaPacketConsts.Modified

You must either import mx.data.components.datasetclasses.DeltaPacketConsts or fully qualify each constant.

Example

The following example calls the getOperation() method:

//...
while( dpCursor.hasNext()) {
  dpDelta = Delta(dpCursor.next());
  op=dpDelta.getOperation();
  trace("DeltaPacket source is: " + dpDelta.getDeltaPacket().getSource());
  switch( op ) {
    case mx.data.components.datasetclasses.DeltaPacketConsts.Added:
      trace("***In case DeltaPacketConsts.Added ***");
    case mx.data.components.datasetclasses.DeltaPacketConsts.Modified: {
      trace("***In case DeltaPacketConsts.Modified ***");
//...


Delta.getSource()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

delta.getSource()

Parameters

None.

Returns

The transfer object the changes were performed on.

Description

Method; returns the transfer object the changes were performed on.

Example

The following example calls the getSource() method:

//...
while( dpCursor.hasNext()) {
dpDelta = Delta(dpCursor.next());
op=dpDelta.getOperation();
switch( op ) {
case mx.data.components.datasetclasses.DeltaPacketConsts.Modified: {
// the original values are
trace("Unmodified source is: ");
var src = dpDelta.getDeltaPacket().getSource();
for( var i in src )
  if( typeof(src[i]) != "function" )
    trace( i+"="+src[i] );
//...


About the DeltaItem class

The DeltaItem class provides information about an individual operation performed on a transfer object. For example, the DeltaItem indicates whether a change was made directly to a property of the transfer object or via a method call. It also provides the original state of properties on a transfer object. In addition it contains server response information such as current value and a message.


Using the DeltaItem class (Flash Professional only)

Use the DeltaItem class when accessing the changes in a DeltaPacket. To access these changes, use DeltaPacket.getIterator(), which returns an iterator of Delta instances. Each Delta instance contains zero or more DeltaItem instances, which you can access through either Delta.getItemByName() or Delta.getChangeList().

ActionScript Class Name mx.data.components.datasetclasses.DeltaItem

Property summary for the DeltaItem class

Property | Description
DeltaItem.argList | If a change is made via a method call, this is the array of argument values that were passed to the method.
DeltaItem.curValue | If change is to a property, this is the current server value of the property.
DeltaItem.delta | Associated Delta for the DeltaItem.
DeltaItem.kind | Indicates the type of change.
DeltaItem.message | Server message associated with the DeltaItem.
DeltaItem.name | The name of the property or method that changed.
DeltaItem.newValue | If change is to a property, this is the new value of the property.
DeltaItem.oldValue | If change is to a property, this is the old value of the property.


DeltaItem.argList

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaitem.argList

Description

Property; read-only array of argument values passed to the change method. This property only applies if the change's kind is DeltaItem.Method.


DeltaItem.curValue

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaitem.curValue

Description

Property; read-only object containing the current property value on the server's copy of the transfer object. This property applies only if the change's kind is DeltaItem.Property and is only relevant in a Delta that has been returned from a server and is being applied to the data set for user resolution.


DeltaItem.delta

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaitem.delta

Description

Property; read-only Delta associated with the DeltaItem. When a DeltaItem is created, it is associated with a Delta and adds itself to the Delta's list of changes. This property provides a reference to the Delta this item belongs to.


DeltaItem.kind

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaitem.kind

Description

Property; number that indicates the type of change. Use the following constants to evaluate this property:

  • DeltaItem.Property The change was made to a property on the transfer object.
  • DeltaItem.Method The change was made using a method call on the transfer object.


DeltaItem.message

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaitem.message

Description

Property; string containing a server message associated with this DeltaItem. This can be any message for the property or method call change attempted within the DeltaPacket. This message is generally only relevant in a Delta that has been returned from a server and is being applied to the DataSet for resolution.


DeltaItem.name

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaitem.name

Description

Property; read-only string containing the name of the changed property (if the change's kind is DeltaItem.Property) or the name of the method that made the change (if the change's kind is DeltaItem.Method).


DeltaItem.newValue

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaitem.newValue

Description

Property; read-only object containing the new value of the property. This property applies only if the change's kind is DeltaItem.Property.


DeltaItem.oldValue

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaitem.oldValue

Description

Property; read-only object containing the old value of the property. This property applies only if the change's kind is DeltaItem.Property.


About the DeltaPacket interface

You use the DeltaPacket interface in combination with the DataSet component (part of the data management functionality in the Flash MX Professional 2004 data architecture). The DeltaPacket interface, and the related Delta interface and DeltaItem class enable you to manage changes made to the data. These components have no visual appearance at runtime.

A DeltaPacket is an optimized set of instructions that describes the changes made to data at runtime. If the DataSet.logChanges parameter is set to true, the DataSet component automatically saves before and after images of changes to the DataSet. When the DataSet.applyUpdates() method is called, the DataSet component populates the DataSet.deltaPacket property. You typically bind the DataSet.deltaPacket property to a resolver (for example, RDBMSResolver), which converts these instructions to an update packet in the appropriate format. For more information, see the RDBMSResolver documentation or refer to the Macromedia Support Center.


Using the DeltaPacket interface (Flash Professional only)

Use the DeltaPacket interface when you need to interact directly with changes going to and from the originating data source. Typically the DeltaPacket is used internally by resolver components.

ActionScript Interface Name mx.data.components.datasetclasses.DeltaPacket

Method summary for the DeltaPacket component

Method | Description
RDBMSResolver.addFieldInfo() | Returns configuration information that is specific to the implementation of the DeltaPacket.
DeltaPacket.getIterator() | Returns the iterator for the DeltaPacket.
DeltaPacket.getSource() | Returns the source of the DeltaPacket. This is the component that has exposed this DeltaPacket instance.
DeltaPacket.getTimestamp() | Returns the date and time when the DeltaPacket instance was instantiated.
DeltaPacket.getTransactionId() | Returns the transaction identifier for this DeltaPacket instance.
DeltaPacket.logChanges() | Indicates whether the consumer of the DeltaPacket instance should log the changes it specifies.


DeltaPacket.getConfigInfo()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaPacket.getConfigInfo(info)

Parameters

info Object; contains information specific to the implementation.

Returns

An object that contains information required for the specific DeltaPacket implementation.

Description

Method; returns configuration information that is specific to the implementation of the DeltaPacket. This method allows implementations of the DeltaPacket interface to access custom information using this interface.

Example

The following example calls the getConfigInfo() method:

//...
new DeltaPacketImpl( source, getTransactionId(), null, logChanges(), getConfigInfo());
//...


DeltaPacket.getIterator()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaPacket.getIterator()

Parameters

None.

Returns

An interface to the iterator for the DeltaPacket collection.

Description

Method; returns the iterator for the DeltaPacket. This provides a mechanism for looping through the changes within the DeltaPacket. For a complete description of this interface, see Iterator interface (Flash Professional only).

Example

The following example uses the getIterator() method to access the iterator for the Delta instances in a DeltaPacket and uses a while statement to loop through the Delta instances:

//...
var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket;
trace("*** Test deltapacket. Trans ID is: " + deltapkt.getTransactionId() + " ***");
var OPS:Array = new Array( "added", "removed", "modified" );
var dpCursor:Iterator = deltapkt.getIterator();
var dpDelta:Delta;
var op:Number;
var changeMsg:String;
while( dpCursor.hasNext()) {
  dpDelta = Delta(dpCursor.next());
  op=dpDelta.getOperation();
//...


DeltaPacket.getSource()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaPacket.getSource()

Parameters

None.

Returns

An object; the source of the DeltaPacket collection. This is typically a descendent of MovieClip; however, this is not required. For example, if the source is a DataSet, this might be _level0.myDataSet.

Description

Method; returns the source of the DeltaPacket collection.

Example

The following example calls the getSource() method:

//...
var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket;
var dpSourceText:String = "Source: " + deltapkt.getSource();
trace(dpSourceText);
//...


DeltaPacket.getTimestamp()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaPacket.getTimestamp()

Parameters

None.

Returns

A Date object containing the date and time the DeltaPacket was created.

Description

Method; returns the date and time the DeltaPacket was created.

Example

The following example calls the getTimeStamp() method:

//...
var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket;
var dpTime:String = " Time: " + deltapkt.getTimestamp();
trace(dpTime);
//...


DeltaPacket.getTransactionId()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaPacket.getTransactionId()

Parameters

None.

Returns

A string; the unique transaction ID for a single transaction grouping of DeltaPackets.

Description

Method; returns the transaction identifier for the DeltaPacket instance. This unique identifier is used to group a send/receive transaction for a DeltaPacket. The DataSet uses this to determine if the DeltaPacket instance is part of the same transaction it originated with the DataSet.applyUpdates() call.

Example

The following example calls the getTransactionId() method:

//...
var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket;
trace("*** Trans ID is: " + deltapkt.getTransactionId() + " ***");
//...


DeltaPacket.logChanges()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

deltaPacket.logChanges()

Parameters

None.

Returns

A Boolean value; true if the consumer should log changes found in the DeltaPacket.

Description

Method; returns true if the consumer of this DeltaPacket should log the changes it specifies. This value is used mainly for communication of changes between DataSet via sharedObjects or from a server to a local data set. In both cases the DataSet should not record the changes specified.

Example

The following example calls the logChanges() method:

//...
var deltapkt:DeltaPacket = _parent.myDataSet.deltaPacket;
if(deltapkt.logChanges()) {
  trace("*** We need to log changes. ***");
}
else {
  trace("*** We do not need to log changes");
}

//...


About the DepthManager class

ActionScript Class Name mx.managers.DepthManager

The DepthManager class adds functionality to the ActionScript MovieClip class that allows you to manage the relative depth assignments of any component or movie clip, including _root. It also allows you to manage reserved depths in a special highest-depth clip on the _root for system-level services like the cursor or tooltips.

The following methods compose the relative depth-ordering API:

  • DepthManager.createChildAtDepth()
  • DepthManager.createClassChildAtDepth()
  • DepthManager.setDepthAbove()
  • DepthManager.setDepthBelow()
  • DepthManager.setDepthTo()

The following methods compose the reserved depth space API:

  • DepthManager.createClassObjectAtDepth()
  • DepthManager.createObjectAtDepth()

Method summary for the DepthManager class

Method | Description
DepthManager.createChildAtDepth() | Creates a child of the specified symbol at the specified depth.
DepthManager.createClassChildAtDepth() | Creates an object of the specified class at that specified depth.
DepthManager.createClassObjectAtDepth() | Creates an instance of the specified class at a specified depth in the special highest-depth clip.
DepthManager.createObjectAtDepth() | Creates an object at a specified depth in the highest-depth clip.
DepthManager.setDepthAbove() | Sets the depth above the specified instance.
DepthManager.setDepthBelow() | Sets the depth below the specified instance.
DepthManager.setDepthTo() | Sets the depth to the specified instance in the highest-depth clip.


DepthManager.createChildAtDepth()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

movieClipInstance.createChildAtDepth(linkageName, depthFlag[, initObj])

Parameters

linkageName A linkage identifier. This parameter is a string.

depthFlag One of the following values: DepthManager.kTop, DepthManager.kBottom, DepthManager.kTopmost, DepthManager.kNotopmost. All depth flags are static properties of the DepthManger class. You must either reference the DepthManager package (for example, mx.managers.DepthManager.kTopmost), or use the import statement to import the DepthManager package.

initObj An initialization object. This parameter is optional.

Returns

A reference to the object created.

Description

Method; creates a child instance of the symbol specified by the linkageName parameter at the depth specified by the depthFlag parameter.

Example

The following example creates a minuteHand instance of the MinuteSymbol movie clip and places it on top of the clock:

import mx.managers.DepthManager;
minuteHand = clock.createChildAtDepth("MinuteSymbol", DepthManager.kTop);


DepthManager.createClassChildAtDepth()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

movieClipInstance.createClassChildAtDepth( className, depthFlag[, initObj] )

Parameters

className A class name.

depthFlag One of the following values: DepthManager.kTop, DepthManager.kBottom, DepthManager.kTopmost, DepthManager.kNotopmost. All depth flags are static properties of the DepthManger class. You must either reference the DepthManager package (for example, mx.managers.DepthManager.kTopmost), or use the import statement to import the DepthManager package.

initObj An initialization object. This parameter is optional.

Returns

A reference to the created child.

Description

Method; creates a child of the class specified by the className parameter at the depth specified by the depthFlag parameter.

Example

The following code draws a focus rectangle on top of all NoTopmost objects:

import mx.managers.DepthManager
this.ring = createClassChildAtDepth(mx.skins.RectBorder, DepthManager.kTop);

The following code creates an instance of the Button class and passes it a value for its label property as an initObj parameter:

import mx.managers.DepthManager
button1 = createClassChildAtDepth(mx.controls.Button, DepthManager.kTop, {label: "Top Button"});


DepthManager.createClassObjectAtDepth()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

DepthManager.createClassObjectAtDepth(className, depthSpace[, initObj])

Parameters

className A class name.

depthSpace One of the following values: DepthManager.kCursor, DepthManager.kTooltip. All depth flags are static properties of the DepthManger class. You must either reference the DepthManager package (for example, mx.managers.DepthManager.kCursor), or use the import statement to import the DepthManager package.

initObj An initialization object. This parameter is optional.

Returns

A reference to the created object.

Description

Method; creates an object of the class specified by the className parameter at the depth specified by the depthSpace parameter. This method is used for accessing the reserved depth spaces in the special highest-depth clip.

Example

The following example creates an object from the Button class:

import mx.managers.DepthManager
myCursorButton = createClassObjectAtDepth(mx.controls.Button, DepthManager.kCursor, {label: "Cursor"});


DepthManager.createObjectAtDepth()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

DepthManager.createObjectAtDepth(linkageName, depthSpace[, initObj])

Parameters

linkageName A linkage identifier.

depthSpace One of the following values: DepthManager.kCursor, DepthManager.kTooltip. All depth flags are static properties of the DepthManger class. You must either reference the DepthManager package (for example, mx.managers.DepthManager.kCursor), or use the import statement to import the DepthManager package.

initObj An initialization object.

Returns

A reference to the created object.

Description

Method; creates an object at the specified depth. This method is used for accessing the reserved depth spaces in the special highest-depth clip.

Example

The following example creates an instance of the TooltipSymbol symbol and places it at the reserved depth for tooltips:

import mx.managers.DepthManager
myCursorTooltip = createObjectAtDepth("TooltipSymbol", DepthManager.kTooltip);


DepthManager.setDepthAbove()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

movieClipInstance.setDepthAbove(instance)

Parameters

instance An instance name.

Returns

Nothing.

Description

Method; sets the depth of a movie clip or component instance above the depth of the instance specified by the instance parameter.


DepthManager.setDepthBelow()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

movieClipInstance.setDepthBelow(instance)

Parameters

instance An instance name.

Returns

Nothing.

Description

Method; sets the depth of a movie clip or component instance below the depth of the instance specified by the instance parameter.

Example

The following code sets the depth of the textInput instance below the depth of the button:

textInput.setDepthBelow(button);


DepthManager.setDepthTo()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

movieClipInstance.setDepthTo(depth)

Parameters

depth A depth level.

Returns

Nothing.

Description

Method; sets the depth of movieClipInstance to the value specified by depth. This method moves an instance to another depth to make room for another object.

Example

The following example sets the depth of the mc1 instance to a depth of 10:

mc1.setDepthTo(10);

For more information about depth and stacking order, see Determining the next highest available depth.


About the FocusManager class

You can use the FocusManager to specify the order in which components receive focus when a user presses the Tab key to navigate in an application. You can use the FocusManager API to set a button in your document that receives keyboard input when a user presses Enter (Windows) or Return (Macintosh). For example, when a user fills out a form, they should be able to tab between fields and press Enter (Windows) or Return (Macintosh) to submit the form.

All components implement FocusManager support; you don't need to write code to invoke it. The FocusManager also interacts with the System Manager, which activates and deactivates FocusManager instances as pop-up windows are activated or deactivated. Each modal window has an instance of a FocusManager so the components in that window become their own tab set, preventing the user from tabbing into components in other windows.

The FocusManager recognizes groups of radio buttons (those with a defined RadioButton.groupName property) and sets focus to the instance in the group that has a selected property that is set to true. When the Tab key is pressed, the Focus Manager checks to see if the next object has the same groupName as the current object. If it does, it automatically moves focus to the next object with a different groupName. Other sets of components that support a groupName property can also use this feature.

The FocusManager handles focus changes due to mouse clicks. If the user clicks on a component, that component is given focus.

The FocusManager does not automatically assign focus to a component in an application. The main window and any pop-up windows will not have focus set on any component by default unless you call FocusManager.setFocus() on a component.

See also:

  • Using the FocusManager
  • Customizing the FocusManager
  • FocusManager class


Using the FocusManager

The FocusManager does not automatically assign focus to a component. You must write a script that calls FocusManager.setFocus() on a component if you want a component to have focus when an application loads.

To create focus navigation in an application, set the tabIndex property on any objects (including buttons) that should receive focus. When a user presses the Tab key, the FocusManager looks for an enabled object with a tabIndex property that is higher than the current value of tabIndex. Once the FocusManager reaches the highest tabIndex property, it returns to zero. So, in the following example, the comment object (probably a TextArea component) receives focus first, and then the okButton object receives focus:

comment.tabIndex = 1;
okButton.tabIndex = 2;

You can also use the Accessibility panel to assign a tab index value.

If nothing on the Stage has a tab index value, the FocusManager uses the z-order. The z-order is set up primarily by the order components are dragged to the Stage, however, you can also use the Modify/Arrange/Bring-to-Front/Back commands to determine the final z-order.

To create a button that receives focus when a user presses Enter (Windows) or Return (Macintosh), set the FocusManager.defaultPushButton property to the instance name of the desired button, as in the following:

focusManager.defaultPushButton = okButton;

Note: The FocusManager is sensitive to when objects are placed on the Stage (the depth order of objects) and not their relative positions on the stage. This is different from the way Flash Player handles tabbing.

See also:

  • FocusManager parameters
  • Creating an application with the FocusManager

FocusManager parameters

There are no authoring parameters for the FocusManager. You must use the ActionScript methods and properties of the FocusManager class in the Actions panel. For more information, see FocusManager class.

Creating an application with the FocusManager

The following procedure creates a focus scheme in a Flash application.

  1. Drag the TextInput component from the Components panel to the Stage.
  2. In the Property inspector, assign it the instance name comment.
  3. Drag the Button component from the Components panel to the Stage.
  4. In the Property inspector, assign it the instance name okButton and set the label parameter to OK.
  5. In Frame 1 of the Actions panel, enter the following:
    comment.tabIndex = 1;
okButton.tabIndex = 2;
focusManager.setFocus(comment);
focusManager.defaultPushButton = okButton;
lo = new Object();
lo.click = function(evt){
  trace(evt.target + " was clicked");
}
okButton.addEventListener("click", lo);

    This code sets the tab ordering and specifies a default button to receive a click event when a user presses Enter (Windows) or Return (Macintosh).


Customizing the FocusManager

You can change the color of the focus ring in the Halo theme by changing the value of the themeColor style.

The FocusManager uses a FocusRect skin for drawing focus. This skin can be replaced or modified and subclasses can override UIComponent.drawFocus to draw custom focus indicators.


FocusManager class

Inheritance UIObject > UIComponent > FocusManager

ActionScript Class Name mx.managers.FocusManager

Method summary for the FocusManager class

Method | Description
FocusManager.getFocus() | Returns a reference to the object that has focus.
FocusManager.sendDefaultPushButtonEvent() | Sends a click event to listener objects registered to the default push button.
FocusManager.setFocus() | Sets focus to the specified object.

Property summary for the FocusManager class

Method | Description
FocusManager.defaultPushButton | The object that receives a click event when a user presses the Return or Enter key.
FocusManager.defaultPushButtonEnabled | Indicates whether keyboard handling for the default push button is turned on (true) or off (false). The default value is true.
FocusManager.enabled | Indicates whether tab handling is turned on (true) or off (false). The default value is true.
FocusManager.nextTabIndex | The next value of the tabIndex property.


FocusManager.defaultPushButton

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004.

Usage

focusManager.defaultPushButton

Description

Property; specifies the default push button for an application. When the user presses the Enter key (Windows) or Return key (Macintosh), the listeners of the default push button receive a click event. The default value is undefined and the data type of this property is object.

The FocusManager uses the emphasized style declaration of the SimpleButton class to visually indicate the current default push button.

The value of the defaultPushButton property is always the button that has focus. Setting the defaultPushButton property does not give initial focus to the default push button. If there are several buttons in an application, the button that is currently focused receives the click event when Enter or Return is pressed. If some other component has focus when Enter or Return is pressed, the defaultPushButton property is reset to its original value.

Example

The following code sets the default push button to the OKButton instance:

FocusManager.defaultPushButton = OKButton;

See also

FocusManager.defaultPushButtonEnabled, FocusManager.sendDefaultPushButtonEvent()


FocusManager.defaultPushButtonEnabled

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

focusManager.defaultPushButtonEnabled

Description

Property; a Boolean value that determines if keyboard handling of the default push button is turned on (true), or not (false). Setting defaultPushButtonEnabled to false allows a component to receive the Return or Enter key and handle it internally. You must re-enable default push button handling by watching the component's onKillFocus() method (see MovieClip.onKillFocus) or focusOut event. The default value is true.

Example

The following code disables default push button handling:

focusManager.defaultPushButtonEnabled = false;


FocusManager.enabled

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

focusManager.enabled

Description

Property; a Boolean value that determines if tab handling is turned on (true), or not (false) for a particular group of focus objects. (For example, another pop-up window could have its own FocusManager.) Setting enabled to false allows a component to receive the tab handling keys and handle them internally. You must re-enable the FocusManager handling by watching the component's onKillFocus() method (see MovieClip.onKillFocus) or focusOut event.

Example

The following code disables tabbing:

focusManager.enabled = false;


FocusManager.getFocus()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

focusManager.getFocus()

Parameters

None.

Returns

A reference to the object that has focus.

Description

Method; returns a reference to the object that currently has focus.

Example

The following code sets the focus to myOKButton if the currently focused object is myInputText:

if (focusManager.getFocus() == myInputText)
{
  focusManager.setFocus(myOKButton);
}

See also

FocusManager.setFocus()


FocusManager.nextTabIndex

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

FocusManager.nextTabIndex

Description

Property; the next available tab index number. Use this property to dynamically set an object's tabIndex property.

Example

The following code gives the mycheckbox instance the next highest tabIndex value:

mycheckbox.tabIndex = focusManager.nextTabIndex;

See also

UIComponent.tabIndex


FocusManager.sendDefaultPushButtonEvent()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

focusManager.sendDefaultPushButtonEvent()

Parameters

None.

Returns

Nothing.

Description

Method; sends a click event to listener objects registered to the default push button. Use this method to programmatically send a click event.

Example

The following code triggers the default push button click event and fills in the user name and password fields when a user selects the CheckBox instance chb (the check box would be labeled "Automatic Login"):

name_txt.tabIndex = 1;
password_txt.tabIndex = 2;
chb.tabIndex = 3;
submit_ib.tabIndex = 4;

focusManager.defaultPushButton = submit_ib;

chbObj = new Object();
chbObj.click = function(o){
  if (chb.selected == true){
    name_txt.text = "Jody";
    password_txt.text = "foobar";
    focusManager.sendDefaultPushButtonEvent();
  } else {
    name_txt.text = "";
    password_txt.text = "";
  }
}
chb.addEventListener("click", chbObj);

submitObj = new Object();
submitObj.click = function(o){
  if (password_txt.text != "foobar"){
    trace("error on submit");
  } else {
    trace("Yeah! sendDefaultPushButtonEvent worked!");
  }
}
submit_ib.addEventListener("click", submitObj);

See also

FocusManager.defaultPushButton, FocusManager.sendDefaultPushButtonEvent()


FocusManager.setFocus()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

focusManager.setFocus(object)

Parameters

object A reference to the object to receive focus.

Returns

Nothing.

Description

Method; sets focus to the specified object.

Example

The following code sets focus to myOKButton:

focusManager.setFocus(myOKButton);

See also

FocusManager.getFocus()


About the Form class (Flash Professional only)

The Form class provides the runtime behavior of forms you create in the Screen Outline pane in Flash MX Professional 2004. For an overview of working of working with screens, see Working with Screens (Flash Professional Only).

See also:

  • Using the Form class (Flash Professional only)
  • Form class (API)


Using the Form class (Flash Professional only)

Forms function as both containers for graphic objects—user interface elements in an application, for example—as well as application states. You can use the Screen Outline pane to visualize the different states of an application that you're creating, where each form is a different application state. For example, the following illustration shows the Screen Outline pane for an example application designed using forms.

Screen Outline view of sample form application

This illustration shows the outline for a sample application called "Employee Directory", which consists of several forms. The form named "entryForm" (selected in the above illustration) contains several user interface objects, including input text fields, labels, and a push button. The developer can easily present this form to the user by toggling its visibility (using the Form.visible property), while simultaneously toggling the visibility of other forms, as well.

Using the Behaviors panel (Window > Development Panels > Behaviors) you can also attach behaviors and controls to forms. For more information about adding transitions and controls to screens, see Creating controls and transitions for screens with behaviors (Flash Professional only).

Because the Form class extends the Loader class, you can easily load external content (either a SWF or JPEG file) into a form. For example, the contents of a form could be a separate SWF file, which itself might contain forms. In this way, you can modularize your form applications, which makes maintaining the applications easier, and also reduces initial download time. For more information, see Loading external content into screens (Flash Professional only).

See also:

  • Form object parameters

Form object parameters

The following are authoring parameters that you can set for each Form object instance in the Property inspector or in the Component Inspector panel:

autoload Indicates whether the content specified by the contentPath parameter should load automatically (true), or wait to load until the Loader.load() method is called (false). The default value is true.

contentPath Specifies the contents of the form. This can be the linkage identifier of a movie clip or an absolute or relative URL for a SWF or JPG file to load into the slide. By default, loaded content clips to fit the slide.

visible Specifies whether the form is visible (true) or not (false) when it first loads.


Form class (API)

Inheritance UIObject > UIComponent > View > Loader > Screen > Form

ActionScript Class Name mx.screens.Form

Method summary for the Form class

Method | Description
Form.getChildForm() | Returns the child form at a specified index.

Inherits all methods from UIObject, UIComponent, View, Loader component, and Screen class overview (Flash Professional only).

Property summary for the Form class

Property | Description
Form.currentFocusedForm | Returns the "leafmost" form that contains the global current focus.
Form.indexInParentForm | Returns the index (zero-based) of this form in its parent's list of subforms.
Form.visible | Specifies whether the form is visible when its parent form, slide, movie clip, or SWF is visible.
Form.numChildForms | Returns the number of child forms that this form contains.
Form.parentIsForm | Returns whether or not the parent object of this form is also a form.
Form.rootForm | Returns the root of the form tree, or subtree, that contains the form.

Inherits all properties from UIObject, UIComponent, View, Loader component, and Screen class overview (Flash Professional only).

Event summary for Form class

Inherits all events from UIObject, UIComponent, View, Loader component, and Screen class overview (Flash Professional only).


Form.currentFocusedForm

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mx.screens.Form.currentFocusedForm

Description

Property (read-only); returns the Form object that contains the global current focus. The actual focus may be on the form itself, or on a movie clip, text object, or component inside that form. May be null if there is no current focus.

Example

The following code, attached to a button (not shown), displays the name of the form with the current focus.

trace("The form with the current focus is: " + mx.screens.Form.currentFocusedForm);


Form.getChildForm()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myForm.getChildForm(childIndex)

Parameters

childIndex A number that indicates the index (zero-based) of the child form to return.

Returns

A Form object.

Description

Method; returns the child Form of myForm whose index is childIndex.

Example

The following example displays in the Output panel the names of all the child Form objects belonging to the root Form object named Application.

for (var i:Number = 0; i < _root.Application.numChildForms; i++) {
    var childForm:mx.screens.Form = _root.Application.getChildForm(i);
    trace(childForm._name);
}

See also

Form.numChildForms


Form.indexInParentForm

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myForm.indexInParentForm

Description

Property (read-only); contains the index (zero-based) of myForm in its parent's list of child forms. If the parent object of myForm is a screen but not a form (for example, it is a slide), then indexInParentForm is always 0.

Example

var myIndex:Number = myForm.indexInParent;
if (myForm == myForm._parent.getChildForm(myIndex)) {
  trace("I'm where I should be");
}

See also

Form.getChildForm()


Form.numChildForms

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myForm.numChildForms

Description

Property (read-only); returns the number of child forms contained by myForm. This property does not includes any slides that are contained my myForm, only forms.

Example

The following code iterates over all the child forms contained my myForm and displays their names in the Output panel.

var howManyKids:Number = myForm.numChildForms;
for(i=0; i<howManyKids; i++) {
  var childForm = myForm.getChildForm(i);
  trace(childForm._name);
}

See also

Form.getChildForm()


Form.parentIsForm

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myForm.parentIsForm

Description

Property (read-only): returns a Boolean (true or false) value indicating whether the specified form's parent object is also a form (true), or not (false). If false, then myForm is at the root of its form hierarchy.

Example

if (myForm.parentIsForm) {
  trace("I have "+myForm._parent.numChildScreens+" sibling screens");
} else {
  trace("I am the root form and have no siblings");
}


Form.rootForm

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myForm.rootForm

Description

Property (read-only); returns the form at the top of the form hierarchy that contains myForm. If myForm is contained by an object that is not a form (that is, a slide), then this property returns myForm.

Example

In the following example, a reference to the root form of myForm is placed into a variable named root. If the value assigned to root refers to myForm, then myForm is at the top of its form tree.

var root:my.screens.Form = myForm.rootForm;
if(rootForm == myForm) {
  trace("myForm is the top form in its tree");
}


Form.visible

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myForm.visible

Description

Property; determines whether myForm is visible when its parent form, slide, movie clip, or movie is visible. You can also set this property using the Property inspector in the Flash authoring environment.

When this property is set to true, myForm receives a reveal event; when set to false, myForm receives a hide event. You can attach transitions to forms that execute when a form receives one of these events. For more information on adding transitions to screens, see Creating controls and transitions for screens with behaviors (Flash Professional only).

Example

The following code, attached to an instance of the Button component, sets to false the visible property of the form that contains the button.

on(click) {
  _parent.visible = true;
}


About the Iterator interface

The Iterator interface allows you to step through the objects that a collection contains.

Using the Iterator interface

Use the Iterator interface when accessing objects stored in a collection.

ActionScript Class Name mx.utils.Iterator

Method summary for the Iterator interface

Method | Description
Iterator.hasNext() | Indicates whether the Iterator has more items.
Iterator.next() | Returns the next item in the iteration.


Iterator.hasNext()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

iterator.hasNext()

Returns

A Boolean value that contains true if there are more instances in the iterator and false if there are not.

Description

Method; indicates whether there are more instances in the iterator. You typically use this method in a while statement when looping through an iterator.

Example

The following example uses the hasNext() method to control looping through the iterator of items in a Collection:

on (click) {
  var myColl:mx.utils.Collection;
  myColl = _parent.thisShelf.MyCompactDisks;
  var itr:mx.utils.Iterator = myColl.getIterator();
  while (itr.hasNext()) {
    var cd:CompactDisk = CompactDisk(itr.next());
    var title:String = cd.Title;
    var artist:String = cd.Artist;
    trace("Title: "+title+" Artist: "+artist);
  }
}


Iterator.next()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

iterator.next()

Returns

An object that contains an instance of the next item in the iterator.

Description

Method; returns an instance of the next item in the iterator. You must cast this instance to the correct type.

Example

The following example uses the next() method to access the next item in a Collection:

on (click) {
  var myColl:mx.utils.Collection;
  myColl = _parent.thisShelf.MyCompactDisks;
  var itr:mx.utils.Iterator = myColl.getIterator();
  while (itr.hasNext()) {
    var cd:CompactDisk = CompactDisk(itr.next());
    var title:String = cd.Title;
    var artist:String = cd.Artist;
    trace("Title: "+title+" Artist: "+artist);
  }
}


About the Label component

A label component is a single line of text. You can specify that a label be formatted with HTML. You can also control alignment and sizing of a label. Label components don't have borders, cannot be focused, and don't broadcast any events.

A live preview of each Label instance reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring. The Label doesn't have a border, so the only way to see its live preview is to set its text parameter. The autoSize parameter is not supported in live preview.

When you add the Label component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility:

mx.accessibility.LabelAccImpl.enableAccessibility();

You only enable accessibility for a component once no matter how many instances you have of the component. For more information, see Creating Accessible Content.See also:

  • Using the label component
  • Customizing the label component
  • Label class


Using the label component

Use a Label component to create a text label for another component in a form, such as a "Name:" label to the left of a TextInput field that accepts a user's name. If you're building an application using components based on version 2 (v2) of the Macromedia Component Architecture, it's a good idea to use a Label component instead of a plain text field because you can use styles to maintain a consistent look and feel.

See also:

  • Label parameters
  • Creating an application with the Label component

Label parameters

The following are authoring parameters that you can set for each Label component instance in the Property inspector or in the Component Inspector panel:

text indicates the text of the label; the default value is Label.

html indicates whether the label is formatted with HTML (true) or not (false). If the html parameter is set to true, a Label cannot be formatted with styles. The default value is false.

autoSize indicates how the label sizes and aligns to fit the text. The default value is none. The parameter can be any of the following four values:

  • none—the label doesn't resize or align to fit the text.
  • left—the right and bottom sides of the label resize to fit the text. The left and top sides don't resize.
  • center—the bottom side of the label resizes to fit the text. The horizontal center of the label stays anchored at the its original horizontal center position.
  • right—the left and bottom sides of the label resize to fit the text. The top and right side don't resize.

Note: The Label component autoSize property is different from the built-in ActionScript TextField object's autoSize property.

You can write ActionScript to set additional options for Label instances using its methods, properties, and events. For more information, see Label class.

Creating an application with the Label component

The following procedure explains how to add a Label component to an application while authoring. In this example, the label is beside a combo box with dates in a shopping cart application.

To create an application with the Label component, do the following:

  1. Drag a Label component from the Components panel to the Stage.
  2. In the Component Inspector panel, enter Expiration Date for the label parameter.


Customizing the label component

You can transform a Label component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. You can also set the autoSize authoring parameter; setting this parameter doesn't change the bounding box in the Live Preview, but the label does resize. For more information, see Label parameters. At runtime, use the setSize() method (see UIObject.setSize()) or Label.autoSize.

See also:

  • Using styles with the Label component
  • Using skins with the Label component

Using styles with the Label component

You can set style properties to change the appearance of a label instance. All text in a Label component instance must share the same style. For example, you can't set the color style to "blue" for one word in a label and to "red" for the second word in the same label.

If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties.

For more information about styles, see Using styles to customize component color and text.

A Label component supports the following styles:

Style | Description
color | The default color for text.
embedFonts | The fonts to embed in the document.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style, either "normal" or "italic".
fontWeight | The font weight, either "normal" or "bold".
textAlign | The text alignment: either "left", "right", or "center".
textDecoration | The text decoration, either "none" or "underline".

Using skins with the Label component

The Label component is not skinnable.

For more information about skinning a component, see About skinning components.


Label class

Inheritance UIObject > Label

ActionScript Class Name mx.controls.Label

The properties of the Label class allow you at runtime to specify text for the label, indicate whether the text can be formatted with HTML, and indicate whether the label auto-sizes to fit the text.

Setting a property of the Label class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.Label.version);

Note: The following code returns undefined: trace(myLabelInstance.version);.

Method summary for the Label class

Inherits all methods from UIObject.

Property summary for the Label class

Property | Description
Label.autoSize | A string that indicates how a label sizes and aligns to fit the value of its text property. There are four possible values: "none", "left", "center", and "right". The default value is "none".
Label.html | A Boolean value that indicates whether a label can be formatted with HTML (true) or not (false).
Label.text | The text on the label.

Inherits all properties from UIObject.

Event summary for the Label class

Inherits all events from UIObject.


Label.autoSize

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

labelInstance.autoSize

Description

Property; a string that indicates how a label sizes and aligns to fit the value of its text property. There are four possible values: "none", "left", "center", and "right". The default value is "none".

  • none—the label doesn't resize or align to fit the text.
  • left—the right and bottom sides of the label resize to fit the text. The left and top sides don't resize.
  • center—the bottom side of the label resizes to fit the text. The horizontal center of the label stays anchored at the its original horizontal center position.
  • right—the left and bottom sides of the label resize to fit the text. The top and right side don't resize.

Note: The Label component autoSize property is different from the built-in ActionScript TextField object's autoSize property.


Label.html

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

labelInstance.html

Description

Property; a Boolean value that indicates whether the label can be formatted with HTML (true) or not (false). The default value is false. Label components with the html property set to true cannot be formatted with styles.

You cannot use the <font color> HTML tag with the Label component even when Label.html is set to true. For example, in the following example, the text "Hello" displays black, not red as it would if <font color> were supported:

lbl.html = true;
lbl.text = "<font color=\"#FF0000\">Hello</font> World";

In order to retrieve plain text from HTML formatted text, set the HTML property to false and then access the text property. This will remove the HTML formatting, so you may want to copy the label text to an off-screen Label or TextArea component before you retrieve the plain text.

Example

The following example sets the html property to true so the label can be formatted with HTML. The text property is then set to a string that includes HTML formatting, as follows:

labelControl.html = true;
labelControl.text = "The <b>Royal</b> Nonesuch";

The word "Royal" displays in bold.


Label.text

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

labelInstance.text

Description

Property; the text of a label. The default value is "Label".

Example

The following code sets the text property of the Label instance labelControl and sends the value to the Output panel:

labelControl.text = "The Royal Nonesuch";
trace(labelControl.text);


About the List component

The List component is a scrollable single- or multiple-selection list box. A list can also display graphics, including other components. You add the items displayed in the List using the Values dialog box that appears when you click in the labels or data parameter fields. You can also use the List.addItem() and List.addItemAt() methods to add items to the list.

The List component uses a zero-based index, where the item with index 0 is the top item displayed. When adding, removing, or replacing list items using the List class methods and properties, you may need to specify the index of the list item.

The List receives focus when you click it or tab to it, and you can then use the following keys to control it:

Key | Description
Alphanumerical keys | Jump to the next item with Key.getAscii() as the first character in its label.
Control | Toggle key. Allows multiple non-contiguous selects and deselects.
Down | Selection moves down one item.
Home | Selection moves to the top of the list.
Page Down | Selection moves down one page.
Page Up | Selection moves up one page.
Shift | Contiguous selection key. Allows for contiguous selection.
Up | Selection moves up one item.

Note: The page size used by the Page Up and Page Down keys is one less than the number of items that fit in the display. For example, paging down through a ten-line drop-down list will show items 0-9, 9-18, 18-27, and so on, with one item overlapping per page.

For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each List instance on the Stage reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring.

When you add the List component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility:

mx.accessibility.ListAccImpl.enableAccessibility();

You only enable accessibility for a component once no matter how many instances you have of the component. For more information, see Creating Accessible Content.See also:

  • Using the List component
  • Customizing the List component
  • List class


Using the List component

You can set up a list so that users can make either single or multiple selections. For example, a user visiting an e-commerce website needs to select which item to buy. There are 30 items, and the user scrolls through a list and selects one by clicking it.

You can also design a list that uses custom movie clips as rows so you can display more information to the user. For example, in an e-mail application, each mailbox could be a List component and each row could have icons to indicate priority and status.

See also:

  • List component parameters
  • Creating an application with the List component

List component parameters

The following are authoring parameters that you can set for each List component instance in the Property inspector or in the Component Inspector panel:

data An array of values that populate the data of the list. The default value is [] (an empty array). There is no equivalent runtime property.

labels An array of text values that populate the label values of list. The default value is [] (an empty array). There is no equivalent runtime property.

multipleSelection A Boolean value that indicates whether you can select multiple values (true) or not (false). The default value is false.

rowHeight This indicates the height, in pixels, of each row. The default value is 20. Setting a font does not change the height of a row.

You can write ActionScript to set additional options for List instances using its methods, properties, and events. For more information, see List class.

Creating an application with the List component

The following procedure explains how to add a List component to an application while authoring. In this example, the list is a sample with three items.

To add a simple List component to an application, do the following:

  1. Drag a List component from the Components panel to the Stage.
  2. Select the list and select Modify > Transform to resize it to fit your application.
  3. In the Property inspector, do the following:
    • Enter the instance name myList.
    • Enter Item1, Item2, and Item3 for the labels parameter.
    • Enter item1.html, item2.html, item3.html for the data parameter.
  4. Select Control > Test Movie to see the list with its items.

    You could use the data property values in your application to open HTML files.

The following procedure explains how to add a List component to an application while authoring. In this example, the list is a sample with three items.

To add a List component to an application, do the following:

  1. Drag a List component from the Components panel to the Stage.
  2. Select the list and select Modify > Transform to resize it to fit your application.
  3. In the Actions panel, enter the instance name myList
  4. Select Frame 1 of the Timeline and, in the Actions panel, enter the following:
    myList.dataProvider = myDP;

    If you have defined a data provider named myDP, the list will fill with data. For more information about data providers, see List.dataProvider.

  5. Select Control > Test Movie to see the list with its items.


Customizing the List component

You can transform a List component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the List.setSize() method (see UIObject.setSize()).

When a list is resized, the rows of the list shrink horizontally, clipping any text within them. Vertically, the list adds or removes rows as needed. Scroll bars position themselves automatically. For more information about scroll bars, see ScrollPane component.

See also:

  • Using styles with the List component
  • Using skins with the List component

Using styles with the List component

You can set style properties to change the appearance of a List component.

A List component uses the following Halo styles:

Style | Description
alternatingRowColors | Specifies colors for rows in an alternating pattern. The value can be an array of two or more colors, for example, 0xFF00FF, 0xCC6699, and 0x996699.
backgroundColor | The background color of the list. This style is defined on a class style declaration, ScrollSelectList.
borderColor | The black section of a three-dimensional border or the color section of a two-dimensional border.
borderStyle | The bounding box style. The possible values are: "none", "solid", "inset" and "outset". This style is defined on a class style declaration, ScrollSelectList.
defaultIcon | Name of the default icon to use for list rows. The default value is undefined.
rollOverColor | The color of a rolled over row.
selectionColor | The color of a selected row.
selectionEasing | A reference to an easing equation (function) used for controlling programmatic tweening.
disabledColor | The disabled color for text.
textRollOverColor | The color of text when the pointer rolls over it.
textSelectedColor | The color of text when selected.
selectionDisabledColor | The color of a row if it has been selected and disabled.
selectionDuration | The length of any transitions when selecting items.
useRollOver | Determines whether rolling over a row activates highlighting.

A List component also uses the style properties of the Label component (see Using styles with the Label component), the ScrollPane component (see ScrollPane component), and RectBorder.

Using skins with the List component

All the skins in the List component are included in the subcomponents from which the list is composed (ScrollPane component and RectBorder). For more information, see ScrollPane component. You can use the setStyle() method (see UIObject.setStyle()) to change the following RectBorder style properties:

RectBorder styles | Border position
borderColor | a
highlightColor | b
borderColor | c
shadowColor | d
borderCapColor | e
shadowCapColor | f
shadowCapColor | g
borderCapColor | h

The style properties set the following positions on the border:


List class

Inheritance UIObject > UIComponent > View > ScrollView > ScrollSelectList > List

ActionScript Class Name mx.controls.List

The List component is composed of three parts:

  • Items
  • Rows
  • A data provider

An item is an ActionScript object used for storing the units of information in the list. A list can be thought of as an array; each indexed space of the array is an item. An item is an object that typically has a label property that is displayed and a data property that is used for storing data.

A row is a component that is used to display an item. Rows are either supplied by default by the list (the SelectableRow class is used), or you can supply them, usually as a subclass of the SelectableRow class. The SelectableRow class implements the CellRenderer interface, which is the set of properties and methods that allow the list to manipulate each row and send data and state information (for example, size, selected, and so on) to the row for display.

A data provider is a data model of the list of items in a list. Any array in the same frame as a list is automatically given methods that allow you to manipulate data and broadcast changes to multiple views. You can build an Array instance or get one from a server and use it as a data model for multiple Lists, ComboBoxes, DataGrids, and so on. The List component has a set of methods that proxy to its data provider (for example, addItem() and removeItem()). If no external data provider is provided to the list, these methods create a data provider instance automatically, which is exposed through List.dataProvider.

To add a List component to the tab order of an application, set its tabIndex property (see UIComponent.tabIndex). The List component uses the FocusManager to override the default Flash Player focus rectangle and draw a custom focus rectangle with rounded corners. For more information, see Creating custom focus navigation.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.List.version);

Note: The following code returns undefined: trace(myListInstance.version);.

Method summary for the List class

Method | Description
List.addItem() | Adds an item to the end of the list.
List.addItemAt() | Adds an item to the list at the specified index.
List.getItemAt() | Returns the item at the specified index.
List.removeAll() | Removes all items from the list.
List.removeItemAt() | Removes the item at the specified index.
List.replaceItemAt() | Replaces the item at the specified index with another item.
List.setPropertiesAt() | Applies the specified properties to the specified item.
List.sortItems() | Sorts the items in the list according to the specified compare function.
List.sortItemsBy() | Sorts the items in the list according to a specified property.

Inherits all methods from UIObject and UIComponent.

Property summary for the List class

Property | Description
List.cellRenderer | Assigns the class or symbol to use to display each row of the list.
List.dataProvider | The source of the list items.
List.hPosition | The horizontal position of the list.
List.hScrollPolicy | Indicates whether the horizontal scroll bar is displayed ("on") or not ("off").
List.iconField | A field within each item to be used to specify icons.
List.iconFunction | A function that determines which icon to use.
List.labelField | Specifies a field of each item to be used as label text.
List.labelFunction | A function that determines which fields of each item to use for the label text.
List.length | The length of the list in items. This property is read-only.
List.maxHPosition | Specifies the number of pixels the list can scroll to the right, when List.hScrollPolicy is set to "on".
List.multipleSelection | Indicates whether multiple selection is allowed in the list (true) or not (false).
List.rowCount | The number of rows that are at least partially visible in the list.
List.rowHeight | The pixel height of every row in the list.
List.selectable | Indicates whether the list is selectable (true) or not (false).
List.selectedIndex | The index of a selection in a single-selection list.
List.selectedIndices | An array of the selected items in a multiple-selection list.
List.selectedItem | The selected item in a single-selection list. This property is read-only.
List.selectedItems | The selected item objects in a multiple-selection list. This property is read-only.
List.vPosition | Scrolls the list so the topmost visible item is the number assigned.
List.vScrollPolicy | Indicates whether the vertical scroll bar is displayed ("on"), not displayed ("off"), or displayed when needed ("auto").

Inherits all properties from UIObject and UIComponent.

Event summary for the List class

Event | Description
List.change | Broadcast whenever the selection changes due to user interaction.
List.itemRollOut | Broadcast when list items are rolled over and then off by the pointer.
List.itemRollOver | Broadcast when list items are rolled over by the pointer.
List.scroll | Broadcast when a list is scrolled.

Inherits all events from UIObject and UIComponent.


List.addItem()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.addItem(label[, data])
listInstance.addItem(itemObject)

Parameters

label A string that indicates the label for the new item.

data The data for the item. This parameter is optional and can be any data type.

itemObject An item object that usually has label and data properties.

Returns

The index at which the item was added.

Description

Method; adds a new item to the end of the list.

In the first usage example, an item object is always created with the specified label property, and, if specified, the data property.

The second usage example adds the specified item object.

Calling this method modifies the data provider of the List component. If the data provider is shared with other components, those components will update as well.

Example

Both of the following lines of code add an item to the myList instance. To try this code, drag a List to the Stage and give it the instance name myList. Add the following code to Frame 1 in the Timeline:

myList.addItem("this is an Item");
myList.addItem({label:"Gordon",age:"very old",data:123});


List.addItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.addItemAt(index, label[, data])
listInstance.addItemAt(index, itemObject)

Parameters

label A string that indicates the label for the new item.

data The data for the item. This parameter is optional and can be any data type.

index A number greater than or equal to zero that indicates the position of the item.

itemObject An item object that usually has label and data properties.

Returns

The index at which the item was added.

Description

Method; adds a new item to the position specified by the index parameter.

In the first usage example, an item object is always created with the specified label property, and, if specified, the data property.

The second usage example adds the specified item object.

Calling this method modifies the data provider of the List component. If the data provider is shared with other components, those components will update as well.

Example

The following line of code adds an item to the third index position, which is the fourth item in the list:

myList.addItemAt(3,{label:'Red',data:0xFF0000});


List.cellRenderer

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.cellRenderer

Description

Property; assigns the cell renderer to use for each row of the list. This property must be a class object reference, or a symbol linkage identifier. Any class used for this property must implement the CellRenderer API.

Example

The following example uses a linkage identifier to set a new cell renderer:

myList.cellRenderer = "ComboBoxCell";


List.change

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(change){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.change = function(eventObject){
  // your code here
}
listInstance.addEventListener("change", listenerObject)

Description

Event; broadcast to all registered listeners when the selected index of the list changes as a result of user interaction.

The first usage example uses an on() handler and must be attached directly to a list component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the list component instance myBox, sends "_level0.myBox" to the Output panel:

on(click){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (listInstance) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Finally, you call the addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

Example

The following example sends the instance name of the component that generated the change event to the Output panel:

form.change = function(eventObj){
  trace("Value changed to " + eventObj.target.value);
}
myList.addEventListener("change", form);

See also

UIEventDispatcher.addEventListener()


List.dataProvider

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listnstance.dataProvider

Description

Property; the data model for items viewed in a list. The value of this property can be an array or any object that implements the DataProvider interface. The default value is []. For more information about the DataProvider interface, see DataProvider API.

The List component, and other data-aware components, add methods to the Array object's prototype so that they conform to the DataProvider interface. Therefore, any array that exists at the same time as a list automatically has all the methods (addItem(), getItemAt(), and so on) it needs to be the data model for the list, and can be used to broadcast model changes to multiple components.

If the array contains objects, the List.labelField or List.labelFunction properties are accessed to determine what parts of the item to display. The default value is "label", so if a label field exists, it is chosen for display, if is doesn't exist, a comma-separated list of all fields is displayed.

Note: If the array contains strings at each index, and not objects, the list is not able to sort the items and maintain the selection state. Any sorting will lose the selection.

Any instance that implements the DataProvider interface can be a data provider for a List component. This includes Flash Remoting RecordSets, Firefly DataSets, and so on.

Example

This example uses an array of strings to populate the list:

list.dataProvider = ["Ground Shipping","2nd Day Air","Next Day Air"];

This example creates a data provider array and assigns it to the dataProvider property, as in the following:

myDP = new Array();
list.dataProvider = myDP;

for (var i=0; i<accounts.length; i++) {
  // these changes to the DataProvider will be broadcast to the list
  myDP.addItem({ label: accounts[i].name,
                 data:  accounts[i].accountID });
}


List.getItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.getItemAt(index)

Parameters

index A number greater than or equal to 0, and less than List.length. The index of the item to retrieve.

Returns

The indexed item object. Undefined if index is out of range.

Description

Method; retrieves the item at a specified index.

Example

The following code displays the label of the item at index position 4:

trace(myList.getItemAt(4).label);


List.hPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.hPosition

Description

Property; scrolls the list horizontally to the number of pixels specified. You can't set hPosition unless the value of hScrollPolicy is "on" and the list has a maxHPosition that is greater than 0.

Example

The following example gets the horizontal scroll position of myList:

var scrollPos = myList.hPosition;

The following example sets the horizontal scroll position all the way to the left:

myList.hPosition = 0;


List.hScrollPolicy

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.hScrollPolicy

Description

Property; a string that determines whether or not the horizontal scroll bar is displayed; the value can be "on" or "off". The default value is "off". The horizontal scroll bar does not measure text, you must set a maximum horizontal scroll position, see List.maxHPosition.

Note: The value "auto" is not supported for List.hScrollPolicy.

Example

The following code enables the list to scroll horizontally up to 200 pixels:

myList.hScrollPolicy = "on";
myList.Box.maxHPosition = 200;

See also

List.hPosition, List.maxHPosition


List.iconField

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.iconField

Description

Property; specifies the name of a field to be used as an icon identifier. If the field has a value of undefined, the default icon specified by the defaultIcon style is used. If the defaultIcon style is undefined, no icon is used.

Example

The following example sets the iconField property to the icon property of each item:

list.iconField = "icon"

See also

List.iconFunction


List.iconFunction

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.iconFunction

Description

Property; specifies a function to be used to determine which icon each row will use to display its item. This function receives a parameter, item, which is the item being rendered, and must return a string representing the icon's symbol identifier.

Example

The following example adds icons that indicate whether a file is an image or a text document. If the data.fileExtension field contains a value of "jpg" or "gif", the icon used will be "pictureIcon", and so on:

list.iconFunction = function(item){
  var type = item.data.fileExtension;
  if (type=="jpg" || type=="gif") {
    return "pictureIcon";
  } else if (type=="doc" || type=="txt") {
    return "docIcon";
  }
}


List.itemRollOut

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(itemRollOut){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.itemRollOut = function(eventObject){
  // your code here
}
listInstance.addEventListener("itemRollOut", listenerObject)

Event Object

In addition to the standard properties of the event object, the itemRollOut event has an additional property: index. The index is the number of the item that was rolled out.

Description

Event; broadcast to all registered listeners when the list items are rolled out.

The first usage example uses an on() handler and must be attached directly to a List component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the List instance myList, sends "_level0.myList" to the Output panel:

on(itemRollOut){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (listInstance) dispatches an event (in this case, itemRollOut) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example sends a message to the Output panel that indicates which item index number has been rolled over:

form.itemRollOut = function (eventObj) {
  trace("Item #" + eventObj.index + " has been rolled out.");
}
myList.addEventListener("itemRollOut", form);

See also

List.itemRollOver


List.itemRollOver

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(itemRollOver){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.itemRollOver = function(eventObject){
  // your code here
}
listInstance.addEventListener("itemRollOver", listenerObject)

Event Object

In addition to the standard properties of the event object, the itemRollOver event has an additional property: index. The index is the number of the item that was rolled over.

Description

Event; broadcast to all registered listeners when the list items are rolled over.

The first usage example uses an on() handler and must be attached directly to a List component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the List instance myList, sends "_level0.myList" to the Output panel:

on(itemRollOver){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (listInstance) dispatches an event (in this case, itemRollOver) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example sends a message to the Output panel that indicates which item index number has been rolled over:

form.itemRollOver = function (eventObj) {
  trace("Item #" + eventObj.index + " has been rolled over.");
}
myList.addEventListener("itemRollOver", form);

See also

List.itemRollOut


List.labelField

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.labelField

Description

Property; specifies a field within each item to be used as display text. This property takes the value of the field and uses it as the label. The default value is "label".

Example

The following example sets the labelField property to be the "name" field of each item. "Nina" would display as the label for the item added in the second line of code:

list.labelField = "name";
list.addItem({name: "Nina", age: 25});

See also

List.labelFunction


List.labelFunction

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.labelFunction

Description

Property; specifies a function to be used to decide which field (or field combination) to display of each item. This function receives one parameter, item, which is the item being rendered, and must return a string representing the text to display.

Example

The following example makes the label display some formatted details of the items:

list.labelFunction = function(item){
  return "The price of product " + item.productID + ", " + item.productName + " is $"
+ item.price;
}

See also

List.labelField


List.length

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.length

Description

Property (read-only); the number of items in the list.

Example

The following example places the value of length in a variable:

var len = myList.length;


List.maxHPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.maxHPosition

Description

Property; specifies the number of pixels the list can scroll when List.hScrollPolicy is set to "on". The list doesn't precisely measure the width of text that it contains. You must set maxHPosition to indicate the amount of scrolling that the list requires. The list will not scroll horizontally if this property is not set.

Example

The following example creates a list with 400 pixels of horizontal scrolling:

myList.hScrollPolicy = "on";
myList.maxHPosition = 400;

See also

List.hScrollPolicy


List.multipleSelection

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.multipleSelection

Description

Property; indicates whether multiple selections are allowed (true) or only single selections are allowed (false). The default value is false.

Example

The following example tests to determine whether multiple items may be selected:

if (myList.multipleSelection){
  // your code here
}

The following example allows the list to take multiple selections:

myList.selectMultiple = true;


List.removeAll()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.removeAll()

Parameters

None.

Returns

Nothing.

Description

Method; removes all items in the list.

Calling this method modifies the data provider of the List component. If the data provider is shared with other components, those components will update as well.

Example

The following code clears the list:

myList.removeAll();


List.removeItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.removeItemAt(index)

Parameters

index A string that indicates the label for the new item. A value greater than zero and less than List.length.

Returns

An object; the removed item (undefined if no item exists).

Description

Method; removes the item at the specified index position. The list indices after the index indicated by the index parameter collapse by one.

Calling this method modifies the data provider of the List component. If the data provider is shared with other components, those components will update as well.

Example

The following code removes the item at index position 3:

myList.removeItemAt(3);


List.replaceItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.replaceItemAt(index, label[, data])
listInstance.replaceItemAt(index, itemObject)

Parameters

index A number greater than zero and less than List.length that indicates the position at which to insert the item (the index of the new item).

label A string that indicates the label for the new item.

data The data for the item. This parameter is optional and can be of any type.

itemObject. An object to use as the item, usually containing label and data properties.

Returns

Nothing.

Description

Method; replaces the content of the item at the index specified by the index parameter.

Calling this method modifies the data provider of the List component. If the data provider is shared with other components, those components will update as well.

Example

The following example changes the fourth index position:

myList.replaceItemAt(3, "new label");


List.rowCount

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.rowCount

Description

Property; the number of rows that are at least partially visible in the list. This is useful if you've scaled a list by pixel and need to count its rows. Conversely, setting the number of rows guarantees an exact number of rows will be displayed, without a partial row at the bottom.

The code myList.rowCount = num is equivalent to the code myList.setSize(myList.width, h) (where h is the height required to display num items).

The default value is based on the height of the list as set while authoring, or set by the list.setSize() method (see UIObject.setSize()).

Example

The following example discovers the number of visible items in a list:

var rowCount = myList.rowCount;

The following example makes the list display four items:

myList.rowCount = 4;

This example removes a partial row at the bottom of a list, if there is one:

myList.rowCount = myList.rowCount;

This example sets a list to the smallest number of rows it can fully display:

myList.rowCount = 1;
trace("myList has "+myList.rowCount+" rows");


List.rowHeight

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.rowHeight

Description

Property; the height, in pixels, of every row in the list. The font settings do not make the rows grow to fit, so setting the rowHeight property is the best way to make sure items are fully displayed. The default value is 20.

Example

The following example sets each row to 30 pixels:

myList.rowHeight = 30;


List.scroll

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(scroll){
  // your code here
}

Usage 2:

listenerObject = new Object();
listenerObject.scroll = function(eventObject){
  // your code here
}
listInstance.addEventListener("scroll", listenerObject)

Event Object

Along with the standard event object properties, the scroll event has one additional property, direction. It is a string with two possible values "horizontal" or "vertical". For a ComboBox scroll event, the value is always "vertical".

Description

Event; broadcast to all registered listeners when a list scrolls.

The first usage example uses an on() handler and must be attached directly to a List component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the List instance myList, sends "_level0.myList" to the Output panel:

on(scroll){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (listInstance) dispatches an event (in this case, scroll) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example sends the instance name of the component that generated the change event to the Output panel:

form.scroll = function(eventObj){
  trace("list scrolled");
}
myList.addEventListener("scroll", form);


List.selectable

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.selectable

Description

Property; a Boolean value that indicates whether the list is selectable (true) or not (false). The default value is true.


List.selectedIndex

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.selectedIndex

Description

Property; the selected index of a single-selection list. The value is undefined if nothing is selected; the value is equal to the last item selected if there are multiple selections. If you assign a value to selectedIndex, any current selection is cleared and the indicated item is selected.

Example

This example selects the item after the currently selected item. If nothing is selected, item 0 is selected, as follows:

var selIndex = myList.selectedIndex;
myList.selectedIndex = (selIndex==undefined ? 0 : selIndex+1);

See also

List.selectedIndices, List.selectedItem, List.selectedItems


List.selectedIndices

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.selectedIndices

Description

Property; an array of indices of the selected items. Assigning this property replaces the current selection. Setting selectedIndices to a 0-length array (or undefined) clears the current selection. The value is undefined if nothing is selected.

The selectedIndices property is listed in the order that items were selected. If you click the second item, then the third item, and then the first item, selectedIndices returns [1,2,0].

Example

The following example gets the selected indices:

var selIndices = myList.selectedIndices;

The following example selects four items:

var myArray = new Array (1,4,5,7);
myList.selectedIndices = myArray;

See also

List.selectedIndex, List.selectedItem, List.selectedItems


List.selectedItem

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.selectedItem

Description

Property (read-only); an item object in a single-selection list. (In a multiple-selection list with multiple items selected, selectedItem returns the item that was most recently selected.) If there is no selection, the value is undefined.

Example

This example displays the selected label:

trace(myList.selectedItem.label);

See also

List.selectedIndex, List.selectedIndices, List.selectedItems


List.selectedItems

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.selectedItems

Description

Property (read-only); an array of the selected item objects. In a multiple-selection list, selectedItems allows you to access the set of items selected as item objects.

Example

The following example gets an array of selected item objects:

var myObjArray = myList.selectedItems;

See also

List.selectedIndex, List.selectedItem, List.selectedIndices


List.setPropertiesAt()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.setPropertiesAt(index, styleObj)

Parameters

index A number greater than zero or less than List.length indicating the index of the item to change.

styleObj An object that enumerates the properties and values to set.

Returns

Nothing.

Description

Method; applies the properties specified by the styleObj parameter to the item specified by the index parameter. The supported properties are icon and backgroundColor.

Example

The following example changes the fourth item to black and gives it an icon:

myList.setPropertiesAt(3, {backgroundColor:0x000000, icon: "file"});


List.sortItems()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.sortItems(compareFunc)

Parameters

compareFunc A reference to a function. This function is used to compare two items to determine their sort order.

For more information, see Array.sort().

Returns

The index at which the item was added.

Description

Method; sorts the items in the list according to the compareFunc parameter.

Example

The following example sorts the items based on uppercase labels. Note that the a and b parameters that are passed to the function are items that have label and data properties:

myList.sortItems(upperCaseFunc);
function upperCaseFunc(a,b){
    return a.label.toUpperCase() > b.label.toUpperCase();
}

See also

List.sortItemsBy()


List.sortItemsBy()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.sortItemsBy(fieldName, order)

Parameters

fieldName A string that specifies the name of the property to be used for sorting. Typically, this value is "label" or "data".

order A string that specifies whether to sort the items in ascending order ("ASC") or descending order ("DESC").

Returns

Nothing.

Description

Method; sorts the items in the list alphabetically or numerically, in the specified order, using the fieldName specified. If the fieldName items are a combination of text strings and integers, the integer items are listed first. The fieldName parameter is usually "label" or "data", but you can specify any primitive data value.

Example

The following code sorts the items in the list surnameMenu in ascending order using the labels of the list items:

surnameMenu.sortItemsBy("label", "ASC");

See also

List.sortItems()


List.vPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.vPosition

Description

Property; scrolls the list so that index is the topmost visible item. If index is out of bounds, goes to the nearest in-bounds index. The default value is 0.

Example

The following example sets the position of the list to the first index item:

myList.vPosition = 0;


List.vScrollPolicy

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listInstance.vScrollPolicy

Description

Property; a string that determines whether or not the list supports vertical scrolling. This property can be one of the following values: "on", "off" or "auto". The value "auto" causes a scroll bar to appear when its needed.

Example

The following example disables the scroll bar:

myList.vScrollPolicy = "off";

You can still create scrolling by using List.vPosition.

See also

List.vPosition


About the Loader component

The Loader component is a container that can display a SWF or a JPEG. You can scale the contents of the loader, or resize the loader itself to accommodate the size of the contents. By default, the contents are scaled to fit the Loader. You can also load content at runtime, and monitor loading progress.

A Loader component can't receive focus. However, content loaded into the Loader component can accept focus and have its own focus interactions. For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each Loader instance reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring.

Content that is loaded into a Loader component may be enabled for accessibility. If so, you can use the Accessibility panel to make it accessible to screen readers. For more information, see Creating Accessible Content.See also:

  • Using the Loader component
  • Customizing the Loader component
  • Loader class


Using the Loader component

You can use a loader whenever you need to grab content from a remote location and pull it into a Flash application. For example, you could use a loader to add a company logo (JPEG file) to a form. You could also use a loader to leverage Flash work that has already been completed. For example, if you had already built a Flash application and wanted to expand it, you could use the loader to pull the old application into a new application, perhaps as a section of a tab interface. In another example, you could use the loader component in an application that displays photos. Use Loader.load(), Loader.percentLoaded, and Loader.complete to control the timing of the image loads and display progress bars to the user during loading.

See also:

  • Loader component parameters
  • Creating an application with the Loader component

Loader component parameters

The following are authoring parameters that you can set for each Loader component instance in the Property inspector or in the Component Inspector panel:

autoload indicates whether the content should load automatically (true), or wait to load until the Loader.load() method is called (false). The default value is true.

contentPath an absolute or relative URL indicating the file to load into the loader. A relative path must be relative to the SWF file loading the content. The URL must be in the same subdomain as the URL where the Flash content currently resides. For use in Flash Player or for testing in test-movie mode, all SWF files must be stored in the same folder, and the filenames cannot include folder or disk drive specifications. The default value is undefined until the load had started.

scaleContent indicates whether the content scales to fit the Loader (true), or the Loader scales to fit the content (false). The default value is true.

You can write ActionScript to set additional options for Loader instances using its methods, properties, and events. For more information, see Loader class.

Creating an application with the Loader component

The following procedure explains how to add a Loader component to an application while authoring. In this example, the loader loads a logo JPEG from an imaginary URL.

To create an application with the Loader component, do the following:

  1. Drag a Loader component from the Components panel to the Stage.
  2. Select the loader on the Stage and use the Free Transform tool to size it to the dimensions of the corporate logo.
  3. In the Property inspector, enter the instance name logo.
  4. Select the loader on the Stage and in the Component Inspector panel and enter http://corp.com/websites/logo/corplogo.jpg for the contentPath parameter.


Customizing the Loader component

You can transform a Loader component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()).

The sizing behavior of the Loader component is controlled by the scaleContent property. When scaleContent = true, the content is scaled to fit within the bounds of the loader (and is rescaled when UIObject.setSize() is called). When the property is scaleContent = false, the size of the component is fixed to the size of the content and the UIObject.setSize() method has no effect.

See also:

  • Using styles with the Loader component
  • Using skins with the Loader component

Using styles with the Loader component

The Loader component doesn't use styles.

Using skins with the Loader component

The Loader component uses RectBorder which uses the ActionScript Drawing API. You can use the setStyle() method (see UIObject.setStyle()) to change the following RectBorder style properties:

RectBorder styles | Letter
borderColor | a
highlightColor | b
borderColor | c
shadowColor | d
borderCapColor | e
shadowCapColor | f
shadowCapColor | g
borderCapColor | h

The style properties set the following positions on the border:


Loader class

Inheritance UIObject > UIComponent > View > Loader

ActionScript Class Name mx.controls.Loader

The properties of the Loader class allow you to set content to load and monitor its loading progress at runtime.

Setting a property of the Loader class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

For more information, see Creating custom focus navigation.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.Loader.version);

Note: The following code returns undefined: trace(myLoaderInstance.version);.

Method summary for the Loader class

Method | Description
Loader.load() | Loads the content specified by the contentPath property.

Inherits all methods from UIObject and UIComponent.

Property summary for the Loader class

Property | Description
Loader.autoLoad | A Boolean value that indicates whether the content loads automatically (true) or if you must call Loader.load() (false).
Loader.bytesLoaded | A read-only property that indicates the number of bytes that have been loaded.
Loader.bytesTotal | A read-only property that indicates the total number of bytes in the content.
Loader.content | A reference to the content specified by the Loader.contentPath property. This property is read-only.
Loader.contentPath | A string that indicates the URL of the content to be loaded.
Loader.percentLoaded | A number that indicates the percentage of loaded content. This property is read-only.
Loader.scaleContent | A Boolean value that indicates whether the content scales to fit the Loader (true), or the Loader scales to fit the content (false).

Inherits all properties from UIObject and UIComponent.

Event summary for the Loader class

Event | Description
Loader.complete | Triggered when the content finished loading.
Loader.progress | Triggered while content is loading.

Inherits all properties from UIObject and UIComponent


Loader.autoLoad

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

loaderInstance.autoLoad

Description

Property; a Boolean value that indicates whether to automatically load the content (true), or wait until Loader.load() is called (false). The default value is true.

Example

The following code sets up the loader component to wait for a Loader.load() call:

loader.autoload = false;


Loader.bytesLoaded

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

loaderInstance.bytesLoaded

Description

Property (read-only); the number of bytes of content that have been loaded. The default value is 0 until content begins loading.

Example

The following code creates a ProgressBar and a Loader component. It then creates a listener object with a progress event handler that shows the progress of the load. The listener is registered with the loader instance, as follows:

createClassObject(mx.controls.ProgressBar, "pBar", 0);
createClassObject(mx.controls.Loader, "loader", 1);
loadListener = new Object();
loadListener.progress = function(eventObj){
  // eventObj.target is the component which generated the change event,
  // i.e., the Loader.
  pBar.setProgress(loader.bytesLoaded, loader.bytesTotal); // show progress
}
loader.addEventListener("progress", loadListener);
loader.content = "logo.swf";

When you create an instance with the createClassObject() method, you have to position it on Stage with the move() and setSize() methods. See UIObject.move() and UIObject.setSize().

See also

Loader.bytesTotal, UIObject.createClassObject()


Loader.bytesTotal

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

loaderInstance.bytesTotal

Description

Property (read-only); the size of the content in bytes. The default value is 0 until content begins loading.

Example

The following code creates a ProgressBar and a Loader component. It then creates a load listener object with a progress event handler that shows the progress of the load. The listener is registered with the loader instance, as follows:

createClassObject(mx.controls.ProgressBar, "pBar", 0);
createClassObject(mx.controls.Loader, "loader", 1);
loadListener = new Object();
loadListener.progress = function(eventObj){
  // eventObj.target is the component which generated the change event,
  // i.e., the Loader.
  pBar.setProgress(loader.bytesLoaded, loader.bytesTotal); // show progress
}
loader.addEventListener("progress", loadListener);
loader.content = "logo.swf";

See also

Loader.bytesLoaded


Loader.complete

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(complete){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.complete = function(eventObject){
  ...
}
loaderInstance.addEventListener("complete", listenerObject)

Description

Event; broadcast to all registered listeners when the content has finished loading.

The first usage example uses an on() handler and must be attached directly to a Loader component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the Loader component instance myLoaderComponent, sends "_level0.myLoaderComponent" to the Output panel:

on(complete){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (loaderInstance) dispatches an event (in this case, complete) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example creates a Loader component and then defines a listener object with a complete event handler that sets the loader's visible property to true:

createClassObject(mx.controls.Loader, "loader", 0);
loadListener = new Object();
loadListener.complete = function(eventObj){
  loader.visible = true;
}
loader.addEventListener("complete", loadListener);S
loader.contentPath = "logo.swf";


Loader.content

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

loaderInstance.content

Description

Property (read-only); a reference to the content of the loader. The value is undefined until the load begins.

See also

Loader.contentPath


Loader.contentPath

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

loaderInstance.contentPath

Description

Property; a string that indicates an absolute or relative URL of the file to load into the loader. A relative path must be relative to the SWF file that loads the content. The URL must be in the same subdomain as the URL as the loading SWF file.

If you are using Flash Player or test-movie mode in Flash, all SWF files must be stored in the same folder, and the filenames cannot include folder or disk drive information.

Example

The following example tells the loader instance to display the contents of the "logo.swf" file:

loader.contentPath = "logo.swf";


Loader.load()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

loaderInstance.load(path)

Parameters

path An optional parameter that specifies the value for the contentPath property before the load begins. If a value is not specified, the current value of contentPath is used as is.

Returns

Nothing.

Description

Method; tells the loader to begin loading its content.

Example

The following code creates a Loader instance and sets the autoload property to false so that the loader must wait for a call for the load() method to begin loading content. It then calls load() and indicates the content to load:

createClassObject(mx.controls.Loader, "loader", 0);
loader.autoload = false;
loader.load("logo.swf");


Loader.percentLoaded

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

loaderInstance.percentLoaded

Description

Property (read-only); a number indicating what percent of the content has loaded. Typically, this property is used to present the progress to the user in a easily readable form. Use the following code to round the figure to the nearest integer:

Math.round(bytesLoaded/bytesTotal*100))

Example

The following example creates a Loader instance and then creates a listener object with a progress handler that traces the percent loaded and sends it to the Output panel:

createClassObject(Loader, "loader", 0);
loadListener = new Object();
loadListener.progress = function(eventObj){
  // eventObj.target is the component which generated the change event,
  // i.e., the Loader.
  trace("logo.swf is " + loader.percentLoaded + "% loaded."); // track loading progress
}
loader.addEventListener("complete", loadListener);
loader.content = "logo.swf";


Loader.progress

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(progress){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.progress = function(eventObject){
  ...
}
loaderInstance.addEventListener("progress", listenerObject)

Description

Event; broadcast to all registered listeners while content is loading. This event is triggered when the load is triggered by the autoload parameter or by a call to Loader.load(). The progress event is not always broadcast. The complete event may be broadcast without any progress events being dispatched. This can happen especially if the loaded content is a local file.

The first usage example uses an on() handler and must be attached directly to a Loader component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the Loader component instance myLoaderComponent, sends "_level0.myLoaderComponent" to the Output panel:

on(progress){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (loaderInstance) dispatches an event (in this case, progress) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following code creates a Loader instance and then creates a listener object with an event handler for the progress event that sends a message to the Output panel about what percent of the content has loaded:

createClassObject(mx.controls.Loader, "loader", 0);
loadListener = new Object();
loadListener.progress = function(eventObj){
  // eventObj.target is the component which generated the change event,
  // i.e., the Loader.
  trace("logo.swf is " + loader.percentLoaded + "% loaded."); // track loading progress
}
loader.addEventListener("progress", loadListener);
loader.contentPath = "logo.swf";


Loader.scaleContent

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

loaderInstance.scaleContent

Description

Property; indicates whether the content scales to fit the Loader (true), or the Loader scales to fit the content (false). The default value is true.

Example

The following code tells the Loader to resize itself to match the size of its content:

loader.strechContent = false;


About media components (Flash Professional only)

The streaming media components make it easy to incorporate streaming media into Flash presentations. These components allow you to present your media in a variety of ways.

The following are the three media components available to you:

  • The MediaDisplay component allows media to be streamed into your Flash content without a supporting user interface. This component can be used with video and audio data. The user of your application will have no control over the media when the MediaDisplay component is used by itself.
  • The MediaController component complements the MediaDisplay component by providing a user interface that controls media playback using standard controls (play, pause, and so on). Media is never loaded into or played by the MediaController; it is used only for controlling playback in a MediaPlayback or MediaDisplay instance. The MediaController component features a "drawer," which exposes the contents of the playback controls when the mouse is positioned over the component.
  • The MediaPlayback component is a combination of the MediaDisplay and MediaController components; it provides methods to stream your media content.

Bear in mind these points about media components:

  • The media components require Flash Player 7 or later.
  • Scan forward and scan backward functionality is not supported by the media components. However, you can achieve this functionality by moving the playback slider.
  • Only component size and controller policy are reflected in Live Preview.
  • The media components do not support accessibility.

See also:

  • Interacting with media components (Flash Professional only)
  • Understanding media components (Flash Professional only)
  • Using media components (Flash Professional only)
  • Media component parameters (Flash Professional only)
  • Creating applications with media components (Flash Professional only)
  • Customizing media components (Flash Professional only)
  • Media class (Flash Professional only)


Interacting with media components (Flash Professional only)

The streaming MediaPlayback and MediaController components respond to both mouse and keyboard activity. The MediaDisplay component does not respond to keyboard or mouse events. The following table summarizes the actions for the MediaPlayback and MediaController components upon receiving focus:.

Target

Navigation

Description

Playback controls of a given controller

Mouse over

Button is highlighted.

Playback controls of a given controller

Single click of left mouse button

Users can manipulate the playback of audio and video media through the playback controls for a given controller by clicking the playback controls to trigger their corresponding effects.

The Pause/Play and Go to Beginning/Go to End buttons follow the standard button behaviors. When the mouse button is pressed, the onscreen button highlights in its pressed state, and when the mouse button is released, the onscreen button reverts to its unselected appearance.

The Go to End button is disabled when FLV media files are playing.

Slider controls of a given controller

Move slider back and forth

The playback slider indicates the user's position within the media content; the display handle moves horizontally (by default) to indicate the playback from beginning (left) to end (right). The playback slider moves from bottom to top when the controls are oriented vertically. As the indicator handle moves from left to right, it highlights the previous display space to indicate that this content has been played back or selected. Display space ahead of the indicator handle remains unhighlighted until the indicator passes. Users can drag the indicator handle to affect the media content's playback position. Media begins automatic playback from the point at which the mouse is released if media is playing. If the media is paused, the slider can be moved and released and the media will remain paused.

There is also a volume slider, which can be moved from left (muted) to right (maximum volume) in both the horizontal and vertical layouts.

Playback controller navigation

Tab, Shift+Tab

Moves the focus from button to button within the controller component, where the focused element will become highlighted. This navigation works with the Pause/Play, Go to Beginning, Go to End, Volume Mute, and Volume Max controls. The focus moves from left to right and top to bottom as users tab through the elements. Shift+Tab moves focus from right to left and bottom to top. Upon receiving focus via the Tab key, the control immediately passes focus to the Play/Pause button. When focus is on the Volume Max button, and then Tab is pressed, the control provides focus to the next control in the tab index on the Stage.

A given control button

Space or Enter/Return

Selects the element in focus. On press, the button appears in its pressed state. On release, the button reverts back to its focused, mouse-over state.


Understanding media components (Flash Professional only)

Before you start using media components, it is a good idea to understand how they work. This section provides an overview of how the media components work. Most of the properties listed in this section can be directly set with the Component Inspector panel. See Using the Component Inspector panel with media components.

Apart from the layout properties discussed later in this section, the following properties can be set for the MediaDisplay and MediaPlayback components:

  • The media type, which can be set to MP3 or FLV (see Media.mediaType and Media.setMedia()).
  • The relative or absolute content path, which holds the media file to be streamed (see Media.contentPath).
  • Cue point objects, along with their name, time, and player properties (see Media.addCuePoint() and Media.cuePoints). The name of the cue point is arbitrary and should be set such that its name has meaning when using listener and trace events. A cue point broadcasts a cuePoint event when the value of its time property is equal to that of the playhead location of the MediaPlayback or MediaDisplay component with which it is associated. The player property is a reference to the MediaPlayback instance with which it is associated. Cue points can be subsequently removed by means of Media.removeCuePoint() and Media.removeAllCuePoints().

The streaming media components broadcast a number of related events. The following broadcast events can be used to set other items in motion:

  • A change event is broadcast continuously by the MediaDisplay and MediaPlayback components while media is playing. (See Media.change.)
  • A progress event is continuously broadcast by the MediaDisplay and MediaPlayback components while media is loading. (See Media.progress.)
  • A click event is broadcast by the MediaController and MediaPlayback components whenever the Pause/Play button is clicked. In this case, the detail property of the event object provides information on which button was clicked. (See Media.click.)
  • A volume event is broadcast by the MediaController and MediaPlayback components when the volume controls are adjusted by the user. (See Media.volume.)
  • A playheadChange event is broadcast by the MediaController and MediaPlayback components when the playback slider is moved by the user. (See Media.playheadChange.)

The MediaDisplay component works in conjunction with the MediaController component. Combined, the components behave in a manner similar to the MediaPlayback component, yet allow more flexibility with respect to layout. Therefore, if you require a flexible look and feel when presenting your media, use the MediaDisplay and MediaController components. Otherwise, the MediaPlayback component is the best choice.

See also:

  • Understanding the MediaDisplay component
  • Understanding the MediaController component
  • Understanding the MediaPlayback component

Understanding the MediaDisplay component

When you place a MediaDisplay component on the Stage, it is drawn with no visible user interface. It is simply a container to hold and play media. The appearance of any video media playing in a MediaDisplay component is affected by the following properties:

  • Media.aspectRatio
  • Media.autoSize
  • Height
  • Width

Note: The user will not be able to see anything unless some media is playing.

The Media.aspectRatio property takes precedence over the other properties. When Media.aspectRatio is set to true (the default), the component will always readjust the size of the playing media after the component size has been set to ensure that the aspect ratio of the media is maintained.

For FLV files, when Media.autoSize is set to true, the media to be played will be displayed at its preferred size, regardless of the size of the component. This implies that, unless the MediaDisplay instance size is the same as the size of the media, the media will either spill out of the instance boundaries or not fill the instance size. When Media.autoSize is set to false, the instance size will be used as much as possible, while honoring the aspect ratio. If both Media.autoSize and Media.aspectRatio are set to false, the exact size of the component will be used.

Note: Since there is no image to show with MP3 files, setting Media.autoSize would have no effect. For MP3 files, the minimum usable size is 60 pixels high by 256 pixels wide in the default orientation.

The MediaDisplay component also supports the Media.volume property. This property takes on integer values from 0 to 100, with 0 being mute and 100 being the maximum volume. The default setting is 75.

Understanding the MediaController component

The interface for the MediaController component depends on its Media.controllerPolicy and Media.backgroundStyle properties. The Media.controllerPolicy property determines if the media control set is always visible, collapsed, or only visible when the mouse is hovering over the control portion of the component. When collapsed, the controller draws a modified progress bar, which is a combination of the loadbar and the playbar. It shows the progress of the bytes being loaded at the bottom of the bar, and the progress of the playhead just above it. The expanded state draws an enhanced version of the playbar/loadbar, which contains the following items:

  • Text labels on the left that indicate the playback state (streaming or paused), and on the right that indicate playhead location in seconds
  • Playhead location indicator
  • A slider, which users can drag to navigate around the media

The following items are also provided with the MediaController component:

  • A Play/Pause state button
  • A group of two buttons: Go to Beginning and Go to End, which navigate to the beginning and end of the media, respectively
  • A volume control that consists of a slider, a mute, and a maximum volume button

Both the collapsed and expanded states of the MediaController component use the Media.backgroundStyle property. This property determines whether the controller draws a chrome background (the default) or allows the movie background to display from behind the controls.

The MediaController component has an orientation setting, Media.horizontal, which can be used to draw the component with a horizontal orientation (the default) or a vertical one. With a horizontal orientation, the playbar tracks playing media from left to right. With a vertical orientation, the playbar tracks the media from bottom to top.

The MediaDisplay and MediaController components can be associated with each other through the Media.associateDisplay() and Media.associateController() methods. When called, these methods allow the MediaController instance to update its controls based on events broadcast from the MediaDisplay instance, and allow the MediaDisplay component to react to the setting made by the user from the MediaController.

Understanding the MediaPlayback component

The MediaPlayback component is a combination of the MediaController and MediaDisplay controls. Both subcomponents are contained within MediaPlayback. The MediaController and MediaDisplay portions always scale to fit the size of the overall MediaPlayback component instance.

The MediaPlayback component uses Media.controlPlacement to determine the layout of the controls. Possible control placement include top, bottom, left, and right, indicating where the controls will be drawn in relation to the display. For example, a value of right would give a control a vertical orientation and position it on the right of the display.


Using media components (Flash Professional only)

With the sharp increase in the use of media to provide information to web users, there is generally a desire to provide users a method to stream the media and then control it. The following are example usage scenarios for media components:

  • Showing media that introduces a company
  • Streaming movies or movie previews
  • Streaming songs or song snippets
  • Providing learning material in the form of media

See also:

  • Using the MediaPlayback component
  • Using the MediaDisplay and MediaController components
  • Using the Component Inspector panel with media components
  • Controlling media components by using behaviors

Using the MediaPlayback component

Suppose you must develop a website for your clients that allows website users to preview DVDs and CDs that you sell in a rich media environment. The example below shows the steps to accomplish this and assumes your website is ready for inserting streaming components.

To create a Flash document that displays a CD or DVD preview:

  1. In Flash, select File > New; then select Flash Document.
  2. Open the Components panel (Window > Development Panels > Components) and double-click the MediaPlayback component, which places an instance of the component on the Stage.
  3. Select the MediaPlayback component instance and enter the instance name myMedia in the Property inspector.
  4. In the Component Inspector panel (Window > Development Panels > Component Inspector), set your media type according to the type of media that will be streaming (MP3 or FLV).
  5. If you selected FLV, enter the duration of the video in the Video Length text boxes; use the format HH:MM:SS.
  6. Enter the location of your preview video in the URL text box. For example, you might enter http://my.web.com/videopreviews/AMovieName.flv.
  7. Set the desired options for the Automatically Play, Use Preferred Media Size, and Respect Aspect Ratio check boxes.
  8. Set the control placement to the desired side of the MediaPlayback component.
  9. Add a cue point toward the end of the media that will be used in conjunction with a listener to open a pop-up window that informs the user that the movie is on sale. Give the cue point the name cuePointName and set the cue point time such that it is toward the end of the clip (within a few seconds). To accomplish this, take the following steps:
    1. Double-click a Window component to make it appear on the Stage.
    2. Delete the Window component. This places an item called Window in your library.
    3. Create a text box and write some text informing the user that the movie is on sale.
    4. Convert this text box to a movie clip by selecting Modify > Convert to Symbol, and give it the name mySale_mc.
    5. Right-click the mySale_mc movie clip in the library, select Linkage, and select the Export for ActionScript option. This places the movie clip in your runtime library.
  10. Add the following ActionScript to Frame 1. This code creates a listener to open a pop-up window informing the user that the movie is on sale.
    // Import the classes necessary to create the pop-up window dynamically

import mx.containers.Window;
import mx.managers.PopUpManager;

// Create a listener object to fire off sale pop-up
var saleListener = new Object();

saleListener.cuePoint = function(evt){

var saleWin = PopUpManager.createPopUp(_root, Window, false, {closeButton: true, title: "Movie Sale ", contentPath: "mySale_mc"});

// Enlarge the window so that the content fits

saleWin.setSize(80, 80);
var delSaleWin = new Object();
delSaleWin.click = function(evt){
saleWin.deletePopUp();
}
saleWin.addEventListener("click", delSaleWin);

}

myMedia.addEventListener("cuePoint", saleListener);

Using the MediaDisplay and MediaController components

Suppose you decide that you want more control over the look and feel of your media display. For this reason, you need to use the MediaDisplay and MediaController together to provide the desired experience. The following example shows the equivalent steps from the previous example that will create a Flash application that displays your CD and DVD preview media.

To create a Flash document that displays a CD or DVD preview:

  1. In Flash, select File > New; then select Flash Document.
  2. In the Components panel (Window > Development Panels > Components), double-click the MediaController and MediaDisplay components, which places an instance of each component on the Stage.
  3. Select the MediaDisplay instance and enter the instance name myDisplay in the Property inspector.
  4. Select the MediaController instance and enter the instance name myController in the Property inspector.
  5. Launch the Component Inspector panel from the Property inspector and set your media type according to the type of media that will be streaming (MP3 or FLV).
  6. If you selected FLV, enter the duration of the video in the Video Length text boxes in using the format HH:MM:SS.
  7. Enter the location of your preview video in the URL text box. For example, you might enter http://my.web.com/videopreviews/AMovieName.flv.
  8. Set the desired options for the Automatically Play, Use Preferred Media Size, and Respect Aspect Ratio check boxes.
  9. Select the MediaController instance and, in the Component Inspector panel, set your orientation to vertical by setting the horizontal property to false.
  10. In the Component Inspector panel, set backgroundStyle to None.

    This specifies that the MediaController instance should not draw a background but should instead fill the media between the controls.

  11. Use a behavior to associate the MediaController and MediaDisplay instances so that the MediaController instance accurately reflects the playhead movement and other settings in the MediaDisplay instance, and so that the MediaDisplay instance responds to user clicks:
    1. Select the MediaDisplay instance and, in the Property inspector, enter the instance name myMediaDisplay.
    2. Select the MediaController instance that will trigger the behavior.
    3. In the Behaviors panel (Window > Development Panels > Behaviors), click the Add (+) button and select Media > Associate Display.
    4. In the Associate Display window, select myMediaDisplay under _root and click OK.

For more information on using behaviors with media components, see Controlling media components by using behaviors.

Using the Component Inspector panel with media components

The Component Inspector panel makes it easy to set media component parameters, properties, and so on. To use this panel, click the desired component on the Stage and, with the Property inspector open, click Launch Component Inspector. The Component Inspector panel can be used for the following purposes:

  • To automatically play the media (see Media.activePlayControl and Media.autoPlay)
  • To keep or ignore the media's aspect ratio (see Media.aspectRatio)
  • To determine if the media will be automatically sized to fit the component instance (see Media.autoSize)
  • To enable or disable the chrome background (see Media.backgroundStyle)
  • To specify the path to your media in the form of a URL (see Media.contentPath)
  • To specify the visibility of the playback controls (see Media.controllerPolicy)
  • To add cue point objects (see Media.addCuePoint())
  • To delete cue point objects (see Media.removeCuePoint())
  • To set the orientation of MediaController instances (see Media.horizontal)
  • To set the type of media being played (see Media.setMedia())
  • To set the play time of the FLV media (see Media.totalTime)
  • To set the last few digits of the time display to indicate milliseconds or frames per second (fps)

It is important to understand a few concepts when working with the Component Inspector panel:

  • The video time control is removed when an MP3 video type is selected, because this information is automatically read in when MP3 files are used. For FLV files, you must input the total time of the media (Media.totalTime) in order for the playbar of the MediaPlayback component (or any listening MediaController component) to accurately reflect play progress.
  • With the file type set to FLV, you'll notice a Milliseconds option and (if Milliseconds is unselected) a Frames Per Second (FPS) pop-up menu. When the Milliseconds option is selected, the FPS control is not visible. In this mode, the time displayed in the playbar at runtime is formatted as HH:MM:SS.mmm (H = hours, M = minutes, S = seconds, m = milliseconds), and cue points are set in seconds. When Milliseconds is unselected, the FPS control is enabled and the playbar time is formatted as HH:MM:SS.FF (F = frames per second), while cue points are set in frames.

    Note: You can only set the FPS property by using the Component Inspector panel. Setting an fps value by using ActionScript has no effect and will be ignored.

Controlling media components by using behaviors

Behaviors are prewritten ActionScript scripts that you add to an object instance, such as a MediaDisplay component, to control that object. Behaviors allow you to add the power, control, and flexibility of ActionScript coding to your document without having to create the ActionScript code yourself.

To control a media component with a behavior, you use the Behaviors panel to apply the behavior to a given media component instance. You specify the event that will trigger the behavior (such as reaching a specified cue point), select a target object (the media components that will be affected by the behavior), and, if necessary, select settings for the behavior (such as the movie clip within the media to navigate to).

The following behaviors are packaged with Flash MX Professional 2004 and are used to control embedded media components.

Behavior | Purpose | Parameters
Associate Controller | Associates a MediaController component with a MediaDisplay component | Instance name of target MediaController components
Associate Display | Associates a MediaDisplay component with a MediaController component | Instance name of target MediaController components
Labeled Frame CuePoint Navigation | Places an action on a MediaDisplay or MediaPlayback instance that tells an indicated movie clip to navigate to a frame with the same name as a given cue point | Name of frame and name of cue point (the names should be equal)
Slide CuePoint Navigation | Makes a slide-based Flash document navigate to a slide with the same name as a given cue point | Name of slide and name of cue point (the names should be equal)

To associate a MediaDisplay component with a MediaController component:

  1. Place a MediaDisplay instance and a MediaController instance on the Stage.
  2. Select the MediaDisplay instance and, using the Property inspector, enter the instance name myMediaDisplay.
  3. Select the MediaController instance that will trigger the behavior.
  4. In the Behaviors panel (Window > Development Panels > Behaviors), click the Add (+) button and select Media > Associate Display.
  5. In the Associate Display window, select myMediaDisplay under _root and click OK.

Note: If you have associated the MediaDisplay component to the MediaController component, you do not need to associate the MediaController component to the MediaDisplay component.

To associate a MediaController component with a MediaDisplay component:

  1. Place a MediaDisplay instance and a MediaController instance on the Stage.
  2. Select the MediaController instance and, using the Property inspector, enter the instance name myMediaController.
  3. Select the MediaDisplay instance that will trigger the behavior.
  4. In the Behaviors panel (Window > Development Panels > Behaviors), click the Add (+) button and select Media > Associate Controller.
  5. In the Associate Controller window, select myMediaController under _root and click OK.

To use a Labeled Frame CuePoint Navigation behavior:

  1. Place a MediaDisplay or MediaPlayback component instance on the Stage.
  2. Select the desired frame that you want the media to navigate to and, using the Property inspector, enter the frame name myLabeledFrame.
  3. Select your MediaDisplay or MediaPlayback instance.
  4. In the Component Inspector panel, click the Add (+) button and enter the cue point time in the format HH:MM:SS:mmm or HH:MM:SS:FF, and give the cue point the name myLabeledFrame.

    The cue point indicates the amount of time that should elapse before you navigate to the selected frame. For example, if you want to jump to myLabeledFrame 5 seconds into the movie, enter 5 in the SS text box and enter myLabeledFrame in the Name text box.

  5. In the Behaviors panel (Window > Development Panels > Behaviors), click the Add (+) button and select Media > Labeled Frame CuePoint Navigation.
  6. In the Labeled Frame CuePoint Navigation window, select the _root clip and click OK.

To use a Slide CuePoint Navigation behavior:

  1. Open your new document as a Flash slide presentation.
  2. Place a MediaDisplay or MediaPlayback component instance on the Stage.
  3. In the Screen Outline pane to the left of the Stage, click the Insert Screen (+) button to add a second slide; then select the second slide and rename it mySlide.
  4. Select your MediaDisplay or MediaController instance.
  5. In the Component Inspector panel, click the Add (+) button and enter the cue point time in the format HH:MM:SS:mmm or HH:MM:SS:FF, and give the cue point the name MySlide.

    The cue point indicates the amount of time that should elapse before you navigate to the selected slide. For example, if you want to jump to mySlide 5 seconds into the movie, enter 5 in the SS text box and enter mySlide in the Name text box.

  6. In the Behaviors panel (Window > Development Panels > Behaviors), click the Add (+) button and select Media > Slide CuePoint Navigation.
  7. In the Slide CuePoint Navigation window, select Presentation under the _root clip and click OK.


Media component parameters (Flash Professional only)

The following tables list authoring parameters that you can set for a given media component instance in the Property inspector:

  • MediaDisplay component parameters
  • MediaController component parameters
  • MediaPlayback component parameters

MediaDisplay component parameters

Name | Type | Default value | Description
Automatically Play (Media.autoPlay) | Boolean | Selected | Determines if the media plays as soon as it has loaded.
Use Preferred Media Size (Media.autoSize) | Boolean | Selected | Determines whether the media associated with the MediaDisplay instance conforms to the component size or simply uses its default size.
FPS | Integer | 30 | Indicates the number of frames per second. When the Milliseconds option is selected, this control is disabled.
Cue Points (Media.cuePoints) | Array | Undefined | An array of cue point objects, each with a name and position in time in a valid HH:MM:SS:FF (Milliseconds option selected) or HH:MM:SS:mmm format.
FLV or MP3 (Media.mediaType) | "FLV" or "MP3" | "FLV" | Designates the type of media to be played.
Milliseconds | Boolean | Unselected | Determines whether the playbar uses frames or milliseconds, and whether the cue points use seconds or frames. When this option is selected, the FPS control is not visible.
URL (Media.contentPath) | String | Undefined | A string that holds the path and filename of the media to be played.
Video Length (Media.totalTime) | Integer | Undefined | The total time needed to play the FLV media. This setting is required in order for the playbar to work correctly. This control is only visible when the media type is set to FLV.

MediaController component parameters

Name | Type | Default value | Description
activePlayControl (Media.activePlayControl) | String: "pause" or "play" | "pause" | Determines whether the playbar is in play or pause mode upon instantiation.
backgroundStyle (Media.backgroundStyle) | string: "default"or "none" | "default" | Determines whether the chrome background will be drawn for the MediaController instance.
controllerPolicy (Media.controllerPolicy) | "auto", "on", or "off" | "auto" | Determines whether the controller opens or closes based on mouse position, or is locked in the open or closed state.
horizontal (Media.horizontal) | Boolean | true | Determines whether the controller portion of the instance is vertically or horizontally oriented. A true value indicates that the component will have a horizontal orientation.
enabled | Boolean | true | Determines whether this control can be modified by the user. A true value indicates that the control can be modified.
visible | Boolean | true | Determines whether this control is viewable by the user. A true value indicates that the control is viewable.
minHeight | Integer | 0 | Minimum height allowable for this instance, in pixels.
minWidth | Integer | 0 | Minimum width allowable for this instance, in pixels.

MediaPlayback component parameters

Name | Type | Default value | Description
Control Placement (Media.controlPlacement) | "top", "bottom", "left", "right" | "bottom" | Position of the controller. The value is related to orientation.
Media.controllerPolicy | Boolean | true | Determines whether the controller opens or closes based on mouse position.
Automatically Play (Media.autoPlay) | Boolean | Selected | Determines if the media plays as soon as it has loaded.
Use Preferred Media Size (Media.autoSize) | Boolean | Selected | Determines whether the MediaController instance sizes to fits the media or uses other settings.
FPS | Integer | 30 | Number of frames per second. When the Milliseconds option is selected, this control is disabled.
Cue Points (Media.cuePoints) | Array | Undefined | An array of cue point objects, each with a name and position in time in a valid HH:MM:SS:mmm (Milliseconds option selected) or HH:MM:SS:FF format.
FLV or MP3 (Media.mediaType) | "FLV" or "MP3" | "FLV" | Designates the type of media to be played.
Milliseconds | Boolean | Unselected | Determines whether the playbar uses frames or milliseconds, and whether the cue points use seconds or frames. When this option is selected, the FPS control is disabled.
URL (Media.contentPath) | String | Undefined | A string that holds the path and filename of the media to be played.
Video Length (Media.totalTime) | Integer | Undefined | The total time needed to play the FLV media. This setting is required in order for the playbar to work correctly.


Creating applications with media components (Flash Professional only)

Creating Flash content by using media components is quite simple and often requires only a few steps.

This example shows how to create an application to play a small, publicly available media file.

To add a media component to an application:

  1. In Flash, select File > New; then select Flash Document.
  2. In the Components panel (Window > Development Panels > Components), double-click the MediaPlayback component to add it to the Stage.
  3. In the Property inspector, enter the instance name myMedia.
  4. In the Property inspector, click Launch Component Inspector.
  5. In the Component Inspector panel, enter http://www.cathphoto.com/c.flv in the URL text box.
  6. Select Control > Test Movie to see the media play.


Customizing media components (Flash Professional only)

If you want to change the appearance of your media components, you can use skinning. For a complete guide to component customization, see Customizing Components.

See also:

  • Using styles with media components
  • Using skins with media components

Using styles with media components

Styles are not supported with media components.

Using skins with media components

The media components do not support dynamic skinning, although you can open the media components source document and change their assets to achieve the desired look. It is best to make a copy of this file and work from the copy, so that you will always have the installed source to go back to. You can find the media component source document at the following locations:

  • Windows: C:\Documents and Settings\user\Local Settings\Application Data\Macromedia\ Flash MX 2004\language\Configuration\ComponentFLA.fla
  • Macintosh: HD Drive:Users:Username:Library:Application Support:Macromedia:Flash MX 2004:language:Configuration:ComponentFLA.fla

For more information on component skins, see About skinning components.


Media class (Flash Professional only)

Inheritance mx.core.UIComponent

ActionScript Class Names mx.controls.MediaController, mx.controls.MediaDisplay, mx.controls.MediaPlayback

Each component class has a version property, which is a class property. Class properties are available only for the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.MediaPlayback.version);

Note: The code trace(myMediaInstance.version); returns undefined.

Method summary for the Media class

Method | Components | Description
Media.addCuePoint() | MediaDisplay, MediaPlayback | Adds a cue point object to the component instance.
Media.associateController() | MediaDisplay | Associates a MediaDisplay instance with a MediaController instance.
Media.associateDisplay() | MediaController | Associates a MediaController instance with a MediaDisplay instance.
Media.displayFull() | MediaPlayback | Converts the component instance to full-screen playback mode.
Media.displayNormal() | MediaPlayback | Converts the component instance back to its original screen size.
Media.getCuePoint() | MediaDisplay, MediaPlayback | Returns a cue point object.
Media.play() | MediaDisplay, MediaPlayback | Plays the media associated with the component instance at a given starting point.
Media.pause() | MediaDisplay, MediaPlayback | Pauses the playhead at its current location in the media Timeline.
Media.removeAllCuePoints() | MediaDisplay, MediaPlayback | Deletes all cue point objects associated with a given component instance.
Media.removeCuePoint() | MediaDisplay, MediaPlayback | Deletes a specified cue point associated with a given component instance.
Media.setMedia() | MediaDisplay, MediaPlayback | Sets the media type and path to the specified media type.
Media.stop() | MediaDisplay, MediaPlayback | Stops the playhead and moves it to position 0, which is the beginning of the media.

Property summary for the Media class

Property | Components | Description
Media.activePlayControl | MediaController | Determines the component state when loaded at runtime.
Media.aspectRatio | MediaDisplay, MediaPlayback | Determines if the component instance maintains its video aspect ratio.
Media.autoPlay | MediaDisplay, MediaPlayback | Determines if the component instance immediately starts to buffer and play.
Media.autoSize | MediaDisplay, MediaPlayback | Determines how the media-viewing portion of the MediaDisplay or MediaPlayback component sizes itself.
Media.backgroundStyle | MediaController | Determines if the component instance draws its chrome background.
Media.bytesLoaded | MediaDisplay, MediaPlayback | The number of bytes loaded that are available for playing.
Media.bytesTotal | MediaDisplay, MediaPlayback | The number of bytes to be loaded into the component instance.
Media.contentPath | MediaDisplay, MediaPlayback | A string that holds the relative path and filename of the media to be streamed and played.
Media.controllerPolicy | MediaController, MediaPlayback | Determines whether the controls within the component are hidden during playback and only shown when a mouse-over event is triggered, or whether the controls are visible or hidden at all times.
Media.controlPlacement | MediaPlayback | Determines where the controls for the component are positioned in relation to the component.
Media.cuePoints | MediaDisplay, MediaPlayback | An array of cue point objects that have been assigned to a given component instance.
Media.horizontal | MediaController | Determines the orientation of the component instance.
Media.mediaType | MediaDisplay, MediaPlayback | Determines the type of media to be played.
Media.playheadTime | MediaDisplay, MediaPlayback | Holds the current position of the playhead (in seconds) for the media Timeline that is playing.
Media.playing | MediaDisplay, MediaPlayback | Returns a Boolean value to indicate whether a given component instance is playing media.
Media.preferredHeight | MediaDisplay, MediaPlayback | The default value of the height of a FLV media file.
Media.preferredWidth | MediaDisplay, MediaPlayback | The default value of the width of a FLV media file.
Media.totalTime | MediaDisplay, MediaPlayback | An integer that indicates the total length of the media, in seconds.
Media.volume | MediaDisplay, MediaPlayback | An integer from 0 (minimum) to 100 (maximum) that represents the volume level.

Event summary for the Media class

Event | Components | Description
Media.change | MediaDisplay, MediaPlayback | Broadcast continuously while media is playing.
Media.click | MediaController, MediaPlayback | Broadcast when the user clicks the Play/Pause button.
Media.complete | MediaDisplay, MediaPlayback | Notification that the playhead has reached the end of the media.
Media.cuePoint | MediaDisplay, MediaPlayback | Notification that the playhead has reached a given cue point.
Media.playheadChange | MediaController, MediaPlayback | Broadcast by the component instance when a user moves the playback slider or clicks the Go to Beginning or Go to End button.
Media.progress | MediaDisplay, MediaPlayback | Is generated continuously until the media has downloaded completely.
Media.volume | MediaController, MediaPlayback | Broadcast when the user adjusts the volume.


Media.activePlayControl

Applies to

MediaController

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.activePlayControl

Description

Property; a Boolean value that determines what state the MediaController component is in when it is loaded at runtime. A true value indicates that the MediaController component should be in a play state at runtime, and a false value indicates that it is in a paused state at runtime. This property should be set in conjunction with the autoPlay property, such that both are either paused or playing at runtime. The default value is true.

Example

The following example indicates that the control will be paused when first loaded at runtime:

myMedia.activePlayControl = false;

See also

Media.autoPlay


Media.addCuePoint()

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.addCuePoint(cuePointName, cuePointTime)

Parameters

cuePointName A string that can be used to name the cue point.

cuePointTime A number, expressed in seconds, which indicates when a cuePoint event is broadcast.

Returns

Nothing.

Description

Method; adds a cue point object to a MediaPlayback or MediaDisplay component instance. When the playhead time equals a cue point time, a cuePoint event is broadcast.

Example

The following code adds a cue point called Homerun to myMedia at time = 16 seconds.

myMedia.addCuePoint("Homerun", 16);

See also

Media.cuePoint, Media.cuePoints, Media.getCuePoint(), Media.removeAllCuePoints(), Media.removeCuePoint()


Media.aspectRatio

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.aspectRatio

Description

Property; a Boolean value that determines whether a MediaDisplay or MediaPlayback instance maintains its video aspect ratio during playback. A true value indicates that the aspect ratio should be maintained; a false value indicates that the aspect ratio can change during playback. The default value is true.

Example

The following example indicates that the aspect ratio can change during playback:

myMedia.aspectRatio = false;


Media.associateController()

Applies to

MediaDisplay

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.associateController(instanceName)

Parameters

instanceName A string that indicates the instance name of the MediaController component to associate.

Returns

Nothing.

Description

Method; associates a MediaDisplay component instance with a given MediaController instance.

If you have associated a MediaController instance with a MediaDisplay instance by using Media.associateDisplay(), you do not need to use Media.associateController().

Example

The following code associates myMedia with myController:

myMedia.associateController(myController);

See also

Media.associateDisplay()


Media.associateDisplay()

Applies to

MediaController

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.associateDisplay(instanceName)

Parameters

instanceName A string that indicates the instance name of the MediaDisplay component to associate.

Returns

Nothing.

Description

Method; associates a MediaController component instance with a given MediaDisplay instance.

If you have associated a MediaDisplay instance with a MediaController instance by using Media.associateController(), you do not need to use Media.associateDisplay().

Example

The following code associates myMedia with myDisplay:

myMedia.associateDisplay(myDisplay);

See also

Media.associateController()


Media.autoPlay

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.autoPlay

Description

Property; a Boolean value that determines whether the MediaPlayback or MediaDisplay instance will immediately start attempting to buffer and play. A true value indicates that the control will buffer and play at runtime; a false value indicates the control will be stopped at runtime. This property depends on the contentPath and mediaType properties. If contentPath and mediaType are not set, no playback will occur at runtime. The default value is true.

Example

The following example indicates that the control will not be started when first loaded at runtime:

myMedia.autoPlay = false;

See also

Media.contentPath, Media.mediaType


Media.autoSize

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.autoSize

Description

Property; a Boolean value that determines how the media-viewing portion of the MediaDisplay or MediaPlayback component sizes itself.

For the MediaDisplay component, the property behaves as follows:

  • If you set this property to true, Flash will display the media at its preferred size, regardless of the size of the component. This implies that, unless the MediaDisplay instance size is the same as the size of the media, the media will either spill out of the instance boundaries or not fill the instance size.
  • If you set this property to false, Flash will use the instance size as much as possible, while honoring the aspect ratio. If both Media.autoSize and Media.aspectRatio are set to false, the exact size of the component will be used.

For the MediaPlayback component, the property behaves as follows:

  • If you set this property to true, Flash will display the media at its preferred size unless the playback media area is smaller than the preferred size. If this is the case, Flash will shrink the media to fit inside the instance and respect the aspect ratio. If the preferred size is smaller than the media area of the instance, part of the media area will go unused.
  • If you set this property to false, Flash will use the instance size as much as possible, while honoring the aspect ratio. If both Media.autoSize and Media.aspectRatio are set to false, the media area of the component will be filled. This area is defined as the area above the controls (in the default layout), with an 8-pixel margin around it that makes up the edges of the component.

The default value is true.

Example

The following example indicates that the control will not be played back according to its media size:

myMedia.autoSize = false;

See also

Media.aspectRatio


Media.backgroundStyle

Applies to

MediaController

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.backgroundStyle

Description

Property; a value of "default" indicates that the chrome background will be drawn for the MediaController instance, while a value of "none" indicates that no chrome background will be drawn. The default value is "default".

This is not a style property and therefore will not be affected by style settings.

Example

The following example indicates that the chrome background will not be drawn for the control:

myMedia.backgroundStyle = "none";


Media.bytesLoaded

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.bytesLoaded

Description

Read-only property; the number of bytes already loaded into the component that are available for playing. The default value is undefined.

Example

The following code creates a variable called PlaybackLoad that will be set with the number of bytes loaded in the for loop.

// create variable that holds how many bytes are loaded
var PlaybackLoad = myMedia.bytesLoaded;
// perform some function until playback ready
for (PlaybackLoad < 150) {
  someFunction();
}


Media.bytesTotal

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.bytesTotal

Description

Property; the number of bytes to be loaded into the MediaPlayback or MediaDisplay component. The default value is undefined.

Example

The following example tells the user the size of the media to be streamed:

myTextField.text = myMedia.bytesTotal;


Media.change

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.change = function(eventObject){
  // insert your code here
}
myMedia.addEventListener("change", listenerObject)

Description

Event; broadcast by the MediaDisplay and MediaPlayback components while the media is playing. The percentage complete can be retrieved from the component instance. See the example below.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The Media.change event's event object has two additional properties:

target A reference to the broadcasting object.

type The string "change", which indicates the type of event.

For more information about event objects, see Event Objects.

Example

The following example uses an object listener to determine the playhead position (Media.playheadTime), from which the percentage complete can be calculated:

var myPlayerListener = new Object();
myPlayerListener.change = function(eventObject){
  var myPosition = myPlayer.playheadTime;
  var myPercentPosition = (myPosition/totalTime);
}
myPlayer.addEventListener("change", myPlayerListener);

See also

Media.playing, Media.pause()


Media.click

Applies to

MediaController, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

var myMediaListener = new Object()
myMediaListener.click = function(){
  // insert your code here
}
myPlayer.addEventListener("click", myMediaListener);

Description

Event; broadcast when the user clicks the Play/Pause button. The detail field should be used to determine which button was clicked. The Media.click event object has the following properties:

detail The string "pause" or "play".

target A reference to the MediaController or MediaPlayback component instance.

type The string "click".

Example

The following example opens a pop-up window when the user clicks Play:

var myMediaListener = new Object()
myMediaListener.click = function(){
  PopUpManager.createPopup(_root, mx.containers.Window, false, {contentPath: movieSale});
}
myMedia.addEventListener("click", myMediaListener);


Media.complete

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.complete = function(eventObject){
  // insert your code here
}
myMedia.addEventListener("complete", listenerObject)

Description

Event; notification that the playhead has reached the end of the media. The Media.complete event object has the following properties:

target A reference to the MediaDisplay or MediaPlayback component instance.

type The string "complete".

Example

The following example uses an object listener to determine when the media has finished playing:

var myListener = new Object();
myListener.complete = function(eventObject) {
    trace("media is Finished");
};
myMedia.addEventListener("complete", myListener);


Media.contentPath

Applies to

MediaController

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.contentPath

Description

Property; a string that holds the relative path and filename of the media to be streamed and/or played. The Media.setMedia() method is the only supported way of setting this property through ActionScript. The default value is undefined.

Example

The following example displays the name of the movie playing in a text box:

myTextField.text = myMedia.contentPath;

See also

Media.setMedia()


Media.controllerPolicy

Applies to

MediaController, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.controllerPolicy

Description

Property; determines whether the MediaController component (or the controller subcomponent within the MediaPlayback component) is hidden when instantiated and only displays itself when the user moves the mouse over the controller's collapsed state.

The possible values for this property are as follows:

  • "on" indicates that the controls are always expanded.
  • "off" indicates that the controls are always collapsed.
  • "auto" indicates that the control will remain in the collapsed state until the user mouses over the hit area. The hit area matches the area in which the collapsed control is drawn. The control remains expanded until the mouse leaves the hit area.

Note: The hit area expands and contracts with the controller.

Example

The following example will keep the controller open at all times:

myMedia.controllerPolicy = "on";


Media.controlPlacement

Applies to

MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.controlPlacement

Description

Property; determines where the controller portion of the MediaPlayback component is positioned in relation to its display. The possible values are "top", "bottom", "left", and "right". The default value is "bottom".

Example

For the following example, the controller portion of the MediaPlayback component will be on the right side:

myMedia.controlPlacement = "right";


Media.cuePoint

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.cuePoint = function(eventObject){
  // insert your code here
}
myMedia.addEventListener("cuePoint", listenerObject)

Description

Event; notification that the playhead has reached the cue point. The Media.cuePoint event object has the following properties:

name A string that indicates the name of the cue point.

time A number, expressed in frames or seconds, that indicates when the cue point was reached.

target A reference to the cue point object.

type The string "cuePoint".

Example

The following example uses an object listener to determine when a cue point has been reached:

var myCuePointListener = new Object();
myCuePointListener.cuePoint = function(eventObject){
  trace("heard " + eventObject.type + ", " + eventObject.target);
}
myPlayback.addEventListener("cuePoint", myCuePointListener);

See also

Media.addCuePoint(), Media.cuePoints, Media.getCuePoint()


Media.cuePoints

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.cuePoints[N]

Description

Property; an array of cue point objects that have been assigned to a MediaPlayback or MediaDisplay component instance. Within the array, each cue point object can have a name, a time in seconds or frames, and a player property (which is the instance name of the component it is associated with). The default value is an empty array [].

Example

The following example deletes the third cue point if playing an action preview:

if(myVariable == actionPreview) {
  myMedia.removeCuePoint(myMedia.cuePoints[2]);
}

See also

Media.addCuePoint(), Media.getCuePoint(), Media.removeCuePoint()


Media.displayFull()

Applies to

MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.displayFull()

Parameters

None.

Returns

Nothing.

Description

Method; sets the MediaPlayback component instance to full-screen mode. In other words, the component expands to fill the entire Stage. To return the component to its normal size, use Media.displayNormal().

Example

The following code forces the component to expand to fit the Stage:

myMedia.displayFull();

See also

Media.displayNormal()


Media.displayNormal()

Applies to

MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.displayNormal()

Parameters

None.

Returns

Nothing.

Description

Method; sets the MediaPlayback instance back to its normal size after a Media.displayFull() method has been used.

Example

The following code returns a MediaPlayback component to its original size:

myMedia.displayNormal();

See also

Media.displayFull()


Media.getCuePoint()

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.getCuePoint(cuePointName)

Parameters

None.

Returns

cuePointName The string that was provided when Media.addCuePoint() was used.

Description

Method; returns a cue point object based on its cue point name.

Example

The following code retrieves a cue point named myCuePointName.

myMedia.removeCuePoint(myMedia.getCuePoint("myCuePointName"));

See also

Media.addCuePoint(), Media.cuePoint, Media.cuePoints, Media.removeCuePoint()


Media.horizontal

Applies to

MediaController

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.horizontal

Description

Property; determines whether the MediaController component will display itself in a vertical or horizontal orientation. A true value indicates that the component will be displayed in a horizontal orientation; a false value indicates a vertical orientation. When set to false, the playhead and load progress indicator move from bottom to top. The default value is true.

Example

The following example will display the MediaController component in a vertical orientation:

myMedia.horizontal = false;


Media.mediaType

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.mediaType

Description

Property; holds the value of the type of media to be played. The two choices are the FLV and MP3 formats. The default value is "FLV". See Importing Macromedia Flash Video (FLV) files.

Example

The following example determines the current media type being played:

var currentMedia = myMedia.mediaType;

See also

Media.setMedia()


Media.pause()

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.pause()

Parameters

None.

Returns

Nothing,

Description

Method; pauses the playhead at the current location.

Example

The following code pauses the playback.

myMedia.pause();


Media.play()

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.play(startingPoint)

Parameters

startingPoint A non-negative integer value that indicates the starting point (in seconds) at which the media should begin playing.

Returns

Nothing.

Description

Method; plays the media associated with the component instance at the given starting point. The default value is the current value of playheadTime.

Example

The following code indicates that the media component should start playing at 120 seconds:

myMedia.play(120);

See also

Media.pause()


Media.playheadChange

Applies to

MediaController, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.playheadChange = function(eventObject){
  // insert your code here
}
myMedia.addEventListener("playheadChange", listenerObject)

Description

Event; broadcast by the MediaController or MediaPlayback component when the user moves the playback slider or clicks the Go to Beginning or Go to End button. The Media.playheadChange event object has the following properties:

detail A number that indicates the percentage of the media that has played.

type The string "playheadChange".

Example

The following example sends the percentage played to the Output panel when the user stops dragging the playhead:

var controlListen = new Object();
controlListen.playheadChange = function(eventObject){
  trace(eventObject.detail);
}
myMedia.addEventListener("playheadChange", controlListen);


Media.playheadTime

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.playheadTime

Description

Property; holds the current position of the playhead (in seconds) for the media Timeline that is playing. The default value is set to the location of the playhead.

Example

The following example sets a variable to the location of the playhead, which is indicated in seconds:

var myPlayhead = myMedia.playheadTime;


Media.playing

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.playing

Description

Read-only property; returns a Boolean value that indicates whether the media is playing. A value of true indicates that the media is playing; false indicates that the media is paused by the user.

Example

The following code determines if the media is playing or paused:

if(myMedia.playing == true){
  some function;
}

See also

Media.change


Media.preferredHeight

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.preferredHeight

Description

Property; set according to a FLV's default height value. This property applies only to FLV media, because the height is fixed for MP3 files. This property can be used to set the height and width parameters (plus some margin for the component itself). The default value is undefined if no FLV media is set.

Example

The following example sizes a MediaPlayback instance according to the instance it is playing and accounts for the pixel margin needed for the component instance:

if(myPlayback.contentPath = !undefined){
  var mediaHeight = myPlayback.preferredHeight;
  var mediaWidth = myPlayback.preferredWidth;
  myPlayback.setSize((mediaWidth + 20), (mediaHeight + 70));
  }


Media.preferredWidth

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.preferredWidth

Description

Property; set according to a FLV's default width value. The default value is undefined.

Example

The following example sets the desired width of the variable mediaWidth:

var mediaWidth = myMedia.preferredWidth;


Media.progress

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.progress = function(eventObject){
  // insert your code here
}
myMedia.addEventListener("progress", listenerObject)

Description

Event; is generated continuously until media has completely downloaded. The Media.progress event object has the following properties:

target A reference to the MediaDisplay or MediaPlayback component instance.

type The string "progress".

Example

The following example listens for progress:

var myProgressListener = new Object();
myProgressListener.progress = function(){
  // Make lightMovieClip blink while progress is occurring
  var lightVisible = lightMovieClip.visible;
  lightMovieClip.visible = !lightVisible;
}


Media.removeAllCuePoints()

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.removeAllCuePoints()

Parameters

None.

Returns

Nothing.

Description

Method; deletes all cue point objects associated with a component instance.

Example

The following code deletes all cue point objects:

myMedia.removeAllCuePoints();

See also

Media.addCuePoint(), Media.cuePoints, Media.removeCuePoint()


Media.removeCuePoint()

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.removeCuePoint(cuePoint)

Parameters

cuePoint A reference to a cue point object that has been assigned previously by means of Media.addCuePoint().

Returns

Nothing.

Description

Method; deletes a specific cue point associated with a component instance.

Example

The following code deletes a cue point named myCuePoint:

myMedia.removeCuePoint(getCuePoint("myCuePoint"));

See also

Media.addCuePoint(), Media.cuePoints, Media.removeAllCuePoints()


Media.setMedia()

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.setMedia(contentPath, mediaType)

Parameters

contentPath A string that indicates the path and filename of the media to be played.

mediaType A string used to set the media type to either FLV or MP3. This parameter is optional.

Returns

Nothing.

Description

Method; sets the media type and path to the specified media type using a URL argument. The default value for contentPath is undefined.

This method provides the only supported way of setting the content path and media type for the MediaPlayback and MediaDisplay components.

Example

The following code provides new media for a component instance to play.

myMedia.setMedia("http://www.RogerMoore.com/moonraker.flv", "FLV");


Media.stop()

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.stop()

Parameters

None.

Returns

Nothing.

Description

Method; stops the playhead and moves it to position 0, which is the beginning of the media.

Example

The following code stops the playhead and moves it to time = 0.

myMedia.stop()


Media.totalTime

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.totalTime

Description

Property; the total length of the media, in seconds. Since the FLV file format does not provide its play time to a media component until it is completely loaded, it is necessary to input Media.totalTime manually so that the playback slider can accurately reflect the actual play time of the media. The default value for MP3 files is the play time of the media. For FLV files, the default value is undefined.

This property cannot be set for MP3 files, because the information is contained in the Sound object.

Example

The following example sets the play time in seconds for the FLV media:

myMedia.totalTime = 151;


Media.volume

Applies to

MediaDisplay, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

myMedia.volume

Description

Property; stores the volume setting integer value, which can range from 0 to 100. The default value for this property is 75.

Example

The following example sets the maximum volume for the media playback:

myMedia.volume = 100;

See also

Media.volume, Media.pause()


Media.volume

Applies to

MediaController, MediaPlayback

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.volume = function(eventObject){
  // insert your code here
}
myMedia.addEventListener("volume", listenerObject)

Description

Event; broadcast when the volume value is adjusted by the user. The Media.volume event object has the following properties:

detail An integer value between 0 and 100 that represents the volume level.

type The string "volume".

Example

The following example will inform the user that the volume is being adjusted:

var myVolListener = new Object();
myVolListener.volume = function(){
   mytextfield.text = "Volume adjusted!";
}
myMedia.addEventListener("volume", myVolListener);

See also

Media.volume


About the Menu component (Flash Professional only)

The Menu component lets a user select an item from a pop-up menu, much like the File or Edit menu of most software applications.

A Menu usually opens in an application when a user rolls over or clicks a button-like menu activator. You can also script a menu component to open when a user presses a certain key.

Menu components are always created dynamically at runtime. You must add the component to the document from the Components panel, and delete it to add it to the library. Then, use the following code to create a menu with ActionScript:

var myMenu = mx.controls.Menu.createMenu(parent, menuDataProvider);

Use the following code to open a menu in an application:

myMenu.show(x, y);

A menuShow event is broadcast to all of the Menu instance's listeners immediately before the menu is rendered, so you can update the state of the menu items. Similarly, immediately after a Menu instance is hidden, a menuHide event is broadcast.

The items in a menu are described by XML. For more information, see Understanding the Menu component: view and data.

You cannot make the Menu component accessible to screen readers.

See also:

  • Interacting with the Menu component (Flash Professional only)
  • Using the Menu component (Flash Professional only)
  • About menu item types
  • About initialization object properties
  • Menu component parameters
  • Creating an application with the Menu component
  • Customizing the Menu component
  • Menu class (Flash Professional only)


Interacting with the Menu component (Flash Professional only)

You can use the mouse and the keyboard to interact with a Menu component.

After a Menu is opened, it remains visible until it is closed by a script or until the user clicks the mouse outside the menu or inside an enabled item.

Clicking selects a menu item, except with the following types of menu items:

Disabled items or separators Rollovers and clicks have no effect (the menu remains visible).

Anchors for a submenu Rollovers activate the submenu; clicks have no effect; rolling onto any item other than those of the submenu closes the submenu.

When an item is selected, a Menu.change event is sent to all of the menu's listeners, the menu is hidden, and the following actions occur, depending on item type:

check The item's selected attribute is toggled.

radio The item becomes the current selection of its radio group.

Moving the mouse triggers Menu.rollOut and Menu.rollOver events.

Pressing the mouse outside of the menu closes the menu and triggers a Menu.menuHide event.

Releasing the mouse in an enabled item affects item types in the following ways:

check The item's selected attribute is toggled.

radio The item's selected attribute is set to true, and the previously selected item's selected attribute in the radio group is set to false. The selection property of the corresponding radio group object is set to refer to the selected menu item.

undefined and the parent of a hierarchical menu The visibility of the hierarchical menu is toggled.

When a Menu instance has focus either from clicking or tabbing, you can use the following keys to control it:

Key | Description
Down arrow Up arrow | Moves the selection down and up the rows of the menu. The selection loops at the top or bottom row.
Right arrow | Opens a submenu, or moves selection to the next menu in a menu bar (if a menu bar exists).
Left arrow | Closes a submenu and returns focus to the parent menu (if a parent menu exists), or moves selection to the previous menu in a menu bar (if the menu bar exists).
Enter | Opens a submenu, or clicks and releases on a row if a submenu does not exist.

Note: If a menu is opened, you can press the tab key to move out of the menu. You must either make a selection or dismiss the menu by pressing Escape.


Using the Menu component (Flash Professional only)

You can use the Menu component to create menus of individually selectable choices like the File or Edit menu of most software applications. You can also use the Menu component to create context-sensitive menus that appear when a user presses a hot spot or a modifier key. Use the Menu component with the MenuBar component to create a horizontal menu bar with menus that extend under each menu bar item.

Like standard desktop menus, the Menu component supports menu items whose functions fall into the following general categories:

Command activators These items trigger events; you write code to handle those events.

Submenu anchors These items are anchors that open submenus.

Radio buttons These items operate in groups; you can select only one item at a time.

Check box items These items represent a Boolean (true or false) value.

Separators These items provide a simple horizontal line that divides the items in a menu into different visual groups.

See also:

  • Understanding the Menu component: view and data
  • About hierarchical menus
  • About menu item XML attributes

Understanding the Menu component: view and data

Conceptually, the Menu component is composed of a data model and a view that displays the data. The Menu class is the view and contains the visual configuration methods. The MenuDataProvider class adds methods to the global XML prototype object (much like the DataProvider class does to the Array object); these methods let you externally construct data providers and add them to multiple menu instances. The data provider broadcasts any changes to all of its client views. (See MenuDataProvider class.)

A Menu instance is a hierarchical collection of XML elements that correspond to individual menu items. The attributes define the behavior and appearance of the corresponding menu item on the screen. The collection is easily translated to and from XML, which is used to describe menus (the menu tag) and items (the menuitem tag). The built-in ActionScript XML class is the basis for the model underlying the Menu component.

A simple menu with two items can be described in XML with two menu item subelements:

<menu>
  <menuitem label="Up" />
  <menuitem label="Down" />
</menu>

Note: The tag names of the XML nodes (menu and menuitem) are not important; the attributes and their nesting relationships are used in the menu.

About hierarchical menus

To create hierarchical menus, embed XML elements within a parent XML element, as follows:

<menu>
    <menuitem label="MenuItem A" >
      <menuitem label="SubMenuItem 1-A" />
      <menuitem label="SubMenuItem 2-A" />
    </menuitem>
    <menuitem label="MenuItem B" >
      <menuitem label="SubMenuItem 1-B" />
      <menuitem label="SubMenuItem 2-B" />
    </menuitem>
</menu>

Note: This converts the parent menu item into a pop-up menu anchor, so it does not generate events when selected.

About menu item XML attributes

The attributes of a menu item XML element determine what is displayed, how the menu item behaves, and how it is exposed to ActionScript. The following table describes the attributes of an XML menu item:

Attribute name | Type | Default | Description
label | String | undefined | The text that is displayed to represent a menu item. This attribute is required for all item types, except separator.
type | separator, check, radio, normal, or undefined | undefined | The type of menu item: separator, check box, radio button, or normal (a command or submenu activator). If this attribute does not exist, the default value is normal.
icon | String | undefined | The linkage identifier of an image asset. This attribute is not required. This attribute is not available for the check, radio, or separator types.
instanceName | String | undefined | An identifier that you can use to reference the menu item instance from the root menu instance. For example, a menu item named yellow can be referenced as myMenu.yellow. This attribute is not required.
groupName | String | undefined | An identifier that you can use to associate several radio button items in a radio group, and to expose the state of a radio group from the root menu instance. For example, a radio group named colors can be referenced as myMenu.colors. This attribute is only required for the type radio.
selected | false, true, or false or true (a String or Boolean value) | false | A Boolean value indicating whether a check or radio item is on (true) or off (false). This attribute is not required.
enabled | false, true, or false or true (a String or Boolean value) | true | A Boolean value indicating whether this menu item can be selected (true) or not (false). This attribute is not required.


About menu item types

There are four kinds of menu items, specified by the type attribute:

<menu>
    <menuitem label="Normal Item" />
    <menuitem type="separator" />
    <menuitem label="Checkbox Item" type="check" instanceName="check_1"/>
    <menuitem label="RadioButton Item" type="radio" groupName="radioGroup_1" />
</menu>

See also:

  • Normal menu items
  • Separator menu items
  • Check box menu items
  • Radio button menu items
  • Exposing menu items to ActionScript

Normal menu items

The Normal Item menu item doesn't have a type attribute, which means that the type attribute defaults to normal. Normal items can be command activators or submenu activators, depending on whether they has nested subitems.

Separator menu items

Menu items whose type attribute is set to separator act as visual dividers in a menu. The following XML creates three menu items, Top, Middle, and Bottom, with separators between them:

<menu>
    <menuitem label="Top" />
    <menuitem type="separator" />
    <menuitem label="Middle" />
    <menuitem type="separator" />
    <menuitem label="Bottom" />
</menu>

All separator items are disabled. Clicking on or rolling over a separator has no effect.

Check box menu items

Menu items whose type attribute is set to check act as check box items within the menu; when the selected attribute is set to true, a checkmark appears beside the menu item's label. When a check box item is selected, its state automatically toggles, and a change event is broadcast to all listeners on the root menu. The following example defines three check box menu items:

<menu>
    <menuitem label="Apples" type="check" instanceName="buyApples" selected="true" />
    <menuitem label="Oranges" type="check" instanceName="buyOranges" selected="false" />
    <menuitem label="Bananas" type="check" instanceName="buyBananas" selected="false" />
</menu>

You can use the instance names in ActionScript to access the menu items directly from the menu itself, as in the following example:

myMenu.setMenuItemSelected(myMenu.buyapples, true);
myMenu.setMenuItemSelected(myMenu.buyoranges, false);

Note: The selected attribute should be modified only using the setMenuItemSelected(item, b) method. You can directly examine the selected attribute, but it returns a String value of true or false.

Radio button menu items

Menu items whose type attribute is set to radio can be grouped together so that only one of the items can be selected at a time. A radio group is created by giving the menu items the same value for their groupName attribute, as in the following example:

<menu>
    <menuitem label="Center" type="radio" groupName="alignment_group"       instanceName="center_item"/>
    <menuitem type="separator" />
    <menuitem label="Top"    type="radio" groupName="alignment_group" />
    <menuitem label="Bottom" type="radio" groupName="alignment_group" />
    <menuitem label="Right"  type="radio" groupName="alignment_group" />
    <menuitem label="Left"   type="radio" groupName="alignment_group" />
</menu>

When the user selects one of the items, the current selection automatically changes, and a change event is broadcast to all listeners on the root menu. The currently selected item in a radio group is available in ActionScript using the selection property, as follows:

var selectedMenuItem = myMenu.alignment_group.selection;
myMenu.alignment_group = myMenu.center_item;

Each groupName value must be unique within the scope of the root menu instance.

Note: The selected attribute should be modified only using the setMenuItemSelected(item, b) method. You can directly examine the selected attribute, but it returns a String value of true or false.

Exposing menu items to ActionScript

You can assign each menu item a unique identifier in the instanceName attribute, which makes the menu item accessible directly from the root menu. For example, the following XML code provides instanceName attributes for each menu item:

<menu>
    <menuitem label="Item 1" instanceName="item_1" />
    <menuitem label="Item 2" instanceName="item_2" >
      <menuitem label="SubItem A" instanceName="sub_item_A" />
      <menuitem label="SubItem B" instanceName="sub_item_B" />
    </menuitem>
</menu>

You can use ActionScript to access the corresponding object instances and their attributes directly from the menu component, as follows:

var aMenuItem = myMenu.item_1;
myMenu.setMenuItemEnabled(item_2, true);
var aLabel = myMenu.sub_item_A.label;

Note: Each instanceName must be unique within the scope of the root menu component instance (including all of the submenus of root).


About initialization object properties

The initObject (initialization object) parameter is a fundamental concept in creating the layout for the Menu component. The initObject parameter is an object with properties. Each property represents one of the possible the XML attributes of a menu item. (For a description of the properties allowed in the initObject parameter, see About menu item XML attributes.)

The initObject parameter is used in the following methods:

  • Menu.addMenuItem()
  • Menu.addMenuItemAt()
  • MenuDataProvider.addMenuItem()
  • MenuDataProvider.addMenuItemAt()

The following example creates an initObject parameter with two properties, label and instanceName:

var i = myMenu.addMenuItem({label:"myMenuItem", instanceName:"myFirstItem"});

Several of the properties work together to create a particular type of menu item. You assign specific properties to create certain types of menu items (normal, separator, check box, or radio button).

For example, you can initialize a normal menu item with the following initObject parameter:

myMenu.addMenuItem({label:"myMenuItem", enabled:true, icon:"myIcon", instanceName:"myFirstItem"});

You can initialize a separator menu item with the following initObject parameter:

myMenu.addMenuItem({type:"separator"});

You can initialize a check box menu item with the following initObject parameter:

myMenu.addMenuItem({type:"check", label:"myMenuCheck", enabled:false, selected:true, instanceName:"myFirstCheckItem"})

You can initialize a radio button menu item with the following initObject parameter:

myMenu.addMenuItem({type:"radio", label:"myMenuRadio1", enabled:true, selected:false, groupName:"myRadioGroup" instanceName:"myFirstRadioItem"})

Is it important to note that you should treat the instanceName, groupName, and type attributes of a menu item as read-only. You should set them only while creating an item (for example, in a call to addMenuItem()). Modifying these attributes after creation may produce unpredictable results.


Menu component parameters

There are no authoring parameters for the Menu component.

You can write ActionScript to control the Menu component using its properties, methods, and events. For more information, see Menu class (Flash Professional only).


Creating an application with the Menu component

In the following example an application developer is building an application and uses the Menu component to expose some of the commands that users can issue, such as Open, Close, Save, and so on.

To create an application with the Menu component:

  1. Select File > New and create a Flash document.
  2. Drag the Menu component from the Components panel to the Stage and delete it.

    This adds the Menu component to the library without adding it to the application. Menus are created dynamically using ActionScript.

  3. Drag a Button component from the Components panel to the Stage.

    Clicking button activates the menu.

  4. In the Property inspector, give the button the instance name commandBtn, and change its text property to Commands.
  5. In the Actions panel on the first frame, enter the following code to add an event listener to listen for click events on the commandBtn instance:
    var listener = new Object();
listener.click = function(evtObj) {
    var button = evtObj.target;
  if(button.menu == undefined) {
        // Create a Menu instance and add some items
        button.menu = mx.controls.Menu.createMenu();
        button.menu.addMenuItem("Open");
        button.menu.addMenuItem("Close");
        button.menu.addMenuItem("Save");
        button.menu.addMenuItem("Revert");
        // Add a change-listener to catch item selections
        var changeListener = new Object();
        changeListener.change = function(event) {
      var item = event.menuItem;
      trace("Item selected:  " + item.attributes.label);
        }
        button.menu.addEventListener("change", changeListener);
    }
  button.menu.show(button.x, button.y + button.height);
}
commandBtn.addEventListener("click", listener);
  6. Select Control > Test Movie.

    Click the Commands button to see the menu appear. Select menu items to see the trace actions reporting which item was selected in the Output window.

To use XML data from a server to create and populate a menu:

  1. Select File > New and create a Flash document.
  2. Drag the Menu component from the Components panel to the Stage and delete it.

    This adds the Menu component to the library without adding it to the application. Menus are created dynamically using ActionScript.

  3. In the Actions panel, add the following code to the first frame to create a menu and add some items:
    var myMenu = mx.controls.Menu.createMenu();
// Import an XML file
var loader = new XML();
loader.menu = myMenu;
loader.ignoreWhite = true;
loader.onLoad = function(success) {
  // When the data arrives, pass it to the menu
  if(success) {
    this.menu.dataProvider = this.firstChild;
  }
};
loader.load(url);

    Note: The menu items are described by the children of the XML document's first child.

  4. Select Control > Test Movie.

To use a well-formed XML string to create and populate a menu:

  1. Select File > New and create a Flash document.
  2. Drag the Menu component from the Components panel to the Stage and delete it.

    This adds the Menu component to the library without adding it to the application. Menus are created dynamically using ActionScript.

  3. In the Actions panel, add the following code to the first frame to create a menu and add some items:
    // Create an XML string containing an menu definition
var s = "";
s += "<menu>";
s += "<menuitem label='Undo' />";
s += "<menuitem type='separator' />";
s += "<menuitem label='Cut' />";
s += "<menuitem label='Copy' />";
s += "<menuitem label='Paste' />";
s += "<menuitem label='Clear' />";
s += "<menuitem type='separator' />";
s += "<menuitem label='Select All' />";
s += "</menu>";
// Create an XML object from the String
var xml = new XML(s);
xml.ignoreWhite = true;
// Create a Menu from the XML object's firstChild
var myMenu = mx.controls.Menu.createMenu(_root, xml.firstChild);
  4. Select Control > Test Movie.

To use the MenuDataProvider class to create and populate a menu:

  1. Select File > New and create a Flash document.
  2. Drag the Menu component from the Components panel to the Stage and delete it.

    This adds the Menu component to the library without adding it to the application. Menus are created dynamically using ActionScript.

  3. In the Actions panel, add the following code to the first frame to create a menu and add some items:
      // Create an XML object to act as a factory
  var xml = new XML();

  // The item created next will not appear in the menu.
  // The 'createMenu' method call (below) expects to
  // receive a root element whose children will become
  // the items.  This is just a simple way to create that
  // root element and give it a convenient name along
  // the way.
  var theMenuElement = xml.addMenuItem("Edit");

  // Add the menu items
  theMenuElement.addMenuItem({label:"Undo"});
  theMenuElement.addMenuItem({type:"separator"});
  theMenuElement.addMenuItem({label:"Cut"});
  theMenuElement.addMenuItem({label:"Copy"});
  theMenuElement.addMenuItem({label:"Paste"});
  theMenuElement.addMenuItem({label:"Clear", enabled:"false"});
  theMenuElement.addMenuItem({type:"separator"});
  theMenuElement.addMenuItem({label:"Select All"});
  // Create the Menu object
  var theMenuControl = mx.controls.Menu.createMenu(_root, theMenuElement);
  4. Select Control > Test Movie.


Customizing the Menu component

The menu sizes itself to fit horizontally to fit its widest text. You can also call the setSize() method to size the component. Icons should be sized to a maximum of 16 pixels by 16 pixels.

See also:

  • Using styles with the Menu component
  • Using skins with the Menu component

Using styles with the Menu component

You can call the setStyle() method to change the style of the menu, its items, and its submenus. A Menu component that uses the Halo theme supports the following styles:

Style | Description
themeColor | The menu background color. This is the only color style that doesn't inherit its value.
color | The color of the text label of a menu item.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style; either normal, or italic.
fontWeight | The font weight; either normal, or bold.
rollOverColor | The rollover color of menu items.
selectionColor | Selected items and items that contain submenus.
selectionDisabledColor | Selected items and items that contain submenus and are disabled.
textRollOverColor | The color of text when you roll over an item.
textDecoration | The text decoration; either none, or underline.
textDisabledColor | The color of disabled text.
textSelectedColor | The color of text os a selected menu item.
popupDuration | The duration of the transition as a menu opens. The value 0 specifies no transition.

Using skins with the Menu component

For the latest information about this feature, click the Update button at the top of the Help tab.


Menu class (Flash Professional only)

Inheritance UIObject > UIComponent > View > ScrollView > ScrollSelectList > Menu

ActionScript Class Name mx.controls.Menu

Method summary for the Menu class

Method | Description
Menu.addMenuItem() | Adds a menu item to the Menu.
Menu.addMenuItemAt() | Adds a menu item to the Menu at a specific location.
Menu.createMenu() | Creates an instance of the Menu class. This is a static method.
Menu.getMenuItemAt() | Gets a reference to a menu item at a specified location.
Menu.hide() | Closes a menu.
Menu.indexOf() | Returns the index of a given menu item.
Menu.removeAll() | Removes all items from a menu.
Menu.removeMenuItemAt() | Removes a menu item from a Menu at a specified location
Menu.setMenuItemEnabled() | Indicates whether a menu item is enabled (true) or not (false).
Menu.setMenuItemSelected() | Indicates whether a menu item is selected (true) or not (false).
Menu.show() | Opens a menu at a specific location or at its previous location.

Inherits all methods from UIObject, UIComponent, ScrollView, and ScrollSelectList.

Property summary for the Menu class

Property | Description
Menu.dataProvider | The data source for a menu.

Inherits all properties from UIObject, UIComponent, ScrollView, and ScrollSelectList.

Event summary for the Menu class

Event | Description
Menu.change | Broadcast when a user selects an item.
Menu.menuHide | Broadcast when a menu closes.
Menu.menuShow | Broadcast when a menu opens.
Menu.rollOut | Broadcast when the pointer rolls off an item.
Menu.rollOver | Broadcast when the pointer rolls over an item.

Inherits all events from UIObject, UIComponent, ScrollView, and ScrollSelectList


Menu.addMenuItem()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

myMenu.addMenu(initObject)

Usage 2:

myMenu.addMenu(childMenuItem)

Parameters

initObject An object containing properties that initialize a menu item's attributes. See About menu item XML attributes.

childMenuItem An XML node object.

Returns

A reference to the added XML node.

Description

Method; Usage 1 adds a menu item at the end of the menu. The menu item is constructed from the values supplied in the initObject parameter. Usage 2 adds a menu item that is a prebuilt XML node (in the form of an XML object) at the end of the menu. Adding a preexisting node removes the node from its previous location.

Example

Usage 1: The following example appends a menu item to a menu:

myMenu.addMenuItem({ label:"Item 1", type:"radio", selected:false, enabled:true, instanceName:"radioItem1", groupName:"myRadioGroup" } );

Usage 2: The following example moves a node from one menu to the root of another menu:

myMenu.addMenuItem(mySecondMenu.getMenuItemAt(mySecondMenu, 3));


Menu.addMenuItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

myMenu.addMenuItemAt(index, initObject)

Usage 2:

myMenu.addMenuItemAt(index, childMenuItem)

Parameters

index An integer indicating the order (among the child nodes) at which the item is added.

initObject An object containing properties that initialize a menu item's attributes. See About menu item XML attributes.

childMenuItem An XML node object.

Returns

A reference to the added XML node.

Description

Method; Usage 1 adds a menu item (child node) at the specified location in the menu. The menu item is constructed from the values supplied in the initObject parameter. Usage 2 adds a menu item that is a prebuilt XML node (in the form of an XML object) at a specified location in the menu. Adding a preexisting node removes the node from its previous location.

Example

Usage 1: The following example adds a new node as the second child of the root of the menu:

myMenu.addMenuItemAt(1, { label:"Item 1", instanceName:"radioItem1", type:"radio", selected:false, enabled:true, groupName:"myRadioGroup" } );

Usage 2: The following example moves a node from one menu to fourth child of the root of another menu:

myMenu.addMenuItemAt(3, mySecondMenu.getMenuItemAt(mySecondMenu, 3));


Menu.change

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.change = function(eventObject){
  // insert your code here
}
myMenu.addEventListener("change", listenerObject)

Description

Event; broadcast to all registered listeners whenever a user causes a change in the menu.

V2 components use a dispatcher-listener event model. When a Menu component broadcasts a change event, the event is handled by a function (also called a handler), that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The Menu.change event's event object has the following additional properties:

  • menuBar A reference to the MenuBar instance that is the parent of the target Menu. When the target Menu does not belong to a Menu this value is undefined.
  • menu A reference to the Menu instance where the target item is located.
  • menuItem An XML node that is the menu item that was selected.
  • groupName A string indicating the name of the radio button group to which the item belongs. If the item is not in a radio button group this value is undefined.

For more information about event objects, see Event Objects.

Example

In the following example, a handler called listener is defined and passed to the myMenu.addEventListener() method as the second parameter. The event object is captured by the change handler in the event parameter. When the change event is broadcast, a trace statement is sent to the Output panel, as follows:

listener = new Object();
listener.change = function(evt){
    trace("Menu item chosen: "+evt.menuItem.attributes.label);
}
myMenu.addEventListener("change", listener);


Menu.createMenu()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Menu.createMenu(parent, mdp)

Parameters

parent A MovieClip instance. The movie clip is the parent component that contains the new Menu instance. This parameter is optional.

mdp The MenuDataProvider instance that describes this Menu instance. This parameter is optional.

Returns

A reference to the new menu instance.

Description

Method (static); instantiates a Menu instance, and optionally attaches it to the specified parent, with the specified MenuDataProvider as the data source for the menu items.

If the parent argument is omitted or null, the Menu is attached to the _root Timeline.

If the mdp argument is omitted or null, the menu does not have any items; you must call the addMenu() or setDataProvider() methods to populate the menu.

Example

In the following example, line 1 creates a MenuDataProvider which is an XML object decorated with the methods of the MenuDataProvider class. The next line adds a menu item (New) with a submenu (File, Project, and Resource). The next block of code adds more items to the main menu. The third clock of code creates an empty menu attached to myParentClip, fills it with the data source myMDP, and opens it at the coordinates 100, 20, as follows:

var myMDP = new XML();

var newItem = myMDP.addMenuItem({label:"New"});
    newItem.addMenuItem({label:"File..."});
    newItem.addMenuItem({label:"Project..."});
    newItem.addMenuItem({label:"Resource..."});

myMDP.addMenuItem({label:"Open", instanceName:"miOpen"});
myMDP.addMenuItem({label:"Save", instanceName:"miSave"});
myMDP.addMenuItem({type:"separator"});
myMDP.addMenuItem({label:"Quit", instanceName:"miQuit"});

var myMenu = mx.controls.Menu.createMenu(myParentClip, myMDP);

myMenu.show(100, 20);

To test this code, place it in the Actions panel on Frame 1 of the main Timeline. Drag a Menu component from the Components panel to the Stage and delete it. This adds it to the Library without placing it in the document.


Menu.dataProvider

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.dataProvider

Description

Property; the data source for items in a Menu component.

The Menu.dataProvider is an XML node object. Setting this property replaces the existing data source of the Menu.

The default value is undefined.

Note: All XML or XMLNode instances are automatically given the methods and properties of the MenuDataProvider API when they are used with the Menu component.

Example

The following example imports an XML file and assigns it to the Menu.dataProvider property:

var myMenuDP = new XML();
myMenuDP.load("http://myServer.myDomain.com/source.xml");
myMenuDP.onLoad = function(){
  myMenuControl.dataProvider = myMenuDP;
}


Menu.getMenuItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.getMenuItemAt(index)

Parameters

index An integer indicating the index of the node in the menu.

Returns

A reference to the specified node.

Description

Method; returns a reference to the specified child node of the menu.

Example

The following example gets a reference to the second child node in myMenu and copies the value into the variable myItem:

var myItem = myMenu.getMenuItemAt(1);


Menu.hide()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.hide()

Parameters

index The index of the Menu item.

Returns

Nothing.

Description

Method; closes a menu with optional transition effects.

Example

The following example retracts an extended menu:

myMenu.hide();

See also

Menu.show()


Menu.indexOf()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.indexOf(item)

Parameters

item A reference to an XML node that describes a menu item.

Returns

The index of the specified menu item, or undefined if the item does not belong to this menu.

Description

Method; returns the index of the specified menu item within this menu instance.

Example

The following example adds a menu item to a parent item and then gets the item's index within its parent:

var myItem = myMenu.addMenuItem({label:"That item"});
var myIndex = myMenu.indexOf(myItem);


Menu.menuHide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.menuHide = function(eventObject){
  // insert your code here
}
myMenu.addEventListener("menuHide", listenerObject)

Description

Event; broadcast to all registered listeners whenever a menu closes.

V2 components use a dispatcher-listener event model. When a Menu component dispatches a menuHide event, the event is handled by a function (also called a handler), that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler and the name of the listener object as parameters.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The Menu.menuHide event's event object has two additional properties:

  • menuBar A reference to the MenuBar instance that is the parent of the target Menu. When the target Menu does not belong to a MenuBar, this value is undefined.
  • menu A reference to the Menu instance that is hidden.

For more information about event objects, see Event Objects.

Example

In the following example, a handler called form is defined and passed to the myMenu.addEventListener() method as the second parameter. The event object is captured by menuHide handler in the event parameter. When the menuHide event is broadcast, a trace statement is sent to the Output panel, as follows:

form = new Object();
form.menuHide = function(evt){
    trace("Menu closed: "+evt.menu);
}
myMenu.addEventListener("menuHide", form);

See also

Menu.menuShow


Menu.menuShow

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.menuShow = function(eventObject){
  // insert your code here
}
myMenu.addEventListener("menuShow", listenerObject)

Description

Event; broadcast to all registered listeners whenever a menu opens. All parent nodes open menus to show their children.

V2 components use a dispatcher-listener event model. When a Menu component dispatches a menuShow event, the event is handled by a function (also called a handler), that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler and listener object as parameters.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The Menu.menuShow event's event object has two additional properties:

  • menuBar A reference to the MenuBar instance that is the parent of the target Menu. When the target Menu does not belong to a Menu, this value is undefined.
  • menu A reference to the Menu instance that is shown.

For more information about event objects, see Event Objects.

Example

In the following example, a handler called form is defined and passed to the myMenu.addEventListener() method as the second parameter. The event object is captured by menuShow handler in the evtObject parameter. When the menuShow event is broadcast, a trace statement is sent to the Output panel, as follows:

form = new Object();
form.menuShow = function(evt){
    trace("Menu opened: "+evt.menu);
}
myMenu.addEventListener("menuShow", form);

See also

Menu.menuHide


Menu.removeAll()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.removeAll()

Parameters

None.

Returns

Nothing.

Description

Method; removes all items and refreshes the menu.

Example

The following example removes all nodes from the menu:

myMenu.removeAll();


Menu.removeMenuItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.removeMenuItemAt(index)

Parameters

index The index of the menu item to remove.

Returns

A reference to the returned menu item (XML node). This value is undefined if no item exists in that position.

Description

Method; removes the menu item and all its children at the specified index. If there is no menu item at that index, calling this method has no effect.

Example

The following example removes a menu item at index 3:

var item = myMenu.removeMenuItemAt(3);


Menu.rollOut

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.rollOut = function(eventObject){
  // insert your code here
}
myMenu.addEventListener("rollOut", listenerObject)

Description

Event; broadcast to all registered listeners when the pointer rolls off a menu item.

V2 components use a dispatcher-listener event model. When a Menu component broadcasts a rollOut event, the event is handled by a function (also called a handler), that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The Menu.rollOut event's event object has one additional property:

  • menuItem A reference to the menu item (XML node) that the pointer rolled off.

For more information about event objects, see Event Objects.

Example

In the following example, a handler called form is defined and passed to the myMenu.addEventListener() method as the second parameter. The event object is captured by the rollOut handler in the event parameter. When the rollOut event is broadcast, a trace statement is sent to the Output panel, as follows:

form = new Object();
form.rollOut = function(evt){
    trace("Menu rollOut: "+evt.menuItem.attributes.label);
}
myMenu.addEventListener("rollOut", form);


Menu.rollOver

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.rollOver = function(eventObject){
  // insert your code here
}
myMenu.addEventListener("rollOver", listenerObject)

Description

Event; broadcast to all registered listeners when the pointer rolls over a menu item.

V2 components use a dispatcher-listener event model. When a Menu component broadcasts a change event, the event is handled by a function (also called a handler), that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The Menu.rollOver event's event object has one additional property:

menuItem A reference to the menu item (XML node) that the pointer rolled over.

For more information about event objects, see Event Objects.

Example

In the following example, a handler called form is defined and passed to the myMenu.addEventListener() method as the second parameter. The event object is captured by the rollOver handler in the event parameter. When the rollOver event is broadcast, a trace statement is sent to the Output panel, as follows:

form = new Object();
form.rollOver = function(evt){
    trace("Menu rollOver: "+evt.menuItem.attributes.label);
}
myMenu.addEventListener("rollOver", form);


Menu.setMenuItemEnabled()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.setMenuItemEnabled(item, enable)

Parameters

item An XML node. The target menu item's node within the data provider.

enable A Boolean value indicating whether item is enabled (true) or not (false).

Returns

Nothing.

Description

Method; changes the target item's enabled attribute to the state given by the enable parameter. If this call results in a change of state, the item is redrawn with the new state.

Example

The following example disables the second child of myMenu:

var myItem = myMenu.getMenuItemAt(1);
myMenu.setMenuItemEnabled(myItem, false);

See also

Menu.setMenuItemSelected()


Menu.setMenuItemSelected()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.setMenuItemSelected(item, select)

Parameters

item An XML node. The target menu item's node within the data provider.

select A Boolean value indicating whether item is selected (true) or not (false). If the item is a check box, its check box is visible or not visible. If the item is a radio button, the item becomes the current selection in the radio group.

Returns

Nothing.

Description

Method; changes the selected attribute of the item to the state specified by the select parameter. If this call results in a change of state, the item is redrawn with the new state. This is only meaningful for items whose type attribute is set to "radio" or "check", because it causes their dot or check to appear or disappear. If you call this method on an item whose type is "normal" or "separator", it has no effect.

Example

The following example deselects the second child of myMenu:

var myItem = myMenu.getMenuItemAt(1);
myMenu.setMenuItemSelected(myItem, false);


Menu.show()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.show(x, y)

Parameters

x The x coordinate.

y The y coordinate.

Returns

Nothing.

Description

Method; opens a menu at a specific location. The menu is automatically resized so that all of its top-level items are visible, and the upper left corner is placed at the given location within the coordinate system provided by the component's parent.

If the x and y parameters are omitted, the menu is shown at its previous location.

Example

The following example extends a menu:

myMenu.show(10, 10);

See also

Menu.hide()


MenuDataProvider class

The MenuDataProvider class is a decorator (mix-in) API that adds functionality to the XMLNode global class. This functionality lets XML instances assigned to a Menu dataProvider property manipulate their own data as well as the associated Menu views through the MenuDataProvider API.

Key concepts:

  • The MenuDataProvider is a decorator (mix-in) API. It does not need to be instantiated to be used.
  • Menus natively accept XML as a dataProvider property.
  • If a Menu class is instantiated, all XML instances in the SWF file are decorated by the MenuDataProvider API.
  • Only MenuDataProvider API methods broadcast events to the Menu controls. You can still use Native XML methods, but they are not broadcast events that refresh the Menu views.
    • Use MenuDataProvider API methods to control the data model.
    • Use XML methods for read-only operations like moving through the Menu hierarchy.
  • All items in the Menu are XML objects decorated with the MenuDataProvider API.
  • Changes to item attributes are not be reflected in the onscreen menu until a repaint occurs.

Method summary for the MenuDataProvider class

Method | Description
MenuDataProvider.addMenuItem() | Adds a child item.
MenuDataProvider.addMenuItemAt() | Adds a child item at a specific location.
MenuDataProvider.getMenuItemAt() | Gets a reference to a menu item at a specified location.
MenuDataProvider.indexOf() | Returns the index of a specified menu item.
MenuDataProvider.removeMenuItem() | Removes a menu item.
MenuDataProvider.removeMenuItemAt() | Removes a menu item at a specified location.


MenuDataProvider.addMenuItem()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

myMenu.addMenuItem(initObject)

Usage 2:

myMenu.addMenuItem(childMenuItem)

Parameters

initObject An object containing the specific attributes that initialize a Menu item's attributes. For more information, see About menu item XML attributes.

childMenuItem An XML node.

Returns

A reference to an XMLNode object.

Description

Method; Usage 1 adds a child item to the end of a parent menu item (which could be the menu itself). The menu item is constructed from the values passed in the initObject parameter. Usage 2 adds a child item that is defined in the specified XML childMenuItem parameter to the end of a parent menu item.

Example

The following example adds a new node to a specified node in the menu:

myMenuDP.firstChild.addMenuItem("Inbox", { label:"Item 1", icon:"radioItemIcon", type:"radio", selected:false, enabled:true, instanceName:"radioItem1", groupName:"myRadioGroup" } );


MenuDataProvider.addMenuItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

myMenu.addMenuItemAt(index, initObject)

Usage 2:

myMenu.addMenuItemAt(index, childMenuItem)

Parameters

index An integer.

initObject An object containing the specific attributes that initialize a Menu item's attributes. For more information, see About menu item XML attributes.

childMenuItem An XML node.

Returns

A reference to the added XML node.

Description

Method; Usage 1 adds a child item at the specified index position in the parent menu item (which could be the menu itself). The menu item is constructed from the values passed in the initObject parameter. Usage 2 adds a child item that is defined in the specified XML childMenuItem parameter to the specified index of a parent menu item.

Example

Usage 1: The following example adds a new node as the second child of the root of the menu:

myMenu.addMenuItemAt(1, { label:"Item 1", type:"radio", selected:false, enabled:true, instanceName:"radioItem1", groupName:"myRadioGroup" } );


MenuDataProvider.getMenuItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.getMenuItemAt(index)

Parameters

index An integer indicating the position of the menu.

Returns

A reference to the specified XML node.

Description

Method; returns a reference to the specified child menu item of the current menu item.

Example

The following example finds the node you want to get, and then gets the second child of myMenuItem:

var myMenuItem = myMenuDP.firstChild.firstChild;
myMenuItem.getMenuItemAt(1);


MenuDataProvider.indexOf()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.indexOf(item)

Parameters

item A reference to the XML node that describes the menu item.

Returns

The index of the specified menu item; returns undefined if the item does not belong to this menu.

Description

Method; returns the index of the specified menu item within this parent menu item.

Example

The following example adds a menu item to a parent item and gets the item's index:

var myItem = myParentItem.addMenuItem({label:"That item"});
var myIndex = myParentItem.indexOf(myItem);


MenuDataProvider.removeMenuItem()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.removeMenuItem()

Parameters

None.

Returns

A reference to the removed Menu item (XML node); undefined if an error occurs.

Description

Method; removes the target item and any child nodes.

Example

The following example removes myMenuItem from its parent:

myMenuItem.removeMenuItem();


MenuDataProvider.removeMenuItemAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenu.removeMenuItemAt(index)

Parameters

index The index of the Menu item.

Returns

A reference to the removed menu item. This value is undefined if no item exists in that position.

Description

Method; removes the child item of the menu item specified by the index parameter. If there is no menu item at that index, calling this method has no effect.

Example

The following example removes the fourth item:

myMenuDP.removeMenuItemAt(3);


About the MenuBar component (Flash Professional only)

The MenuBar component lets you create a horizontal menu bar with pop-up menus and commands, just like the File and Edit menu bars in most common software applications (such as Macromedia Flash). The menu bar complements the Menu component by providing a clickable interface to show and hide menus that behave as a group for mouse and keyboard interactivity.

The menu bar lets you create an application menu in a few steps. To build a menu bar, you can either assign an XML data provider to the menu bar that describes a series of menus, or use the MenuBar.addMenu() method to add menu instances one at a time.

Each menu within the menu bar is composed of two parts: the menu and the button that causes the menu to open (called the menu activator). These clickable menu activators appear in the menu bar as a text label with inset and outset border highlight states that react to interaction from the mouse and keyboard.

When an menu activator is pressed, the corresponding menu opens below it. The menu stays active until the activator is pressed again, or until a menu item is selected or a click occurs outside the menu area.

In addition to creating menu activators that show and hide menus, the menu bar creates group behavior among a series of menus. This lets a user scan a large number of command choices by rolling over the series of activators or by using the arrow keys to move through the lists. Both mouse and keyboard interactivity work together to let the user jump from menu to menu within the MenuBar component.

A user cannot scroll through menus on a menu bar. If menus exceed the width of the menu bar, they are masked.

You cannot make the MenuBar component accessible to screen readers.

See also:

  • Interacting with the MenuBar component (Flash Professional only)
  • Using the MenuBar component (Flash Professional only)
  • Customizing the MenuBar component (Flash Professional only)
  • MenuBar class


Interacting with the MenuBar component (Flash Professional only)

You can use the mouse and the keyboard to interact with a MenuBar component.

Rolling over a menu activator displays an outset border highlight around the activator label.

When a MenuBar instance has focus either from clicking or tabbing, you can use the following keys to control it:

Key | Description
Down arrow | Moves the selection down a menu row.
Up arrow | Moves the selection up a menu row.
Right arrow | Moves the selection to the next button.
Left arrow | Moves the selection to the previous button.
Enter/Escape | Closes an open menu.

Note: If a menu is open, you can't press the Tab key to close it. You must either make a selection or close the menu by pressing Escape.


Using the MenuBar component (Flash Professional only)

You can use the MenuBar component to add a set of menus (for example, File, Edit, Special, Window, and so on) to the top edge of an application.

See also:

  • MenuBar component parameters
  • Creating an application with the MenuBar component

MenuBar component parameters

The following are authoring parameters that you can set for each MenuBar component instance in the Property inspector or in the Component Inspector panel:

labels An array that adds menu activators to the MenuBar with the given labels. The default value is [] (empty array).

You can write ActionScript to control these and additional options for the MenuBar component using its properties, methods, and events. For more information, see MenuBar class.

Creating an application with the MenuBar component

In this example, you drag a MenuBar component to the Stage, add code to fill the instance with menus, and attach listeners to the menus to respond to menu item selection.

To use a MenuBar component in an application:

  1. Select File > New to create a new Flash Document.
  2. Drag the MenuBar component from the Components panel to the Stage.
  3. Position the menu at the top of the Stage for a standard layout.
  4. Select the MenuBar, and in the Property inspector, enter the instance name myMenuBar.
  5. In the Actions panel on Frame 1, enter the following code:
    var menu = myMenuBar.addMenu("File");
menu.addMenuItem({label:"New", instanceName:"newInstance"});
menu.addMenuItem({label:"Open", instanceName:"openInstance"});
menu.addMenuItem({label:"Close", instanceName:"closeInstance"});

    This code adds a File menu to the menu bar instance. It then uses the Menu API to add three menu items: New, Open, and Close.

  6. In the Actions panel on Frame 1, enter the following code:
    var listen = new Object();
listen.change = function(evt){
  var menu = evt.menu;
  var item = evt.menuItem
  if (item == menu.newInstance){
    myNew();
    trace(item);
  }else if (item == menu.openInstance){
    myOpen()
    trace(item);
  }
}
menu.addEventListener("change",listen);

    This code creates a listener object, listen, that uses the event object, evt, to catch menu item selections.

    Note: You must call the addEventListener method to register the listener with the menu instance, not with the menu bar instance.

  7. Select Control > Test Movie to test the MenuBar component.


Customizing the MenuBar component (Flash Professional only)

This component sizes itself based on the activator labels that are supplied through the dataProvider property or the methods of the MenuBar class. When an activator button is in a menu bar, it remains a fixed size that is dependent on the font styles and the text length.

See also:

  • Using styles with the MenuBar component
  • Using skins with the MenuBar component

Using styles with the MenuBar component

The MenuBar creates an activator label for each menu within a group. You can use styles to change the look of the activator labels. A MenuBar component supports the following Halo styles:

Style | Description
themeColor | The selection highlight color. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style; either "normal", or "italic".
fontWeight | The font weight; either "normal", or "bold".
textDecoration | The text decoration; either "none", or "underline".
popupDuration | The amount of time in milliseconds that it takes a menu to pop up. The default value is 0.

The MenuBar component also uses the RectBorder class to draw inset and outset highlights around the label when a user interacts with it. You can use the setStyle() method (see UIObject.setStyle()) to change the following RectBorder style properties:

RectBorder styles | Border position
borderColor | a
highlightColor | b
borderColor | c
shadowColor | d
borderCapColor | e
shadowCapColor | f
shadowCapColor | g
borderCapColor | h

The style properties set the following positions on the border:

Using skins with the MenuBar component

The MenuBar component uses the skins of the Menu component to represent its visual states. For information about the Menu component skins, see Using skins with the Menu component.


MenuBar class

Inheritance UIObject > UIComponent > MenuBar

ActionScript Class Name mx.controls.MenuBar

Method summary for the MenuBar class

Method | Description
MenuBar.addMenu() | Adds a menu to the menu bar.
MenuBar.addMenuAt() | Adds a menu to the menu bar at a specific location.
MenuBar.getMenuAt() | Gets a reference to a menu at a specified location.
MenuBar.getMenuEnabledAt() | Returns a Boolean value indicating whether a menu is enabled (true) or not (false).
MenuBar.removeMenuAt() | Removes a menu from a menu bar at a specified location.
MenuBar.setMenuEnabledAt() | A Boolean value indicating whether a menu is enabled (true) or not (false).

Inherits all methods from UIObject and UIComponent.

Property summary for the MenuBar class

Property | Description
MenuBar.dataProvider | The data model for a menu bar.
MenuBar.labelField | A string that determines which attribute of each XMLNode to use as the label text of the menu bar item.
MenuBar.labelFunction | A function that determines what to display as the label of each menu bar item.

Inherits all methods from UIObject and UIComponent.


MenuBar.addMenu()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

myMenuBar.addMenu(label)

Usage 2:

myMenuBar.addMenu(label, menuDataProvider)

Parameters

label A string indicating the label of the new menu.

menuDataProvider An XML or XMLNode instance that describes the menu and its items. If the value is an XML instance, the instance's firstChild is used.

Returns

A reference to the new Menu object.

Description

Method; Usage 1 adds a single menu and menu activator at the end of the menu bar with the value specified in the label parameter. Usage 2 adds a single menu and menu activator that are defined in the specified XML menuDataProvider parameter.

Example

Usage 1: The following example adds a File menu and then uses the Menu.addMenuItem() method to add the menu items New and Open:

menu = myMenuBar.addMenu("File");
menu.addMenuItem({label:"New", instanceName:newInstance"});
menu.addMenuItem("{label:"Open", instanceName:"openInstance"}");

Usage 2: The following example adds a Font menu with the menu items Bold and Italic that are defined in the menuDataProvider myMenuDP2:

var myMenuDP2 = new XML();
myMenuDP2.addMenuItem({type:"check", label:"Bold", instanceName:"check1"});
myMenuDP2.addMenuItem({type:"check", label:"Italic", instanceName:"check2"});
menu = myMenuBar.addMenu("Font",myMenuDP2);


MenuBar.addMenuAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

myMenuBar.addMenuAt(index, label)

Usage 2:

myMenuBar.addMenuAt(index, label, menuDataProvider)

Parameters

index An integer indicating the position where the menu should be inserted. The first position is 0. To append to the end of the menu, call MenuBar.addMenu(label).

label A string indicating the label of the new menu.

menuDataProvider An XML or XMLNode instance that describes the menu. If the value is an XML instance, the instance's firstChild is used.

Returns

A reference to the new Menu object.

Description

Method; Usage 1 adds a single menu and menu activator at the specified index with the value specified in the label parameter. Usage 2 adds a single menu and a labeled menu activator at the specified index. The content for the menu is defined in the menuDataProvider parameter.

Example

Usage 1: The following example places a menu to the left of all MenuBar menus:

menu = myMenuBar.addMenuAt(0,"Toreador");
menu.addMenuItem("About Macromedia Flash", instanceName:"aboutInst");
menu.addMenuItem("Preferences", instanceName:"PrefInst");

Usage 2: The following example adds an Edit menu with the menu items Undo, Redo, Cut, and Copy, which are defined in the menuDataProvider myMenuDP:

var myMenuDP = new XML();
myMenuDP.addMenuItem({label:"Undo", instanceName:"undoInst"});
myMenuDP.addMenuItem({label:"Redo", instanceName:"redoInst"});
myMenuDP.addMenuItem({type:"separator"});
myMenuDP.addMenuItem({label:"Cut", instanceName:"cutInst"});
myMenuDP.addMenuItem({label:"Copy", instanceName:"copyInst"});

myMenuBar.addMenuAt(0,"Edit",myMenuDP);


MenuBar.dataProvider

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenuBar.dataProvider

Description

Property; the data model for items in a MenuBar component.

The menuBar.dataProvider is an XML node object. Setting this property replaces the existing data model of the MenuBar component. Whatever child nodes the data provider might have are used as the items for the menu bar itself; any subnodes of these child nodes are used as the items for their respective menus.

The default value is undefined.

Note: All XML or XMLNode instances are automatically given the methods and properties of the MenuDataProvider API when they are used with the MenuBar component.

Example

The following example imports an XML file and assigns it to the MenuBar.dataProvider property:

var myMenuBarDP = new XML();
myMenuBarDP.load("http://myServer.myDomain.com/source.xml");
myMenuBarDP.onLoad = function(success){
  if(success){
    myMenuBar.dataProvider = myMenuBarDP;
  } else {
  trace("error loading XML file");
  }
}


MenuBar.getMenuAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenuBar.getMenuAt(index)

Parameters

index An integer indicating the position of the menu.

Returns

A reference to the menu at the specified index. This value is undefined if there is no menu at that position.

Description

Method; returns a reference to the menu at the specified index.

Example

Because the getMenuAt() method returns an instance, it is possible to add items to a menu at the specified index. In the following example, after using the Label authoring parameter to create the menu activators File, Edit, and View, the following code adds New and Open items to the File menu at runtime:

menu = myMenuBar.getMenuAt(0);
menu.addMenuItem({label:"New",instanceName:"newInst"});
menu.addMenuItem({label:"Open",instanceName:"openInst"});


MenuBar.getMenuEnabledAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenuBar.getMenuEnabledAt(index)

Parameters

index The index of the MenuBar item.

Returns

A Boolean value that indicates whether this menu can be chosen (true) or not (false).

Description

Method; returns a Boolean value that indicates whether this menu can be chosen (true) or not (false).

Example

The following example calls the method on the menu in the first position of myMenuBar:

myMenuBar.getMenuEnabledAt(0);


MenuBar.labelField

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenuBar.labelField

Description

Property; a string that determines which attribute of each XML node to use as the label text of the menu. This property is also passed to any menus that are created from the menu bar. The default value is "label".

After the dataProvider property is set, this property is read-only.

Example

The following example uses the name attribute of each node as the label text:

myMenuBar.labelField = "name";


MenuBar.labelFunction

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenuBar.labelFunction

Description

Property; a function that determines what to display in each menu's label text. The function accepts the XML node associated with an item as a parameter and returns a string to be used as label text. This property is passed to any menus created from the menu bar. The default value is undefined.

After the dataProvider property is set, this property is read-only.

Example

The following example builds a custom label from the node attributes:

myMenuBar.labelFunction = function(node){
var a = node.attributes;
return "The Price for " + a.name + " is " + a.price;
};


MenuBar.removeMenuAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenuBar.removeMenuAt(index)

Parameters

index The index of the MenuBar item.

Returns

A reference to the returned MenuBar item. This value is undefined if no item exists in that position.

Description

Method; removes the menu at the specified index. If there is no menu item at that index, calling this method has no effect.

Example

The following example removes the menu at index 4:

myMenuBar.removeMenuAt(4);


MenuBar.setMenuEnabledAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myMenuBar.setMenuEnabledAt(index, boolean)

Parameters

index The index of the MenuBar item to set.

boolean A Boolean value indicating whether the menu item at the specified index is enabled (true) or not (false).

Returns

Nothing.

Description

Method; enables the menu at the given index. If there is no menu at that index, calling this method has no effect.

Example

The following example gets the MenuBarColumn object at index 3:

myMenuBar.setMenuEnabledAt(3);


About the NumericStepper component

The NumericStepper component allows a user to step through an ordered set of numbers. The component consists of a number displayed beside small up and down arrow buttons. When a user pushes the buttons, the number is raised or lowered incrementally. If the user clicks either of the arrow buttons, the number increases or decreases, based on the value of the stepSize parameter, until the user releases the mouse or until the maximum or minimum value is reached.

The NumericStepper only handles numeric data. Also, you must resize the stepper while authoring to display more than two numeric places (for example, the numbers 5246 or 1.34).

A stepper can be enabled or disabled in an application. In the disabled state, a stepper doesn't receive mouse or keyboard input. An enabled stepper receives focus if you click it or tab to it and its internal focus is set to the text box. When a NumericStepper instance has focus, you can use the following keys control it:

Key | Description
Down | Value changes by one unit.
Left | Moves the insertion point to the left within the text box.
Right | Moves the insertion point to the right within the text box.
Shift + Tab | Moves focus to the previous object.
Tab | Moves focus to the next object.
Up | Value changes by one unit.

For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each stepper instance reflects the value of the value parameter indicated by the Property inspector or Component Inspector panel while authoring. However, there is no mouse or keyboard interaction with the stepper buttons in the live preview.

When you add the NumericStepper component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility:

mx.accessibility.NumericStepperAccImpl.enableAccessibility();

You only enable accessibility for a component once no matter how many instances you have of the component. For more information, see Creating Accessible Content.See also:

  • Using the NumericStepper component
  • Customizing the NumericStepper component
  • NumericStepper class


Using the NumericStepper component

The NumericStepper can be used anywhere you want a user to select a numeric value. For example, you could use a NumericStepper component in a form to allow a user to set their credit card expiration date. In another example, you could use a NumericStepper to allow a user to increase or decrease a font size.

See also:

  • NumericStepper parameters
  • Creating an application with the NumericStepper component

NumericStepper parameters

The following are authoring parameters that you can set for each NumericStepper component instance in the Property inspector or in the Component Inspector panel:

value sets the value of the current step. The default value is 0.

minimum sets the minimum value of the step. The default value is 0.

maximum sets the maximum value of the step. The default value is 10.

stepSize sets the unit of change for the step. The default value is 1.

You can write ActionScript to control these and additional options for NumericStepper components using its properties, methods, and events. For more information, see NumericStepper class.

Creating an application with the NumericStepper component

The following procedure explains how to add a NumericStepper component to an application while authoring. In this example, the stepper allows a user to pick a movie rating from 0 to 5 stars with half-star increments.

To create an application with the Button component, do the following:

  1. Drag a NumericStepper component from the Components panel to the Stage.
  2. In the Property inspector, enter the instance name starStepper.
  3. In the Property inspector, do the following:
    • Enter 0 for the minimum parameter.
    • Enter 5 for the maximum parameter.
    • Enter .5 for the stepSize parameter.
    • Enter 0 for the value parameter.
  4. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code:
    movieRate = new Object();
movieRate.change = function (eventObject){
  starChart.value = eventObject.target.value;
}
starStepper.addEventListener("change", movieRate);

    The last line of code adds a change event handler to the starStepper instance. The handler sets the starChart movie clip to display the amount of stars indicated by the starStepper instance. (To see this code work, you must create a starChart movie clip with a value property that displays the stars.)


Customizing the NumericStepper component

You can transform a NumericStepper component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()) or any applicable properties and methods of the NumericStepper class. See NumericStepper class.

See also:

  • Using styles with the NumericStepper component
  • Using skins with the NumericStepper component

Resizing the NumericStepper component does not change the size of the down and up arrow buttons. If the stepper is resized greater than the default height, the stepper buttons are pinned to the top and the bottom of the component. The stepper buttons always appear to the right of the text box.

Using styles with the NumericStepper component

You can set style properties to change the appearance of a stepper instance. If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

A NumericStepper component that uses the Halo theme supports the following styles:

Style | Description
themeColor | The background of a component. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style; either "normal", or "italic".
fontWeight | The font weight; either "normal", or "bold".
textDecoration | The text decoration; either "none", or "underline".
textAlign | The text alignment; either "left", "right", or "center".

Using skins with the NumericStepper component

The NumericStepper component skins to represent its visual states. To skin the NumericStepper component while authoring, modify skin symbols in the library and re-export the component as a SWC. The skin symbols are located in the Flash UI Components 2/Themes/MMDefault/Stepper Elements/states folder in the library. For more information, see About skinning components.

If a stepper is enabled, the down and up buttons display their over states when the pointer moves over them. The buttons display their down state when clicked. The buttons return to their over state when the mouse is released. If the pointer moves off the buttons while the mouse is pressed, the buttons return to their original state.

If a stepper is disabled it displays its disabled state, regardless of user interaction.

A NumericStepper component uses the following skin properties:

Property | Description
upArrowUp | The up arrow's up state. The default value is StepUpArrowUp.
upArrowDown | The up arrow's pressed state. The default value is StepUpArrowDown.
upArrowOver | The up arrow's over state. The default value is StepUpArrowOver.
upArrowDisabled | The up arrow's disabled state. The default value is StepUpArrowDisabled.
downArrowUp | The down arrow's up state. The default value is StepDownArrowUp.
downArrowDown | The down arrow's down state. The default value is StepDownArrowDown.
downArrowOver | The down arrow's over state. The default value is StepDownArrowOver.
downArrowDisabled | The down arrow's disabled state. The default value is StepDownArrowDisabled.


NumericStepper class

Inheritance UIObject > UIComponent > NumericStepper

ActionScript Class Name mx.controls.NumericStepper

The properties of the NumericStepper class allow you to add indicate the minimum and maximum step values, the unit amount for each step, and the current value of the step at runtime.

Setting a property of the NumericStepper class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

The NumericStepper component uses the FocusManager to override the default Flash Player focus rectangle and draw a custom focus rectangle with rounded corners. For more information, see Creating custom focus navigation.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.NumericStepper.version);

Note: The following code returns undefined: trace(myNumericStepperInstance.version);.

Method summary for the NumericStepper class

Inherits all methods from UIObject and UIComponent.

Property summary for the NumericStepper class

Property | Description
NumericStepper.maximum | A number indicating the maximum range value.
NumericStepper.minimum | A number indicating the minimum range value.
NumericStepper.nextValue | A number indicating the next sequential value. This property is read-only.
NumericStepper.previousValue | A number indicating the previous sequential value. This property is read-only.
NumericStepper.stepSize | A number indicating the unit of change for each step.
NumericStepper.value | A number indicating the current value of the stepper.

Inherits all properties from UIObject and UIComponent.

Event summary for the NumericStepper class

Event | Description
NumericStepper.change | Triggered when the value of the step changes.

Inherits all events from UIObject and UIComponent.


NumericStepper.change

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(click){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.change = function(eventObject){
  ...
}
stepperInstance.addEventListener("change", listenerObject)

Description

Event; broadcast to all registered listeners when the value of the stepper is changed.

The first usage example uses an on() handler and must be attached directly to a NumericStepper component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the stepper myStepper, sends "_level0.myStepper" to the Output panel:

on(click){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (stepperInstance) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when a stepper called myNumericStepper is changed. The first line of code creates a listener object called form. The second line defines a function for the change event on the listener object. Inside the function is a trace action that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event, in this example myNumericStepper. The NumericStepper.value property is accessed from the event object's target property. The last line calls the UIEventDispatcher.addEventListener() method from myNumericStepper and passes it the change event and the form listener object as parameters, as in the following:

form = new Object();
form.change = function(eventObj){
  // eventObj.target is the component which generated the change event,
  // i.e., the Numeric Stepper.
  trace("Value changed to " + eventObj.target.value);
}
myNumericStepper.addEventListener("change", form);


NumericStepper.maximum

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

stepperInstance.maximum

Description

Property; the maximum range value of the stepper. This property can contain a number with up to three decimal places. The default value is 10.

Example

The following example sets the maximum value of the stepper range to 20:

myStepper.maximum = 20;

See also

NumericStepper.minimum


NumericStepper.minimum

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

stepperInstance.minimum

Description

Property; the minimum range value of the stepper. This property can contain a number with up to three decimal places. The default value is 0.

Example

The following example sets the minimum value of the stepper range to 100:

myStepper.minimum = 100;

See also

NumericStepper.maximum


NumericStepper.nextValue

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

stepperInstance.nextValue

Description

Property (read-only); the next sequential value. This property can contain a number with up to three decimal places.

Example

The following example sets the stepSize property to 1 and the starting value to 4, which would make the value of nextValue 5:

myStepper.stepSize = 1;
myStepper.value = 4;
trace(myStepper.nextValue);

See also

NumericStepper.previousValue


NumericStepper.previousValue

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

stepperInstance.previousValue

Description

Property (read-only); the previous sequential value. This property can contain a number with up to three decimal places.

Example

The following example sets the stepSize property to 1 and the starting value to 4, which would make the value of nextValue 3:

myStepper.stepSize = 1;
myStepper.value = 4;
trace(myStepper.previousValue);

See also

NumericStepper.nextValue


NumericStepper.stepSize

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

stepperInstance.stepSize

Description

Property; the unit amount to change from the current value. The default value is 1. This value cannot be 0. This property can contain a number with up to three decimal places.

Example

The following example sets the current value to 2 and the stepSize unit to 2. The value of nextValue is 4:

myStepper.value = 2;
myStepper.stepSize = 2;
trace(myStepper.nextValue);


NumericStepper.value

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

stepperInstance.value

Description

Property; the current value displayed in the text area of the stepper. The value will not be assigned if it does not correspond to the stepper's range and step increment as defined in the stepSize property. This property can contain a number with up to three decimal places

Example

The following example sets the current value of the stepper to 10 and sends the value to the Output panel:

myStepper.value = 10;
trace(myStepper.value);


About the PopUpManager class

ActionScript Class Name mx.managers.PopUpManager

The PopUpManager class allows you to create overlapping windows that can be modal or non-modal. (A modal window doesn't allow interaction with other windows while it's active.) You can call PopUpManager.createPopUp() to create an overlapping window, and call PopUpManager.deletePopUp() on the window instance to destroy a pop-up window.

Method summary for the PopUpManager class

Event | Description
PopUpManager.createPopUp() | Creates a pop-up window.
PopUpManager.deletePopUp() | Deletes a pop-up window created by a call to PopUpManager.createPopUp().


PopUpManager.createPopUp()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

PopUpManager.createPopUp(parent, class, modal [, initobj, outsideEvents])

Parameters

parent A reference to a window to pop-up over.

class A reference to the class of object you want to create.

modal A Boolean value indicating whether the window is modal (true) or not (false).

initobj An object containing initialization properties. This parameter is optional.

outsideEvents A Boolean value indicating whether an event is triggered if the user clicks outside the window (true) or not (false). This parameter is optional.

Returns

A reference to the window that was created.

Description

Method; if modal, a call to createPopUp() finds the topmost parent window starting with parent and creates an instance of class. If non-modal, a call to createPopUp() creates an instance of the class as a child of the parent window.

Example

The following code creates a modal window when the button is clicked:

lo = new Object();
lo.click = function(){
  mx.managers.PopUpManager.createPopUp(_root, mx.containers.Window, true);
}
button.addEventListener("click", lo);


PopUpManager.deletePopUp()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004

Usage

windowInstance.deletePopUp();

Parameters

None.

Returns

Nothing.

Description

Method; deletes a pop-up window and removes the modal state. It is the responsibility of the overlapped window to call PopUpManager.deletePopUp() when the window is being destroyed.

Example

The following code creates and a modal window named win with a close button, and deletes the window when the close button is clicked:

import mx.managers.PopUpManager
import mx.containers.Window
win = PopUpManager.createPopUp(_root, Window, true, {closeButton:true});
lo = new Object();
lo.click = function(){
  win.deletePopUp();
}
win.addEventListener("click", lo);


About the ProgressBar component

The ProgressBar component displays the loading progress while a user waits for the content to load. The loading process can be determinate or indeterminate. A determinate progress bar is a linear representation of the progress of a task over time and is used when the amount of content to load is known. An indeterminate progress bar is used when the amount of content to load is unknown. You can add a label to display the progress of the loading content.

Components are set to export in first frame by default. This means that components are loaded into an application before the first frame is rendered. If you want to create a preloader for an application, you will need to deselect Export in first frame in each component's Linkage Properties dialog (Library panel options > Linkage). The ProgressBar, however, should be set to Export in first frame, because it must display first while other content streams into Flash Player.

A live preview of each ProgressBar instance reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring. The following parameters are reflected in the live preview: conversion, direction, label, labelPlacement, mode, and source.

See also:

  • Using the ProgressBar component
  • Customizing the ProgressBar component
  • ProgressBar class


Using the ProgressBar component

A progress bar allows you to display the progress of content as it loads. This is essential feedback for users as they interact with an application.

There are several modes in which to use the ProgressBar component; you set the mode with the mode parameter. The most commonly used modes are "event" and "polled". These modes use the source parameter to specify a loading process that either emits progress and complete events (event mode), or exposes getBytesLoaded and getsBytesTotal methods (polled mode). You can also use the ProgressBar component in manual mode by manually setting the maximum, minimum, and indeterminate properties along with calls to the ProgressBar.setProgress() method.

See also:

  • ProgressBar parameters
  • Creating an application with the ProgressBar component

ProgressBar parameters

The following are authoring parameters that you can set for each ProgressBar component instance in the Property inspector or in the Component Inspector panel:

mode The mode in which the progress bar operates. This value can be one of the following: event, polled, or manual. The default value is event.

source A string to be converted into an object representing the instance name of the source.

direction The direction toward which the progress bar fills. This value can be right or left; the default value is right.

label The text indicating the loading progress. This parameter is a string in the format "%1 out of %2 loaded (%3%%)"; %1 is a placeholder for the current bytes loaded, %2 is a placeholder for the total bytes loaded, and %3 is a placeholder for the percent of content loaded. The characters "%%" are a placeholder for the "%" character. If a value for %2 is unknown, it is replaced by "??". If a value is undefined, the label doesn't display.

labelPlacement The position of the label in relation to the progress bar. This parameter can be one of the following values: top, bottom, left, right, center. The default value is bottom.

conversion A number to divide the %1 and %2 values in the label string before they are displayed. The default value is 1.

You can write ActionScript to control these and additional options for ProgressBar components using its properties, methods, and events. For more information, see ProgressBar class.

Creating an application with the ProgressBar component

The following procedure explains how to add a ProgressBar component to an application while authoring. In this example, progress bar is used in event mode. In event mode, the loading content must emit progress and complete events that the progress bar uses to display progress. The Loader component emits these events. For more information, see Loader component.

To create an application with the ProgressBar component in event mode, do the following:

  1. Drag a ProgressBar component from the Components panel to the Stage.
  2. In the Property inspector, do the following:
    • Enter the instance name pBar.
    • Select event for the mode parameter.
  3. Drag a Loader component from the Components panel to the Stage.
  4. In the Property inspector, enter the instance name loader.
  5. Select the progress bar on the Stage and, in the Property inspector, enter loader for the source parameter.
  6. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code that loads a JPEG file into the Loader component:
    loader.autoLoad = false;
loader.contentPath = "http://imagecache2.allposters.com/images/86/017_PP0240.jpg";
pBar.source = loader;
// loading does not start until the load method is invoked
loader.load();

In the following example, the progress bar is used in polled mode. In polled mode, the ProgressBar uses the getBytesLoaded and getBytesTotal methods of the source object to display its progress.

To create an application with the ProgressBar component in polled mode, do the following:

  1. Drag a ProgressBar component from the Components panel to the Stage.
  2. In the Property inspector, do the following:
    • Enter the instance name pBar.
    • Select polled for the mode parameter.
    • Enter loader for the source parameter.
  3. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code that creates a Sound object called loader and calls the loadSound() method to load a sound into the Sound object:
    var loader:Object = new Sound();
loader.loadSound("http://soundamerica.com/sounds/sound_fx/A-E/air.wav", true);

In the following example, the progress bar is used in manual mode. In manual mode, you must set the maximum, minimum, and indeterminate properties in conjunction with the setProgress() method to display progress. You do not set the source property in manual mode.

To create an application with the ProgressBar component in manual mode, do the following:

  1. Drag a ProgressBar component from the Components panel to the Stage.
  2. In the Property inspector, do the following:
    • Enter the instance name pBar.
    • Select manual for the mode parameter.
  3. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code that updates the progress bar manually on every file download using calls to the setProgress() method:
    for(var:Number i=1; i <= total; i++){
  // insert code to load file
  // insert code to load file
pBar.setProgress(i, total);
}


Customizing the ProgressBar component

You can transform a ProgressBar component horizontally both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use UIObject.setSize().

The left cap and right cap of the progress bar and track graphic are a fixed size. When you resize a progress bar, the middle part of the progress bar resized to fit between them. If a progress bar is too small, it may not render correctly.

See also:

  • Using styles with the ProgressBar component
  • Using skins with the ProgressBar component

Using styles with the ProgressBar component

You can set style properties to change the appearance of a progress bar instance. If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

A ProgressBar component that uses the Halo theme supports the following styles:

Style | Description
themeColor | The background of a component. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style; either "normal" or "italic".
fontWeight | The font weight; either "normal" or "bold".
textDecoration | The text decoration; either "none" or "underline".

Using skins with the ProgressBar component

The ProgressBar component uses the following movie clip symbols to display its states: TrackMiddle, TrackLeftCap, TrackRightCap and BarMiddle, BarLeftCap, BarRightCap and IndBar. The IndBar symbol is used for an indeterminate progress bar. To skin the ProgressBar component while authoring, modify symbols in the library and re-export the component as a SWC. The symbols are located in the Flash UI Components 2/Themes/MMDefault/ProgressBar Elements folder in the library of the HaloTheme.fla file or the SampleTheme.fla file. For more information, see About skinning components.

If you use the UIObject.createClassObject() method to create a ProgressBar component instance dynamically (at runtime), you can also skin it dynamically. To skin a component at runtime, set the skin properties of the initObject parameter that is passed to the createClassObject() method. The skin properties set the names of the symbols to use as the states of the progress bar.

A ProgressBar component uses the following skin properties:

Property | Description
progTrackMiddleName | The expandable middle of the track. The default value is ProgTrackMiddle.
progTrackLeftName | The fixed-size left cap. The default value is ProgTrackLeft.
progTrackRightName | The fixed-size right cap. The default value is ProgTrackRight.
progBarMiddleName | The expandable middle bar graphic. The default value is ProgBarMiddle.
progBarLeftName | The fixed-size left bar cap. The default value is ProgBarLeft.
progBarRightName | The fixed-size right bar cap. The default value is ProgBarRight.
progIndBarName | The indeterminate bar graphic. The default value is ProgIndBar.


ProgressBar class

Inheritance UIObject > ProgressBar

ActionScript Class Name mx.controls.ProgressBar

Setting a property of the ProgressBar class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.ProgressBar.version);

Note: The following code returns undefined: trace(myProgressBarInstance.version);.

Method summary for the ProgressBar class

Method | Description
ProgressBar.setProgress() | Sets the progress of the bar in manual mode.

Inherits all methods from UIObject.

Property summary for the ProgressBar class

Property | Description
ProgressBar.conversion | A number used to convert the current bytes loaded value and the total bytes loaded values.
ProgressBar.direction | The direction that the progress bar fills.
ProgressBar.indeterminate | Indicates that the total bytes of the source is unknown.
ProgressBar.label | The text the accompanies the progress bar.
ProgressBar.labelPlacement | The location of the label in relation to the progress bar.
ProgressBar.maximum | The maximum value of the progress bar in manual mode.
ProgressBar.minimum | The minimum value of the progress bar in manual mode.
ProgressBar.mode | The mode in which the progress bar loads content.
ProgressBar.percentComplete | A number indicating the percent loaded.
ProgressBar.source | The content to load whose progress is monitored by the progress bar.
ProgressBar.value | Indicates the amount of progress that has been made. This property is read-only.

Inherits all properties from UIObject.

Event summary for the ProgressBar class

Event | Description
ProgressBar.complete | Triggered when loading is complete.
ProgressBar.progress | Triggered as content loads in event or polled mode.

Inherits all events from UIObject.


ProgressBar.complete

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(complete){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.complete = function(eventObject){
  ...
}
pBar.addEventListener("complete", listenerObject)

Event Object

In addition to the standard event object properties, there are two additional properties defined for the ProgressBar.complete event: current (the loaded value equals total), and total (the total value).

Description

Event; broadcast to all registered listeners when the loading progress has completed.

The first usage example uses an on() handler and must be attached directly to a ProgressBar component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the instance pBar, sends "_level0.pBar" to the Output panel:

on(complete){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (pBar) dispatches an event (in this case, complete) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example creates a form listener object with a complete callback function that sends a message to the Output panel with the value of the pBar instance, as in the following:

form.complete = function(eventObj){
  // eventObj.target is the component which generated the change event,
  // i.e., the Progress Bar.
  trace("Value changed to " + eventObj.target.value);
}
pBar.addEventListener("complete", form);

See also

UIEventDispatcher.addEventListener()


ProgressBar.conversion

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.conversion

Description

Property; a number that sets a conversion value for the incoming values. It divides the current and total values, floors them, and displays the converted value in the label property. The default value is 1.

Example

The following code displays the value of the loading progress in kilobytes:

pBar.conversion = 1024;


ProgressBar.direction

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.direction

Description

Property; indicates the fill direction for the progress bar. The default value is "right".

Example

The following code sets makes the progress bar fill from right to left:

pBar.direction = "left";


ProgressBar.indeterminate

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.indeterminate

Description

Property; a Boolean value that indicates whether the progress bar has a candy-cane striped fill and a loading source of unknown size (true), or a solid fill and a loading source of a known size (false).

Example

The following code creates a determinate progress bar with a solid fill that moves from left to right:

pBar.direction = "right";
pBar.indeterminate = false;


ProgressBar.label

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.label

Description

Property; text that indicates the loading progress. This property is a string in the format "%1 out of %2 loaded (%3%%)"; %1 is a placeholder for the current bytes loaded, %2 is a placeholder for the total bytes loaded, and %3 is a placeholder for the percent of content loaded. The characters "%%" are a placeholder for the "%" character. If a value for %2 is unknown, it is replaced by "??". If a value is undefined, the label doesn't display. The default value is "LOADING %3%%"

Example

The following code sets the text that appears beside the progress bar to the format "4 files loaded":

pBar.label = "%1 files loaded";

See also

ProgressBar.labelPlacement


ProgressBar.labelPlacement

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.labelPlacement

Description

Property; sets the placement of the label in relation to the progress bar. The possible values are "left", "right", "top", "bottom", and "center".

Example

The following code sets label to display above the progress bar:

pBar.label = "%1 out of %2 loaded (%3%%)";
pBar.labelPlacement = "top";

See also

ProgressBar.label


ProgressBar.maximum

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.maximum

Description

Property; the largest value for the progress bar when the ProgressBar.mode property is set to "manual".

Example

The following code sets the maximum property to the total frames of a Flash application that's loading:

pBar.maximum = _totalframes;

See also

ProgressBar.minimum, ProgressBar.mode


ProgressBar.minimum

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.minimum

Description

Property; the smallest progress value for the progress bar when the ProgressBar.mode property is set to "manual".

Example

The following code sets the minimum value for the progress bar:

pBar.minimum = 0;

See also

ProgressBar.maximum, ProgressBar.mode


ProgressBar.mode

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.mode

Description

Property; the mode in which the progress bar loads content. This value can be one of the following: "event", "polled", or "manual". The most commonly used modes are "event" and "polled". These modes use the source parameter to specify a loading process that either emits progress and complete events, like a Loader component (event mode), or exposes getBytesLoaded and getsBytesTotal methods, like a MovieClip object (polled mode). You can also use the ProgressBar component in manual mode by manually setting the maximum, minimum, and indeterminate properties along with calls to the ProgressBar.setProgress() method.

A Loader object should be used as the source in event mode. Any object that exposes getBytesLoaded() and getBytesTotal() methods can be used as a source in polled mode. (Including a custom object or the _root object)

Example

The following code sets the progress bar to event mode:

pBar.mode = "event";


ProgressBar.percentComplete

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.percentComplete

Description

Property (read-only); returns the percentage of completion of the process. This value is floored. The following is the formula used to calculate the percentage:

100*(value-minimum)/(maximum-minimum)

Example

The following code sends the value of the percentComplete property to the Output panel:

trace("percent complete = " + pBar.percentComplete);


ProgressBar.progress

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(progress){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.progress = function(eventObject){
  ...
}
pBarInstance.addEventListener("progress", listenerObject)

Event Object

In addition to the standard event object properties, there are two additional properties defined for the ProgressBar.progress event: current (the loaded value equals total), and total (the total value).

Description

Event; broadcast to all registered listeners whenever the value of a progress bar changes. This event is only broadcast when ProgressBar.mode is set to "manual" or "polled".

The first usage example uses an on() handler and must be attached directly to a ProgressBar component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the instance myPBar, sends "_level0.myPBar" to the Output panel:

on(progress){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (pBarInstance) dispatches an event (in this case, progress) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example creates a listener object, form, and defines a progress event handler on it. The form listener is registered to the pBar instance in the last line of code. When the progress event is triggered, pBar broadcasts the event to the form listener which calls the progress callback function, as follows:

var form:Object = new Object();
form.progress = function(eventObj){
  // eventObj.target is the component which generated the change event,
  // i.e., the Progress Bar.
  trace("Value changed to " + eventObj.target.value);
}
pBar.addEventListener("progress", form);

See also

UIEventDispatcher.addEventListener()


ProgressBar.setProgress()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.setProgress(completed, total)

Parameters

completed a number indicating the amount of progress that has been made. You can use the ProgressBar.label and ProgressBar.conversion properties to display the number in percentage form or any units you choose, depending on the source of the progress bar.

total a number indicating the total progress that must be made to reach 100 percent.

Returns

A number indicating the amount of progress that has been made.

Description

Method; sets the state of the bar to reflect the amount of progress made when the ProgressBar.mode property is set to "manual". You can call this method to make the bar reflect the state of a process other than loading. The argument completed is assigned to value property and argument total is assigned to the maximum property. The minimum property is not altered.

Example

The following code calls the setProgress() method based on the progress of a Flash application's Timeline:

pBar.setProgress(_currentFrame, _totalFrames);


ProgressBar.source

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.source

Description

Property; a reference to the instance to be loaded whose loading process will be displayed. The loading content should emit a progress event from which the current and total values are retrieved. This property is used only when ProgressBar.mode is set to "event" or "polled". The default value is undefined.

The ProgressBar can be used with contents within an application, including _root.

Example

This example sets the pBar instance to display the loading progress of a loader component with the instance name loader:

pBar.source = loader;

See also

ProgressBar.mode


ProgressBar.value

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

pBarInstance.value

Description

Property (read-only); indicates the amount of progress that has been made. This property is a number between the value of ProgressBar.minimum and ProgressBar.maximum. The default value is 0.


About the RadioButton component

The RadioButton component allows you to force a user to make a single choice within a set of choices. The RadioButton component must be used in a group of at least two RadioButton instances. Only one member of the group can be selected at any given time. Selecting one radio button in a group deselects the currently selected radio button in the group. You can set the groupName parameter to indicate which group a radio button belongs to.

A radio button can be enabled or disabled. When a user tabs into a radio button group, only the selected radio button receives focus. A user can press the arrow keys to change focus within the group. In the disabled state, a radio button doesn't receive mouse or keyboard input.

A RadioButton component group receives focus if you click it or tab to it. When a RadioButton group has focus, you can use the following keys control it:

Key | Description
Up/Right | The selection moves to the previous radio button within the radio button group.
Down/Left | The selection moves to the next radio button within the radio button group.
Tab | Moves focus from the radio button group to the next component.

For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each RadioButton instance on the Stage reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring. However, the mutual exclusion of selection does not display in the live preview. If you set the selected parameter to true for two radio buttons in the same group, they both appear selected even though only the last instance created will appear selected at runtime. For more information, see RadioButton parameters.

When you add the RadioButton component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility:

mx.accessibility.RadioButtonAccImpl.enableAccessibility();

You only enable accessibility for a component once no matter how many instances you have of the component. For more information, see Creating Accessible Content.See also:

  • Using the RadioButton component
  • Customizing the RadioButton component
  • RadioButton class


Using the RadioButton component

A radio button is a fundamental part of any form or web application. You can use radio buttons wherever you want a user to make one choice from a group of options. For example, you would use radio buttons in a form to ask which credit card a customer is using to pay.

See also:

  • RadioButton parameters
  • Creating an application with the RadioButton component

RadioButton parameters

The following are authoring parameters that you can set for each RadioButton component instance in the Property inspector or in the Component Inspector panel:

label sets the value of the text on the button; the default value is Radio Button.

data is the value associated with the radio button. There is no default value.

groupName is the group name of the radio button. The default value is radioGroup.

selected sets the initial value of the radio button to selected (true) or unselected (false). A selected radio button displays a dot inside it. Only one radio button within a group can have a selected value of true. If more than one radio button within a group is set to true, the radio button that is instantiated last is selected. The default value is false.

labelPlacement orients the label text on the button. This parameter can be one of four values: left, right, top, or bottom; the default value is right. For more information, see RadioButton.labelPlacement.

You can write ActionScript to set additional options for RadioButton instances using the methods, properties, and events of the RadioButton class. For more information, see RadioButton class.

Creating an application with the RadioButton component

The following procedure explains how to add RadioButton components to an application while authoring. In this example, the radio buttons are used to present a yes or no question, "Are you a Flashist?". The data from the radio group is displayed in a TextArea component with the instance name theVerdict.

To create an application with the RadioButton component, do the following:

  1. Drag two RadioButton components from the Components panel to the Stage.
  2. Select one of the radio buttons and in the Component Inspector panel do the following:
    • Enter Yes for the label parameter.
    • Enter Flashist for the data parameter.
  3. Select the other radio button and in the Component Inspector panel do the following:
    • Enter No for the label parameter.
    • Enter Anti-Flashist for the data parameter.
  4. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code:
    flashistListener = new Object();
flashistListener.click = function (evt){
    theVerdict.text = evt.target.selection.data
}
radioGroup.addEventListener("click", flashistListener);

    The last line of code adds a click event handler to the radioGroup radio button group. The handler sets the text property of the TextArea component instance theVerdict to the value of the data property of the selected radio button in the radioGroup radio button group. For more information, see RadioButton.click.


Customizing the RadioButton component

You can transform a RadioButton component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()).

The bounding box of a RadioButton component is invisible and also designates the hit area for the component. If you increase the size of the component, you also increase the size of the hit area.

If the component's bounding box is too small to fit the component label, the label clips to fit.

See also:

  • Using styles with the RadioButton component
  • Using skins with the RadioButton component

Using styles with the RadioButton component

You can set style properties to change the appearance of a RadioButton. If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

A RadioButton component uses the following Halo styles:l

Style | Description
themeColor | The background of a component. This is the only color style that doesn't inherit its value. Possible values are "haloGreen", "haloBlue", and "haloOrange".
color | The text of a component label.
disabledColor | The disabled color for text.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style; either "normal", or "italic".
fontWeight | The font weight; either "normal", or "bold".

Using skins with the RadioButton component

The RadioButton component can be skinned while authoring by modifying the component's symbols in the library. The skins for the RadioButton component are located in the following folder in the library of HaloTheme.fla or SampleTheme.fla: Flash UI Components 2/Themes/MMDefault/RadioButton Assets/States. See About skinning components.

If a radio button is enabled and unselected, it displays its roll-over state when a user moves the pointer over it. When a user clicks an unselected radio button, the radio button receives input focus and displays its false pressed state. When a user releases the mouse, the radio button displays its true state and the previously selected radio button within the group returns to its false state. If a user moves the pointer off a radio button while pressing the mouse, the radio button's appearance returns to its false state and it retains input focus.

If a radio button or radio button group is disabled it displays its disabled state, regardless of user interaction.

If you use the UIObject.createClassObject() method to create a RadioButton component instance dynamically, you can also skin the component dynamically. To skin a RadioButton component dynamically, pass skin properties to the UIObject.createClassObject() method. For more information, see About skinning components. The skin properties indicate which symbol to use to display a component.

A RadioButton component uses the following skin properties:

Name | Description
falseUpIcon | The unchecked state. The default value is radioButtonFalseUp.
falseDownIcon | The pressed-unchecked state. The default value is radioButtonFalseDown.
falseOverIcon | The over-unchecked state. The default value is radioButtonFalseOver.
falseDisabledIcon | The disabled-unchecked state. The default value is radioButtonFalseDisabled.
trueUpIcon | The checked state. The default value is radioButtonTrueUp.
trueDisabledIcon | The disabled-checked state. The default value is radioButtonTrueDisabled.


RadioButton class

Inheritance UIObject > UIComponent > SimpleButton > Button > RadioButton

ActionScript Package Name mx.controls.RadioButton

The properties of the RadioButton class allow you at runtime to create a text label and position it in relation to the radio button. You can also assign data values to radio buttons, assign them to groups, and select them based on data value or instance name.

Setting a property of the RadioButton class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

The RadioButton component uses the FocusManager to override the default Flash Player focus rectangle and draw a custom focus rectangle with rounded corners. For information about creating focus navigation, see Creating custom focus navigation.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.RadioButton.version);

Note: The following code returns undefined: trace(myRadioButtonInstance.version);.

Method summary for the RadioButton class

Inherits all methods from UIObject, UIComponent, SimpleButton, and Button class.

Property summary for the RadioButton class

Property | Description
RadioButton.data | The value associated with a radio button instance.
RadioButton.groupName | The group name for a radio button group or radio button instance.
RadioButton.label | The text that appears next to a radio button.
RadioButton.labelPlacement | The orientation of the label text in relation to a radio button.
RadioButton.selected | Sets the state of the radio button instance to selected and deselects the previously selected radio button.
RadioButton.selectedData | Selects the radio button in a radio button group with the specified data value.
RadioButton.selection | A reference to the currently selected radio button in a radio button group.

Inherits all properties from UIObject, UIComponent, SimpleButton, and the Button class

Event summary for the RadioButton class

Event | Description
RadioButton.click | Triggered when the mouse is pressed over a button instance.

Inherits all events from UIObject, UIComponent, SimpleButton, and Button class


RadioButton.click

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(click){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.click = function(eventObject){
  ...
}
radioButtonGroup.addEventListener("click", listenerObject)

Description

Event; broadcast to all registered listeners when the mouse is clicked (pressed and released) over the radio button or if the radio button is selected by using the arrow keys. The event is also broadcast if the Spacebar or arrow keys are pressed when a radio button group has focus, but none of the radio buttons in the group are selected.

The first usage example uses an on() handler and must be attached directly to a RadioButton component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the radio button myRadioButton, sends "_level0.myRadioButton" to the Output panel:

on(click){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (radioButtonInstance) dispatches an event (in this case, click) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. The event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example, written on a frame of the Timeline, sends a message to the Output panel when a radio button in the radioGroup is clicked. The first line of code creates a listener object called form. The second line defines a function for the click event on the listener object. Inside the function is a trace action that uses the event object that is automatically passed to the function, in this example eventObj, to generate a message. The target property of an event object is the component that generated the event. You can access instance properties from the target property (in this example, the RadioButton.selection property is accessed) The last line calls the UIEventDispatcher.addEventListener() method from radioGroup and passes it the click event and the form listener object as parameters, as in the following:

form = new Object();
form.click = function(eventObj){
  trace("The selected radio instance is " + eventObj.target.selection);
}
radioGroup.addEventListener("click", form);

The following code also sends a message to the Output panel when radioButtonInstance is clicked. The on() handler must be attached directly to radioButtonInstance, as in the following:

on(click){
  trace("radio button component was clicked");
}


RadioButton.data

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

radioButtonInstance.data

Description

Property; specifies the data to associate with a radio button instance. Setting this property overrides the data parameter value set while authoring in the Property inspector or in the Component Inspector panel. The data property can be any data type.

Example

The following example assigns the data value "#FF00FF" to the radioOne radio button instance:

radioOne.data = "#FF00FF";


RadioButton.groupName

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

radioButtonInstance.groupName
radioButtonGroup.groupName

Description

Property; sets the group name for a radio button instance or group. You can use this property to get or set a group name for a radio button instance or a group name for a radio button group. Calling this method overrides the groupName parameter value set while authoring. The default value is "radioGroup".

Example

The following example sets the group name of a radio button instance to "colorChoice" and then changes the group name to "sizeChoice". To test this example, place a radio button on the Stage with the instance name myRadioButton and enter the following code on Frame 1:

myRadioButton.groupName = "colorChoice";
trace(myRadioButton.groupName);
colorChoice.groupName = "sizeChoice";
trace(colorChoice.groupName);


RadioButton.label

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

radioButtonInstance.label

Description

Property; specifies the text label for the radio button. By default, the label appears to the right of the radio button. Calling this method overrides the label parameter specified while authoring. If the label text is too long to fit within the bounding box of the component, the text clips.

Example

The following example sets the label property of the instance radioButton:

radioButton.label = "Remove from list";


RadioButton.labelPlacement

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

radioButtonInstance.labelPlacement
radioButtonGroup.labelPlacement

Description

Property; a string that indicates the position of the label in relation to a radio button. You can set this property for an individual instance, or for a radio button group. If you set the property for a group, the label is placed in the appropriate position for each radio button in the group.

The following are the four possible values:

  • "right" The radio button is pinned to the upper left corner of the bounding area. The label is set to the right of the radio button.
  • "left" The radio button is pinned to the upper right corner of the bounding area. The label is set to the left of the radio button.
  • "bottom" The label is placed below the radio button. The radio button and label grouping are centered horizontally and vertically. If the bounding box of the radio button isn't large enough, the label will clip.
  • "top" The label is placed above the radio button. The radio button and label grouping are centered horizontally and vertically. If the bounding box of the radio button isn't large enough, the label will clip.

Example

The following code places the label to the left of each radio button in the radioGroup:

radioGroup.labelPlacement = "left";


RadioButton.selected

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

radioButtonInstance.selected
radioButtonGroup.selected

Description

Property; a Boolean value that sets the state of the radio button to selected (true) and deselects the previously selected radio button, or sets the radio button to deselected (false).

Example

The first line of code sets the mcButton instance to true. The second line of code returns the value of the selected property, as follows:

mcButton.selected = true;
trace(mcButton.selected);


RadioButton.selectedData

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

radioButtonGroup.selectedData

Description

Property; selects the radio button with the specified data value and deselects the previously selected radio button. If the data property is not specified for a selected instance, the label value of the selected instance is selected and returned. The selectedData property can be of any data type.

Example

The following example selects the radio button with the value "#FF00FF" from the radio group colorGroup and sends the value to the Output panel:

colorGroup.selectedData = "#FF00FF";
trace(colorGroup.selectedData);


RadioButton.selection

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

radioButtonInstance.selection
radioButtonGroup.selection

Description

Property; behaves differently if you get or set the property. If you get the property, it returns the object reference of the currently selected radio button in a radio button group. If you set the property, it selects the specified radio button (passed as an object reference) in a radio button group and deselects the previously selected radio button.

Example

The following example selects the radio button with the instance name color1 and sends its instance name to the Output panel:

colorGroup.selection = color1;
trace(colorGroup.selection._name)


About the RDBMSResolver component (Flash Professional only)

You use resolver components in combination with the DataSet component (part of the data management functionality in the Macromedia Flash data architecture). The resolver components enable you to convert changes made to the data within your application into a format that is appropriate for the external data source that you are updating. These components have no visual appearance at runtime.

The RDBMSResolver component combines changes made to a DataSet component and user settings to create an XML update packet that can be parsed by an external data source such as a web service, Servlet, or ASP page to update a relational database. The XML contains the necessary information and formatting for updating any standard SQL relational database. The updates from the RDBMSResolver component are communicated to the database through a connector object. The resolver component is connected to a DataSet component's DeltaPacket property, sends its own update packet to a connector, receives server errors back from the connector, and communicates them back to the DataSet component—all using bindable properties.

For more information about the Flash data architecture, see Resolver components (Flash Professional only).For more information about resolving data to a relational database, see Resolving data to a relational database (Flash Professional only).

Note: You can use the RDBMSResolver to send data updates to any external data source that can parse XML and generate SQL statements against a database; for example, an ASP page, a Java servlet, or a ColdFusion component.

See also:

  • RDBMSResolver class

Using the RDBMSResolver component (Flash Professional only)

The RDBMSResolver component is used only when your Flash application contains a DataSet component and must send an update back to the data source. This component resolves data that you want to return to a relational database.

RDBMSResolver component parameters

The following are authoring parameters that you can set for each RDBMSResolver component instance, in the Component Inspector panel Parameters tab:

TableName String representing the table name in the XML for the database table to be updated. This should be the same value as the input value for the Resolver.fieldInfo item to be updated. If no updates to this field exist, this value should be blank, which is the default value.

UpdateMode Enumerator that determines the way key fields are identified during the generation of the XML update packet. The default value is umUsingKey. Possible values are as follows:

  • umUsingAll Uses the old values of all of the fields modified to identify the record to be updated. This is the safest value to use for updating, because it guarantees that another user has not modified the record since you retrieved it. However, this approach is time consuming and generates a larger update packet.
  • umUsingModified Uses the old values of all of the fields modified to identify the record to be updated. This value guarantees that another user has not modified the same fields in the record since you retrieved it.
  • umUsingKey This is the default value for this property. This setting uses the old value of the key fields. This implies an "optimistic concurrency" model, which most database systems today employ, and guarantees that you are modifying the same record that you retrieved from the database. Your changes overwrites any other user's changes to the same data.

NullValue String representing a null field value. This is customizable to prevent it from being confused with an empty string ("") or another valid value. The default value is {_NULL_}.

FieldInfo Collection representing one or more key fields that uniquely identify the records. If your data source is a database table, then it should have one or more fields that uniquely key the records within it. Additionally, some fields may have been calculated or joined from other tables. Those fields must be identified so that the key fields can be set within the XML update packet, and so that any fields that should not be updated are omitted from the XML update packet.

The RDBMSResolver component contains a FieldInfo property for this purpose. This collection property lets you define an unlimited number of fields with properties that identify fields that require special handling. Each FieldInfo item in the collection contains three properties:

  • FieldName Name of a field. This should map to a field in the DataSet component.
  • OwnerName Optional value used to identify fields not "owned" by the same table defined in the resolver component's TableName parameter. If this value is the same value as the TableName parameter or is blank, usually the field is included in the XML update packet. If it is a different value, this field is excluded from the update packet.
  • IsKey Boolean property that you should set to true so that all key fields for the table are updated.

The following example shows FieldInfo items that are created to update fields in the Customer table. You must identify the key fields in the customer table. The customer table has a single key field, id; therefore, you should create a field item with the following values:

FieldName = "id"
OwnerName = <--! leave this value blank -->
IsKey = "true"

Also, the custType field is added using a join in the query. This field should be excluded from the update, so you create a field item with the following values:

FieldName = "custType"
OwnerName = "JoinedField"
IsKey = "false"

When the field items are defined, Flash Player can use them to automatically generate the complete XML, which is used to update a table.

Note: The FieldInfo parameter makes use of a feature in Flash called the Collection Editor. When you select the FieldInfo parameter, the Collection Editor dialog box opens. Using this dialog box, you can add new FieldInfo items and set their fieldName, ownerName, and isKey properties from one location.

Common workflow for the RDBMSResolver component

The typical workflow for the RDBMSResolver component is as follows.

To use an RDBMSResolver component:

  1. Add two instances of the WebServicesConnector component and one instance each of the DataSet and RDBMSResolver components to your application and give them instance names.
  2. Select the first WebServicesConnector component and use the Parameters tab of the Component Inspector panel to enter the WSDLURL for a web service that exposes data from an external data source.

    Note: The web service must return an array of records to be bound to the data set.

  3. Use the Bindings tab of the Component Inspector panel to bind the WebServicesConnector component to the DataSet component.
  4. Select the DataSet component, and use the Bindings tab of the Component Inspector panel to bind data elements (DataSet fields) to the visual components in your application.
  5. Bind the DataSet component to the RDBMSResolver component.

    Note: The update instructions are sent from the DataSet component to the RDBMSResolver component when the applyUpdates method of the DataSet component is called.

  6. Select the RDBMSResolver component and bind it to the second WebServiceConnector component to send the data back to your external data source.
  7. Add a trigger to initiate the data binding operation: use the Trigger Data Source behavior attached to a button, or add ActionScript.

    Note: In addition to these steps, you an also create bindings to apply the result packet sent back from the server to the data set via the RDBMSResolver component.

For a step-by-step example that resolves data to a relational database using the RDBMSResolver component, see Web Service Tutorial: Update the Stock Quote Web Service (Flash Professional Only).


RDBMSResolver class

Inheritance MovieClip

ActionScript Package Name mx.data.components.RDBMSResolver

Property summary for the RDBMSResolver component

Property | Description
RDBMSResolver.deltaPacket | A copy of the DataSet component's DeltaPacket property.
RDBMSResolver.fieldInfo | An unlimited number of fields with properties that identify DataSet fields requiring special handling as either a key field or a nonupdatable field.
RDBMSResolver.nullValue | Indicator that a field's value is null.
RDBMSResolver.tableName | The table name put in the XML for the database table to be updated.
RDBMSResolver.updateMode | The value that determines how key fields are identified when the XML update packet is being generated.
RDBMSResolver.updatePacket | A copy of the connector updatePacket property containing the latest XML-formatted data for return from the connector to the DataSet component after the server has received this application's request to update.
RDBMSResolver.updateResults | A copy of the connector's Results property, which returns any XML-formatted errors or updates for the DataSet component.

Method summary for the RDBMSResolver component

Method | Description
RDBMSResolver.addFieldInfo() | Adds a new item to the fieldInfo collection, used for setting up a resolver component dynamically at runtime, rather than using the Component inspector in the authoring environment.

Event summary for the RDBMSResolver component

Event | Description
RDBMSResolver.beforeApplyUpdates | Defined in your application; called by the resolver component to make custom modifications to the XML of the updatePacket property before it is bound to the connector.
RDBMSResolver.reconcileResults | Defined in your application; called by the resolver component to reconcile the updates between the updatePacket property sent to the server and the updatePacket property returned from the server.
RDBMSResolver.reconcileUpdates | Defined in your application; called by the resolver component to reconcile the update received by the server and the pending update.


RDBMSResolver.addFieldInfo()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.addFieldInfo("fieldName", "ownerName", "isKey")

Parameters

fieldName String; provides the name of the field this information object describes.

ownerName String; provides the name of the table that owns this field. May be left blank ("") if it is the same as the resolver instance's tablename property.

isKey Boolean; indicates whether this field is a key field.

Returns

None.

Description

Method; adds a new item to the XML fieldInfo collection in the update Packet. Use this method if you must set up a resolver component dynamically at runtime, rather than using the Component inspector in the authoring environment.

Example

The following example creates a resolver component and provides the name of the table, the name of the key field, and prevents the personTypeName field from being updated:

var myResolver:RDBMSResolver = new RDBMSResolver();
myResolver.tableName = "Customers";
// Sets up the id field as a key field
// and the personTypeName field so it won't be updated.
myResolver.addFieldInfo("id", "", true);
myResolver.addFieldInfo("personTypeName", "JoinedField", false);
// Sets up the data bindings
//...


RDBMSResolver.beforeApplyUpdates

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.beforeApplyUpdates(eventObject)

Parameters

eventObject Resolver event object; describes the customizations to the XML packet before the update is sent though the connector to the database. This resolver event object should contain the following properties:

Property | Description
target | Object; resolver firing this event.
type | String; name of the event.
updatePacket | XML object; XML object about to be applied.

Returns

None.

Description

Property; property of type deltaPacket that receives a deltaPacket to be translated into an xupdatePacket, and outputs a deltaPacket from any server results placed into the updateResults property. This event handler provides a way for you to make custom modifications to the XML before sending the updated data to a connector.

Messages in the updateResults property are treated as errors. This means that a delta with messages is added to the deltaPacket again so it can be resent the next time the deltaPacket is sent to the server. You must write code that handles deltas that have messages so that the messages are presented to the user and the deltas can be modified before being added to the next deltaPacket.

Example

The following example adds the user authentication data to the XML packet:

on (beforeApplyUpdates) {
   // add user authentication data
   var userInfo = new XML( ""+getUserId()+ ""+getPassword()+"" );
   updatePacket.firstChild.appendChild( userInfo );
}


RDBMSResolver.deltaPacket

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.deltaPacket

Description

Property; property of type deltaPacket that receives a deltaPacket to be translated into an updatePacket, and outputs a deltaPacket from any server results placed into the updateResults property.

Messages in the updateResults property are treated as errors. This means that a delta with messages is added to the deltaPacket again so it can be resent the next time the deltaPacket is sent to the server. You must write code that handles deltas that have messages so that the messages are presented to the user and the deltas can be modified before being added to the next deltaPacket.


RDBMSResolver.fieldInfo

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.fieldInfo

Description

Property; property of type Collection specifies a collection of an unlimited number of fields with properties that identify DataSet fields that require special handling, either because the field is a key field or the field is not able to be updated. Each FieldInfo item in the collection contains three properties:

Property | Description
FieldName | Name of the special-case field. This field name should map to a field name in the DataSet.
OwnerName | This optional property is the name of the owner of this field if this field is not "owned" by the same table defined in the component TableName parameter. If this is filled in with the same value as that parameter or left blank, usually the field is included in the XML update packet. If filled in differently, this field is excluded from the update packet.
IsKey | Boolean value set to true for all key fields for the table to be updated.


RDBMSResolver.nullValue

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.deltaPacket

Description

Property; property of type String used to provide a null value for a field's value. This is customizable to prevent it from being confused with an empty string ("") or another valid value. The default string is {_NULL_}.


RDBMSResolver.reconcileResults

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.reconcileResults(eventObject)

Parameters

eventObject Resolver event object; describes the event object used to compare two updatePackets This resolver event object should contain the following properties:

Property | Description
target | Object; resolver firing this event.
type | String; name of the event.

Returns

None.

Description

Event; called by the resolver component to compare two packets after results have been received from the server and have been applied to the deltaPacket.

A single updateResults packet can contain both results of operations that were in the deltaPacket, and information about updates performed by other clients. When a new updatePacket is received, the operation results and database updates are split into two updatePackets and placed separately into the deltaPacket property. The reconcileResults event is fired just before the deltaPacket containing the operation results is sent using data binding.

Example

The following example reconciles two updatePackets and returns and clears the updates on success:

on (reconcileResults) {
     // examine results
     if( examine( updateResults ))
       myDataSet.purgeUpdates();
     else
       displayErrors( results );
}


RDBMSResolver.reconcileUpdates

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.reconcileUpdates(eventObject)

Parameters

eventObject Resolver event object; describes the customizations to the XML packet before the update is sent through the connector to the database. This resolver event object should contain the following properties:

Property | Description
target | Object; resolver firing this event.
type | String; name of the event.

Returns

None.

Description

Event; called by the resolver component when results have been received from the server after applying the updates from a deltaPacket. A single updateResults packet can contain both results of operations that were in the deltaPacket, and information about updates that were performed by other clients. When a new updatePacket is received, the operation results and database updates are split into two deltaPackets, which are placed separately into the deltaPacket property. The reconcileUpdates event is fired just before the deltaPacket containing any database updates is sent using data binding

Example

The following example reconciles two results and clears the updates on success:

on (reconcileUpdates) {
     // examine results
     if( examine( updateResults ))
       myDataSet.purgeUpdates();
     else
       displayErrors( results );


RDBMSResolver.tableName

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.deltaPacket

Description

Property; property of type String used to represent the table name in the XML for the database table to be updated. This also determines which fields to send in the updatePacket. To make this determination, the resolver component compares the value of this property to the value provided for the fieldInfo.ownerName property. If a field has no entry in the fieldInfo collection property, the field is placed into the updatePacket. If a field has an entry in the fieldInfo collection property, and the ownerName property value is blank or identical to the resolver component's tableName property, the field is placed into the updatePacket. If a field has an entry in the fieldInfo collection property, and the ownerName property value is not blank and is different from the resolver component's tableName property, the field is not placed into the updatePacket.


RDBMSResolver.updateMode

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.deltaPacket

Description

Property; property containing several values that determine how key fields are identified when the XML update packet is being generated. The following three strings are values for this property:

Value | Description
umUsingAll | Uses the old values of all of the fields modified to identify the record to be updated. This is the safest value to use for updating, because it guarantees that another user has not modified the all of the record since you retrieved it. However, this approach is more time consuming and generates a larger update packet.
umUsingModified | Uses the old values of all of the fields modified to identify the record to be updated. This value guarantees that another user has not modified the same fields in the record since you retrieved it.
umUsingKey | This is the default value for this property. Uses the old value of the key fields. This implies an "optimistic concurrency" model, which most database systems today employ and guarantees that you are modifying the same record that you retrieved from the database. Your changes will overwrite any other user's changes to the same data.


RDBMSResolver.updatePacket

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.deltaPacket

Description

Description

Property; property of type XML used to bind to a connector property that transmits the translated update packet of changes back to the server so the source of the data can be updated. This is an XML document containing the packet of DataSet changes.


RDBMSResolver.updateResults

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.deltaPacket

Description

Property; property of type deltaPacket that contains the results of an update returned from the server through a connector. Use this property to transmit errors and updated data from the server to a DataSet; for example, when the server assigns new IDs for an auto-assigned field. Bind this property to a connector's Results property so that it can receive the results of an update and transmit the results back to the DataSet.

Messages in the updateResults property are treated as errors. This means that a delta with messages is added to the deltaPacket again so it can be resent the next time the deltaPacket is sent to the server. You must write code that handles deltas that have messages so that the messages are presented to the user and the deltas can be modified before being added to the next deltaPacket.


About the Remote Procedure Call (RPC) Component API

ActionScript Class Name mx.data.components.RPC

The Remote Procedure Call (RPC) Component API is an interface (a set of methods, properties, and events) that can be implemented by a Flash MX 2004 v2 component. The RPC Component API defines an easy way to send parameters to, and receive results from, an external resource such as a web service.

Components that implement the RPC API include the WebServiceConnector and XMLConnector components. These components act as connectors between an external data source, such as a web service or XML file, and a UI component in your application.

An RPC component has the ability to call a single external function, pass in parameters, and receive results. The component can call that same function multiple times. To call multiple functions, you must use multiple components.

Method summary for the RPC Component class

Method | Description
RPC.trigger() | Initiates a remote procedure call.

Property summary for the RPC Component class

Property | Description
RPC.multipleSimultaneousAllowed | Indicates whether multiple calls can take place at the same time.
RPC.params | Specifies data that will be sent to the server when the next trigger() operation is executed.
RPC.results | Identifies data that was received from the server as a result of the a trigger() operation.
RPC.suppressInvalidCalls | Indicates whether to suppress a call if parameters are invalid.

Event summary for the RPC Component class

Event | Description
RPC.result | Broadcast when a Remote Procedure Call completes successfully.
RPC.send | Broadcast when the trigger() function is in process, after the parameter data has been gathered but before the data is validated and the Remote Call is initiated.
RPC.status | Broadcast when a Remote Procedure Call is initiated, to inform the user of the status of the operation.


RPC.multipleSimultaneousAllowed

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

componentInstance.multipleSimultaneousAllowed;

Description

Property; indicates whether multiple calls can take place at the same time. If false, then the trigger() function will perform a call if another call is already in progress. A status event will be emitted, with the code CallAlreadyInProgress. If true, then the call will take place.

When multiple calls are simultaneously in progress, there is no guarantee that they will complete in the same order as they were triggered. Also, Flash Player may place limits on the number of simultaneous network operations. This limit varies by version and platform.


RPC.params

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

componentInstance.params;

Description

Property; specifies data that will be sent to the server when the next trigger() operation is executed. Each RPC component defines how this data is used, and what the valid types are.


RPC.result

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

componentInstance.addEventListener("result", myListenerObject);

Description

Event; broadcasts when an Remote Procedure Call operation successfully completes.

The parameter to the event handler is an object with the following fields:

  • type: the string "result"
  • target: a reference to the object that emitted the event, for example a WebServiceConnector component

You can retrieve the actual result value using the results property.


RPC.results

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

componentInstance.results;

Description

Property; identifies data that was received from the server as a result of a trigger() operation. Each RPC component defines how this data is fetched, and what the valid types are. This data appears when the RPC operation has successfully completed, as signalled by the result event. It is available until the component is unloaded, or until the next RPC operation.

It is possible for the returned data to be very large. You can manage this in 2 ways:

  • Select an appropriate movie clip, Timeline, or screen as the parent for the RPC component. The component's storage will become available for garbage collection when the parent goes away.
  • In ActionScript, you can assign null to this property at any time.


RPC.send

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

componentInstance.addEventListener("send", myListenerObject);

Description

Event; broadcasts during the processing of a trigger() operation, after the parameter data has been gathered but before the data is validated and the Remote Procedure Call is initiated. This is a good place to put code that will modify the parameter data before the call.

The parameter to the event handler is an object with the following fields:

  • type: the string "send"
  • target: a reference to the object that emitted the event, for example a WebServiceConnector component

You can retrieve or modify the actual parameter values using the params property.


RPC.status

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

componentInstance.addEventListener("status", myListenerObject);

Description

Event; broadcasts when a Remote Procedure Call is initiated, to inform the user of the status of the operation.

The parameter to the event handler is an object with the following fields:

  • type: the string "status"
  • target: a reference to the object that emitted the event; for example, a WebServiceConnector component
  • code: a string giving the name of the specific condition that occurred.
  • data: an object whose contents depend on the code.

The following are the codes and associated data available for the status event:

Code | Data | Description
StatusChange | {callsInProgress:nnn} | This event is emitted whenever a web service call starts or finishes. The item "nnn" gives the number of calls currently in progress.
CallAlreadyInProgress | no data | This event is emitted if (a) the trigger() function is called, and (b) multipleSimultaneousAllowed is false, and (c) a call is already in progress. After this event occurs, the attempted call is considered complete, and there will be no "result" or "send" event.
InvalidParams | no data | This event is emitted if the trigger() function found that the "params" property did not contain valid data. If the "suppressInvalidCalls" property is true, then the attempted call is considered complete, and there will be no "result" or "send" event.


RPC.suppressInvalidCalls

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

componentInstance.suppressInvalidCalls;

Description

Property; indicates whether to suppress a call if parameters are invalid. If true, then the trigger() function will not perform a call if the bound parameters fail the validation. A "status" event will be emitted, with the code InvalidParams. If false, then the call will take place, using the invalid data as required.


RPC.trigger()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

componentInstance.trigger();

Description

Method; initiates an Remote Procedure Call. Each RPC component defines exactly what this involves. If the operation is successful, the results of the operation will appear in the RPC component's results property.

The trigger() method performs the following steps:

  1. If any data is bound to the params property, the method execute all the bindings to ensure that up-to-date data is available. This also causes data validation to occur.
  2. If the data is not valid and suppressInvalidCalls is set to true, the operation is discontinued.
  3. If the operation continues, the send event is emitted.
  4. The actual remote call is initiated via the connection method indicated (for example, HTTP).


About the Screen class (Flash Professional only)

The Screen class is the base class for screens you create in the Screen Outline pane in Flash MX Professional 2004. Screens are high-level containers for creating applications and presentations. For an overview of working of working with screens, see Working with Screens (Flash Professional Only).

The Screen class has two primary subclasses: Slide and Form.

The Slide class provides the runtime behavior for slide presentations. The Slide class contains built-in navigation and sequencing capabilities, as well as the ability to easily attach transitions between slide using Behaviors. Slide objects maintain a notion of "state", and allow the user to advance to the next or previous slide/state: when the next slide is shown, the previous slide is hidden. For more information about using the Slide class to control slide presentations, see Slide class (Flash Professional only).

The Form class provides the runtime environment for form applications. Forms have the ability to overlay and be containers for, or be contained by, other components. Unlike slides, forms don't provide any sequencing or navigation capabilities. For more information on using the Form class, see Form class (Flash Professional only).

The Screen class provides functionality common to both slides and forms.

Screens know how to manage their children Every screen comes with a built-in property that is a collection of screens as children. This collection is determined by the layout of the screen hierarchy in the Screens Pane. Screens can have any number of children (including zero), which themselves can have children.

Screens can hide/show their children Because screens are, essentially, a collection of nested movie clips, a screen can control the visibility of its children. For form applications, all of a screen's children are visible by default at the same time; for slide presentations, individual screens are typically shown one-at-a-time.

Screens broadcast events For example, you can trigger a sound to play, or start playing some video, when a particular screen becomes visible.

See also:

  • Loading external content into screens (Flash Professional only)
  • Screen class (API)


Loading external content into screens (Flash Professional only)

The Screen class extends the Loader class (see Loader component), which provides the ability to easily manage and load external SWF files (and JPEG files). The Loader class contains a property called contentPath which specifies the URL of an external SWF or JPEG, or the linkage identifier of a movie clip in the Library.

Using this feature, you can load external screen tree (or any external SWF file) as a child of any screen node. This provides a useful way of modularizing your screens-based movies and dividing them into multiple, separate SWF files.

For example, suppose you had a slide presentation in which three people were each contributing a single section. You could ask each presenter to each create a separate slide presentation (SWF). You would then create a "master slide presentation" that contained three placeholder slides, one for each slide presentation being created by the presenters. For each placeholder slide, you could point its contentPath property to each of the SWF files.

For example, the "master" slide presentation could be arranged as shown in the following illustration:

"Master" SWF slide presentation structure

Suppose that presenters have provided you with three SWF files, speaker_1.swf, speaker_2.swf, and speaker_3.swf. You could easily assemble the overall presentation by pointing contentPath property for each placeholder slide, either using ActionScript, or by setting the Property inspector's contentPath property for each slide.

Speaker_1.contentPath = speaker_1.swf;
Speaker_2.contentPath = speaker_2.swf;
Speaker_3.contentPath = speaker_3.swf;

You can also set the contentPath property for each slide using the Property inspector. Note that, by default, when you set a slide's contentPath in the Property inspector (or with code, as shown above), the specified SWF file will load as soon as the "master presentation" SWF file has loaded. To reduce initial load time, consider setting the contentPath property within an on(reveal) handler attached to each slide.

// Attached to Speaker_1 slide
on(reveal) {
  this.contentPath="speaker_1.swf";
}

Alternatively, you could set to false the slide's autoLoad property (inherited from the Loader class), and then call the load() method on the slide (also inherited from the Loader class) when the slide has been revealed.

// Attached to Speaker_1 slide
on(reveal) {
  this.load();
}

See also:

  • Referencing loaded screens with ActionScript

Referencing loaded screens with ActionScript

The Loader class creates an internal movie clip named contentNode into which it loads the SWF or JPEG file specified by the contentPath property. This movie clip, in effect, adds an extra screen node between the "placeholder" slide (that you created in the "master" presentation above) and the first slide in the loaded slide presentation.

For example, suppose that the SWF file created for the Speaker_1 slide placeholder (see above illustration) had the following structure, as shown in the Screen Outline pane:

"Speaker 1" SWF slide presentation structure

At runtime, when the Speaker 1 SWF file is loaded into the placeholder slide, the overall slide presentation would now have the following structure:

Structure of "master" and "speaker" presentation (runtime)

The properties and methods of the Screen, Slide and Form classes "ignore" this contentHolder node, as much as possible. That is, referring to the illustration above, the slide named MyPresentation (and its subslides) is part of the contiguous slide tree rooted at the Presentation slide, and is not treated as a separate subtree.


Screen class (API)

Inheritance UIObject > UIComponent > View > Loader > Screen

ActionScript Class Name mx.screens.Screen

Method summary for the Screen class

Method | Description
Screen.getChildScreen() | Returns the child screen of this screen at a particular index.

Inherits all methods from UIObject, UIComponent, View, and Loader component.

Property summary for the Screen class

Property | Description
Screen.currentFocusedScreen | Returns the screen that contains the global current focus.
Screen.indexInParent | Returns the screen's index (zero-based) in its parent screen's list of child screens.
Screen.numChildScreens | Returns the number of child screens contained by the screen.
Screen.parentIsScreen | Returns a Boolean (true or false) value that indicates whether the screen's parent object is itself a screen.
Screen.rootScreen | Returns the root screen of the (sub)-tree that contains the screen.

Inherits all properties from UIObject, UIComponent, View, and Loader component.

Event summary for the Screen class

Event | Description
Screen.allTransitionsInDone | Broadcast when all "in" transitions applied to a screen have finished.
Screen.allTransitionsOutDone | Broadcast when all "out" transitions applied to a screen have finished.
Screen.mouseDown | Broadcast when the mouse button was pressed over an object (shape or movie clip) directly owned by the screen.
Screen.mouseDownSomewhere | Broadcast when the mouse button was pressed somewhere on the Stage, but not necessarily on an object owned by this screen.
Screen.mouseMove | Broadcast when the mouse is moved while over a screen.
Screen.mouseOut | Broadcast when the mouse is moved from inside the screen to outside it.
Screen.mouseOver | Broadcast when the mouse is moved from outside this screen to inside it.
Screen.mouseUp | Broadcast when the mouse button was released over an object (shape or movie clip) directly owned by the screen.
Screen.mouseUpSomewhere | Broadcast when the mouse button was released somewhere on the Stage, but not necessarily over an object owned by this screen.

Inherits all events from UIObject, UIComponent, View, and Loader component.


Screen.allTransitionsInDone

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(allTransitionsInDone) {
  // your code here
}
listenerObject = new Object();
listenerObject.allTransitionsInDone = function(eventObject){
  // insert your code here
}
screenObj.addEventListener("allTransitionsInDone", listenerObject)

Description

Event; broadcast when all "in" transitions applied to this screen have finished. The allTransitionsInDone event is broadcast by the transition manager associated with myScreen.

Example

In the following example, a button (nextSlide_btn) that's contained by the slide named mySlide is made visible once all the "in" transitions applied to mySlide have completed.

// Attached to mySlide:
on(allTransitionsInDone) {
  this.nextSlide_btn._visible = true;
}

See also

Screen.allTransitionsOutDone


Screen.allTransitionsOutDone

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(allTransitionsOutDone) {
  // your code here
}
listenerObject = new Object();
listenerObject.allTransitionsOutDone = function(eventObject){
  // insert your code here
}
screenObj.addEventListener("allTransitionsOutDone", listenerObject)

Description

Event; broadcast when all "out" transitions applied to the screen have finished. The allTransitionsOutDone event is broadcast by the transition manager associated with myScreen.

See also

Screen.currentFocusedScreen


Screen.currentFocusedScreen

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mx.screens.Screen.currentFocusedScreen

Description

Static property (read-only); returns a reference to the "leafmost" Screen object that contains the global current focus. The focus may be on the screen itself, or on a movie clip, text object, or component inside that screen. Defaults to null if there is no current focus.

Example

The following example displays the name of the currently focused screen in the Output panel.

var currentFocus:mx.screens.Screen = mx.screens.Screen.currentFocusedScreen;
trace("Current screen is: " + currentFocus._name);


Screen.getChildScreen()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myScreen.getChildScreen(index)

Parameters

childIndex A number that indicates the index (zero-based) of the child screen to return.

Returns

A Screen object.

Description

Method; returns the child Screen object of myScreen whose index is childIndex.

Example

The following example displays in the Output panel the names of all the child screens belonging to the root screen named Presentation.

for (var i:Number = 0; i < _root.Presentation.numChildScreens; i++) {
    var childScreen:mx.screens.Screen = _root.Presentation.getChildScreen(i);
    trace(childScreen._name);
}


Screen.indexInParent

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myScreen.indexInParent

Description

Property (read-only); contains the index (zero-based) of myScreen in its parent's list of subscreens.

Example

The following example displays the relative position of the screen myScreen in its parent screen's list of child screens.

var numChildren:Number = myScreen._parent.numChildScreens;
var myIndex:Number = myScreen.indexInParent;
trace("I'm child slide # " + myIndex + " out of " + numChildren + " screens.");


Screen.mouseDown

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(mouseDown) {
  // your code here
}
listenerObject = new Object();
listenerObject.mouseDown = function(eventObj){
  // insert your code here
}
screenObj.addEventListener("mouseDown", listenerObject)

Description

Event; broadcast when the mouse button was pressed over an object (for example, a shape or a movie clip) directly owned by the screen.

When the event is triggered, it automatically passes an event object (eventObj) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Example

The following code displays the name of the screen that captured the mouse event in the Output panel.

on(mouseDown) {
  trace("Mouse down event on: " + eventObj.target._name);
}


Screen.mouseDownSomewhere

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(mouseDown) {
  // your code here
}
listenerObject = new Object();
listenerObject.mouseDownSomewhere = function(eventObject){
  // insert your code here
}
screenObj.addEventListener("mouseDownSomewhere", listenerObject)

Description

Event; broadcast when the mouse button is pressed, but not necessarily over the specified screen.

When the event is triggered, it automatically passes an event object (eventObj) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.


Screen.mouseMove

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(mouseDown) {
  // your code here
}
listenerObject = new Object();
listenerObject.mouseMove = function(eventObject){
  // insert your code here
}
screenObj.addEventListener("mouseMove", listenerObject)

Description

Event; broadcast when the mouse moves while over the screen. This event is only sent when the mouse is over the bounding box of this screen.

When the event is triggered, it automatically passes an event object (eventObj) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Note: Use of this event may impact system performance and should be used judiciously.


Screen.mouseOut

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(mouseOut) {
  // your code here
}
listenerObject = new Object();
listenerObject.mouseOut = function(eventObject){
  // insert your code here
}
screenObj.addEventListener("mouseOut", listenerObject)

Description

Event; broadcast when the mouse moves from inside the screen's bounding box to outside its bounding box.

When the event is triggered, it automatically passes an event object (eventObj) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Note: Use of this event may impact system performance and should be used judiciously.


Screen.mouseOver

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(mouseDown) {
  // your code here
}
listenerObject = new Object();
listenerObject.mouseOver = function(eventObject){
  // insert your code here
}
screenObj.addEventListener("mouseOver", listenerObject)

Description

Event; broadcast when the mouse moves from outside the screen's bounding to inside its bounding box.

When the event is triggered, it automatically passes an event object (eventObj) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.

Note: Use of this event may impact system performance and should be used judiciously.


Screen.mouseUp

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(mouseUp) {
  // your code here
}
listenerObject = new Object();
listenerObject.mouseUP = function(eventObject){
  // insert your code here
}
screenObj.addEventListener("mouseUp", listenerObject)

Description

Event; broadcast when the mouse is released over the screen.

When the event is triggered, it automatically passes an event object (eventObj) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.


Screen.mouseUpSomewhere

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(mouseUpSomewhere) {
  // your code here
}
listenerObject = new Object();
listenerObject.mouseUpSomewhere = function(eventObject){
  // insert your code here
}
screenObj.addEventListener("mouseUpSomewhere", listenerObject)

Description

Event; broadcast when the mouse button is pressed, but not necessarily over the specified screen

When the event is triggered, it automatically passes an event object (eventObj) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. For more information about event objects, see Event Objects.


Screen.numChildScreens

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myScreen.numChildScreens

Description

Property (read-only); returns the number of child screens contained by myScreen.

Example

The following example displays the names of all the child screens belonging to myScreen.

var howManyKids:Number = myScreen.numChildScreens;
for(i=0; i<howManyKids; i++) {
  var childScreen = myScreen.getChildScreen(i);
  trace(childScreen._name);
}

See also

Screen.getChildScreen()


Screen.parentIsScreen

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myScreen.parentIsScreen

Description

Property (read-only): returns a Boolean (true or false) value indicating whether the specified screen's parent object is also a screen (true), or not (false). If false, then myScreen is at the root of its screen hierarchy.

Example

The following code determines if the parent object of the screen myScreen is also a screen. If so, it's assumed that myScreen is the root, or master, slide in the presentation and therefore has no sibling slides. Otherwise, if myScreen.parentIsScreen is true, then the number of myScreen's sibling slides is displayed in the Output panel.

if (myScreen.parentIsScreen) {
  trace("I have "+myScreen._parent.numChildScreens+" sibling screens");
} else {
  trace("I am the root screen and have no siblings");
}


Screen.rootScreen

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myScreen.rootScreen

Description

Property (read-only); returns the screen at the top of the screen hierarchy that contains myScreen.

Example

The following example displays the name of the root screen that contains the screen myScreen.

var myRoot:mx.screens.Screen = myScreen.rootScreen;


About the ScrollPane component

The Scroll Pane component displays movie clips, JPEG files, and SWF files in a scrollable area. You can enable scroll bars to display images in a limited area. You can display content that is loaded from a local location, or from over the internet. You can set the content for the scroll pane both while authoring and at runtime using ActionScript.

Once the scroll pane has focus, if the content of the scroll pane has valid tab stops, those markers will receive focus. After the last tab stop in the content, focus shifts to the next component. The vertical and horizontal scroll bars in the scroll pane never receive focus.

A ScrollPane instance receives focus if a user clicks it or tabs to it. When a ScrollPane instance has focus, you can use the following keys to control it:

Key | Description
Down | Content moves up one vertical line scroll.
End | Content moves to the bottom of the scroll pane.
Left | Content moves right one horizontal line scroll
Home | Content moves to the top of the scroll pane.
Page Down | Content moves up one vertical page scroll.
Page Up | Content moves down one vertical page scroll.
Right | Content moves left one horizontal line scroll
Up | Content moves down one vertical line scroll.

For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each ScrollPane instance reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring.

See also:

  • Using the ScrollPane component
  • Customizing the ScrollPane component
  • ScrollPane class


Using the ScrollPane component

You can use a scroll pane to display any content that is too large for the area into which it is loaded. For example, if you have a large image and only a small space for it in an application, you could load it into a scroll pane.

You can set up a scroll pane to allow users to drag the content within the pane by setting the scrollDrag parameter to true; a pointing hand appears on the content. Unlike most other components, events are broadcast when the mouse button is pressed and continue broadcasting until the button is released. If the contents of a scroll pane have valid tab stops, you must set scrollDrag to false otherwise each mouse interaction with the contents will invoke scroll dragging.

ScrollPane parameters

The following are authoring parameters that you can set for each ScrollPane component instance in the Property inspector or in the Component Inspector panel:

contentPath indicates the content to load into the scroll pane. This value can be a relative path to a local SWF or JPEG file, or a relative or absolute path to a file on the internet. It can also be the linkage identifier of a movie clip symbol in the library that is set to Export for ActionScript.

hLineScrollSize indicates the number of units a horizontal scroll bar moves each time an arrow button is pressed. The default value is 5.

hPageScrollSize indicates the number of units a horizontal scroll bar moves each time the track is pressed. The default value is 20.

hScrollPolicy displays the horizontal scroll bars. The value can be "on", "off", or "auto". The default value is "auto".

scrollDrag is a Boolean value that allows a user to scroll the content within the scroll pane (true) or not (false). The default value is false.

vLineScrollSize indicates the number of units a vertical scroll bar moves each time an arrow button is pressed. The default value is 5.

vPageScrollSize indicates the number of units a vertical scroll bar moves each time the track is pressed. The default value is 20.

vScrollPolicy displays the vertical scroll bars. The value can be "on", "off", or "auto". The default value is "auto".

You can write ActionScript to control these and additional options for ScrollPane components using its properties, methods, and events. For more information, see ScrollPane class.

See also:

  • Creating an application with the ScrollPane component

Creating an application with the ScrollPane component

The following procedure explains how to add a ScrollPane component to an application while authoring. In this example, the scroll pane loads a SWF file that contains a logo.

To create an application with the ScrollPane component, do the following:

  1. Drag a ScrollPane component from the Components panel to the Stage.
  2. In the Property inspector, enter the instance name myScrollPane.
  3. In the Property inspector, enter logo.swf for the contentPath parameter.
  4. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code:
    scrollListener = new Object();
scrollListener.scroll = function (evt){
  txtPosition.text = myScrollPane.vPosition;
}
myScrollPane.addEventListener("scroll", scrollListener);
completeListener = new Object;
completeListener.complete = function() {
  trace("logo.swf has completed loading.");
}
myScrollPane.addEventListener("complete", completeListener);

    The first block of code is a scroll event handler on the myScrollPane instance that displays the value of the vPosition property in a TextField instance called txtPosition, that has already been placed on Stage. The second block of code creates an event handler for the complete event that sends a message to the Output panel.


Customizing the ScrollPane component

You can transform a ScrollPane component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()) or any applicable properties and methods of the ScrollPane class. See ScrollPane class. If the ScrollPane is too small, the content may not display correctly.

The ScrollPane places the registration point of its content in the upper left corner of the pane.

When the horizontal scroll bar is turned off, the vertical scroll bar is displayed from top to bottom along the right side of the scroll pane. When the vertical scroll bar is turned off, the horizontal scroll bar is displayed from left to right along the bottom of the scroll pane. You can also turn off both scroll bars.

When the scroll pane is resized, the buttons remain the same size and the scroll track and thumb expand or contract, and their hit areas are resized.

See also:

  • Using styles with the ScrollPane component
  • Using skins with the ScrollPane component

Using styles with the ScrollPane component

The ScrollPane doesn't support styles, but the scroll bars that it uses do. For the latest information about this topic, click the Update button at the top of the Help tab.

Using skins with the ScrollPane component

The ScrollPane component doesn't have any skins of its own, but the scroll bars that it uses do have skins. For the latest information about this topic, click the Update button at the top of the Help tab.


ScrollPane class

Inheritance UIObject > UIComponent > View > ScrollView > ScrollPane

ActionScript Class Name mx.containers.ScrollPane

The properties of the ScrollPane class allow you to set the content, monitor the loading progress, and adjust the scroll amount at runtime.

Setting a property of the ScrollPane class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

You can set up a scroll pane to allow users to drag the content within the pane by setting the scrollDrag property to true; a pointing hand appears on the content. Unlike most other components, events are broadcast when the mouse button is pressed and continue broadcasting until the button is released. If the contents of a scroll pane have valid tab stops, you must set scrollDrag to false otherwise each mouse interaction with the contents will invoke scroll dragging.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.containers.ScrollPane.version);

Note: The following code returns undefined: trace(myScrollPaneInstance.version);.

Method summary for the ScrollPane class

Method | Description
ScrollPane.getBytesLoaded() | Returns the number of bytes of content loaded.
ScrollPane.getBytesTotal() | Returns the total number of content bytes to be loaded.
ScrollPane.refreshPane() | Reloads the contents of the scroll pane.

Inherits all methods from UIObject and UIComponent.

Property summary for the ScrollPane class

Method | Description
ScrollPane.content | A reference to the content loaded into the scroll pane.
ScrollPane.contentPath | An absolute or relative URL of the SWF or JPEG file to load into the scroll pane
ScrollPane.hLineScrollSize | The amount of content to scroll horizontally when an arrow button is pressed.
ScrollPane.hPageScrollSize | The amount of content to scroll horizontally when the track is pressed.
ScrollPane.hPosition | The horizontal pixel position of the scroll pane.
ScrollPane.hScrollPolicy | The status of the horizontal scroll bar. It can be always on ("on"), always off ("off"), or on when needed ("auto"). The default value is "auto".
ScrollPane.scrollDrag | Indicates whether there is scrolling when a user presses and drags within the ScrollPane (true) or not (false). The default value is false.
ScrollPane.vLineScrollSize | The amount of content to scroll vertically when an arrow button is pressed.
ScrollPane.vPageScrollSize | The amount of content to scroll vertically when the track is pressed.
ScrollPane.vPosition | The vertical pixel position of the scroll pane.
ScrollPane.vScrollPolicy | The status of the vertical scroll bar. It can be always on ("on"), always off ("off"), or on when needed ("auto"). The default value is "auto".

Inherits all properties from UIObject and UIComponent.

Event summary for the ScrollPane class

Method | Description
ScrollPane.complete | Broadcast when the scroll pane content is loaded.
ScrollPane.progress | Broadcast while the scroll bar content is loading.
ScrollPane.scroll | Broadcast when the scroll bar is pressed.

Inherits all events from UIObject and UIComponent.


ScrollPane.complete

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(complete){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.complete = function(eventObject){
  ...
}
scrollPaneInstance.addEventListener("complete", listenerObject)

Description

Event; broadcast to all registered listeners when the content has finished loading.

The first usage example uses an on() handler and must be attached directly to a ScrollPane component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ScrollPane component instance myScrollPaneComponent, sends "_level0.myScrollPaneComponent" to the Output panel:

on(complete){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (scrollPaneInstance) dispatches an event (in this case, complete) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example creates a listener object with a complete event handler for the scrollPane instance:

form.complete = function(eventObj){
  // insert code to handle the event
}
scrollPane.addEventListener("complete",form);


ScrollPane.content

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.content

Description

Property (read-only); a reference to the content of the scroll pane. The value is undefined until the load begins.

Example

This example sets the mcLoaded variable to the value of the content property:

var mcLoaded = scrollPane.content;

See also

ScrollPane.contentPath


ScrollPane.contentPath

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.contentPath

Description

Property; a string that indicates an absolute or relative URL of the SWF or JPEG file to load into the scroll pane. A relative path must be relative to the SWF file that loads the content.

If you load content using a relative URL, the loaded content must be relative to the location of the SWF file that contains the scroll pane. For example, an application using a ScrollPane component that resides in the directory /scrollpane/nav/example.swf could load contents from the directory /scrollpane/content/flash/logo.swf with the following contentPath property: "../content/flash/logo.swf"

Example

The following example tells the scroll pane to display the contents of an image from the internet:

scrollPane.contentPath ="http://imagecache2.allposters.com/images/43/033_302.jpg";

The following example tells the scroll pane to display the contents of a symbol from the library:

scrollPane.contentPath ="movieClip_Name";

The following example tells the scroll pane to display the contents of the local file "logo.swf":

scrollPane.contentPath ="logo.swf";

See also

ScrollPane.content


ScrollPane.getBytesLoaded()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.getBytesLoaded()

Parameters

None.

Returns

The number of bytes loaded in the scroll pane.

Description

Method; returns the number of bytes loaded in the ScrollPane instance. You can call this method at regular intervals while loading content to check its progress.

Example

This example creates an instance of the ScrollPane class called scrollPane. It then defines a listener object called loadListener with a progress event handler that calls the getBytesLoaded() method to help determine the progress of the load:

createClassObject(mx.containers.ScrollPane, "scrollPane", 0);
loadListener = new Object();
loadListener.progress = function(eventObj){
  // eventObj.target is the component that generated the change event
  var bytesLoaded = scrollPane.getBytesLoaded();
  var bytesTotal = scrollPane.getBytesTotal();
  var percentComplete = Math.floor(bytesLoaded/bytesTotal);

  if (percentComplete < 5 )  // loading just commences
  {
    trace(" Starting loading contents from internet");
  }
  else if(percentComplete = 50) //50% complete
  {
    trace(" 50% contents downloaded ");
  }
}
scrollPane.addEventListener("progress", loadListener);
scrollPane.contentPath = "http://www.geocities.com/hcls_matrix/Images/homeview5.jpg";


ScrollPane.getBytesTotal()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.getBytesTotal()

Parameters

None.

Returns

A number.

Description

Method; returns the total number of bytes to be loaded into the ScrollPane instance.

See also

ScrollPane.getBytesLoaded()


ScrollPane.hLineScrollSize

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.hLineScrollSize

Description

Property; the number of pixels to move the content when the left or right arrow in the horizontal scroll bar is pressed. The default value is 5.

Example

This example increases the horizontal scroll unit to 10:

scrollPane.hLineScrollSize = 10;


ScrollPane.hPageScrollSize

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.hPageScrollSize

Description

Property; the number of pixels to move the content when the track in the horizontal scroll bar is pressed. The default value is 20.

Example

This example increases the horizontal page scroll unit to 30:

scrollPane.hPageScrollSize = 30;


ScrollPane.hPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.hPosition

Description

Property; the pixel position of the horizontal scroll bar. The 0 position is to the left of the bar.

Example

This example sets the scroll bar to 20:

scrollPane.hPosition = 20;


ScrollPane.hScrollPolicy

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.hScrollPolicy

Description

Property; determines whether the horizontal scroll bar is always present ("on"), never present ("off"), or appears automatically according to the size of the image ("auto"). The default value is "auto".

Example

The following code turns scroll bars on all the time:

scrollPane.hScrollPolicy = "on";


ScrollPane.progress

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(progress){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.progress = function(eventObject){
  ...
}
scrollPaneInstance.addEventListener("progress", listenerObject)

Description

Event; broadcast to all registered listeners while content is loading. The progress event is not always broadcast; the complete event may be broadcast without any progress events being dispatched. This can happen especially if the loaded content is a local file. This event is triggered when the content starts loading by setting the value of contentPath property.

The first usage example uses an on() handler and must be attached directly to a ScrollPane component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the ScrollPane component instance mySPComponent, sends "_level0.mySPComponent" to the Output panel:

on(progress){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (scrollPaneInstance) dispatches an event (in this case, progress) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following code creates a ScrollPane instance called scrollPane and then creates a listener object with an event handler for the progress event that sends a message to the Output panel about what number of bytes of the content has loaded:

createClassObject(mx.containers.ScrollPane, "scrollPane", 0);
loadListener = new Object();
loadListener.progress = function(eventObj){
  // eventObj.target is the component that generated the progress event
  // in this case, scrollPane
  trace("logo.swf has loaded " + scrollPane.getBytesLoaded() + " Bytes.");
  // track loading progress
}
scrollPane.addEventListener("complete", loadListener);
scrollPane.contentPath = "logo.swf";


ScrollPane.refreshPane()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.refreshPane()

Parameters

None.

Returns

Nothing.

Description

Method; refreshes the scroll pane after content is loaded. This method reloads the contents. You could use this method if, for example, you've loaded a form into a ScrollPane and an input property (for example, in a text field) has been changed using ActionScript. Call refreshPane() to reload the same form with the new values for the input properties.

Example

The following example refreshes the scroll pane instance sp:

sp.refreshPane();


ScrollPane.scroll

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(scroll){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.scroll = function(eventObject){
  ...
}
scrollPaneInstance.addEventListener("scroll", listenerObject)

Event Object

In addition to the standard event object properties, there is a type property defined for the scroll event, the value is "scroll". There is also a direction property with the possible values "vertical" and "horizontal".

Description

Event; broadcast to all registered listeners when a user presses the scroll bar buttons, thumb, or track. Unlike other events, the scroll event is broadcast when a user presses on the scroll bar and continues broadcasting until the scroll bar is released.

The first usage example uses an on() handler and must be attached directly to a ScrollPane component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the instance sp, sends "_level0.sp" to the Output panel:

on(scroll){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (scrollPaneInstance) dispatches an event (in this case, scroll) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example creates a form listener object with a scroll callback function that's registered to the spInstance instance. You must fill spInstance with content, as in the following:

spInstance.contentPath = "mouse3.jpg";
form = new Object();
form.scroll = function(eventObj){
  trace("ScrollPane scrolled");
}
spInstance.addEventListener("scroll", form);

See also

UIEventDispatcher.addEventListener()


ScrollPane.scrollDrag

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.scrollDrag

Description

Property; a Boolean value that indicates whether there is scrolling when a user presses and drags within the ScrollPane (true) or not (false). The default value is false.

Example

This example enables mouse scrolling within the scroll pane:

scrollPane.scrollDrag = true;


ScrollPane.vLineScrollSize

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.vLineScrollSize

Description

Property; the number of pixels to move the display area when the up or down arrow button in a vertical scroll bar is pressed. The default value is 5.

Example

This code increases the amount that the display area moves when the vertical scroll bar arrow buttons are pressed to 10:

scrollPane.vLineScrollSize = 10;


ScrollPane.vPageScrollSize

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

scrollPaneInstance.vPageScrollSize

Description

Property; the number of pixels to move the display area when the track in a vertical scroll bar is pressed. The default value is 20.

Example

This code increases the amount that the display area moves when the vertical scroll bar arrow buttons are pressed to 30:

scrollPane.vPageScrollSize = 30;


ScrollPane.vPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.vPosition

Description

Property; the pixel position of the vertical scroll bar. The default value is 0.


ScrollPane.vScrollPolicy

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

scrollPaneInstance.vScrollPolicy

Description

Property; determines whether the vertical scroll bar is always present ("on"), never present ("off"), or appears automatically according to the size of the image ("auto"). The default value is "auto".

Example

The following code turns vertical scroll bars on all the time:

scrollPane.vScrollPolicy = "on";


About the Slide class (Flash Professional only)

The Slide class corresponds to a node in a hierarchical slide presentation. In Flash MX Professional 2004, you can create slide presentations using the Screen Outline pane. For an overview of working of working with screens, see Working with Screens (Flash Professional Only).

The Slide class extends the Screen class (see Screen class overview (Flash Professional only)), and provides built-in navigation and sequencing capabilities between slides, as well as the ability to easily attach transitions between slides using Behaviors. Slides maintain a notion of "state", so the user can advance to the next or previous slide in a presentation and when the next slide in a presentation is shown, the previous slide is hidden.

Note that you can only navigate to (or "stop on") slides that don't contain any child slides, or "leaf" slides. For example, the following illustration shows the contents of the Screen Outline pane for a sample slide presentation.

When this presentation starts, it will, by default, "stop" on the slide named Finance, which is the first slide in the presentation that doesn't contain any child slides.

Also note that child slides "inherit" the visual appearance (graphics and other content) of their parent slides. For example, in the above illustration, in addition to the content on the Finance slide, the user would also see any content on the Intro and Presentation slides.

Note: The Slide class inherits from the Loader class (see Loader class), which lets you easily load external SWF files (or JPEG files) into a given slide. This provides a way to modularize your slide presentations, and reduce initial download time. For more information, see Loading external content into screens (Flash Professional only).

See also:

  • Using the Slide class (Flash Professional only)
  • Slide class (API)


Using the Slide class (Flash Professional only)

You use the methods and properties of the Slide class to control Slide Presentations you create using the Screen Outline pane (Window > Screen the get information about a slide presentation (for example, to determine the number of child slides contained by parent slide), or to navigate between slides in a slide presentation (for example, to create "Next slide" and "Previous slide" buttons).

You can also use one of the built-in behaviors for controlling slide presentations that are available in the Behaviors panel (Window > Development Panels > Behaviors). For more information on using behaviors with slides, see Adding controls to screens using behaviors (Flash Professional only).

See also:

  • Slide parameters
  • Using the Slide class to create a Slide Presentation

Slide parameters

The following are authoring parameters that you can set for each slide in the Property inspector or in the Component Inspector panel:

autoKeyNav determines how, or if, the slide responds to the default keyboard navigation. For more information, see Slide.autoKeyNav.

autoload indicates whether the content specified by the contentPath parameter should load automatically (true), or wait to load until the Loader.load() method is called (false). The default value is true.

contentPath specifies the contents of the slide. This can be the linkage identifier of a movie clip or an absolute or relative URL for a SWF or JPG file to load into the slide. By default, loaded content clips to fit the slide.

overlayChildren specifies whether the slide's child slides remain visible when you navigate from one child slide to the next (true), or not (false).

playHidden specifies whether the slide continues to play when hidden (true) or not (false).

Using the Slide class to create a Slide Presentation

You use the methods and properties of the Slide class to control slide presentations you create in the Screen Outline pane (Window > Screen) in the Flash authoring environment. Note that the Behavior panel (Window > Development Panels > Behaviors) contains several behaviors for creating slide navigation. In this example, you write your own ActionScript to create Next and Previous buttons for a slide presentations.

To create a slide presentation with navigation:

  1. In Flash, select File > New.
  2. Click the General tab and select Flash Slide Presentation under Type.
  3. In the Screen Outline pane, click the Insert Screen button (+) twice to create two new slides beneath the Presentation slide.

    The Screen Outline pane should look like the following:

  4. Select Slide1 in the Screen Outline pane and, using the Text tool, add a text field that reads "This is slide one".
  5. Repeat the previous step for Slide2 and Slide3, creating text fields on each slide that read "This is slide two" and "This is slide three", respectively.
  6. Select the Presentation slide and open the Components panel (Window > Development Panels > Components).
  7. Drag a Button component from the Components panel to the bottom of the Stage.
  8. In the Property inspector (Window > Properties) type "Next Slide" for the Button component's Label property.
  9. Open the Actions panel, if it's not already open, by selecting Window > Development Panels > Actions.
  10. Type the following code in the Actions panel:
    on(click) {
  _parent.currentSlide.gotoNextSlide();
}
  11. Test the SWF file (Control > Test Movie) and click the Next Slide button to advance to the next slide.


Slide class (API)

Inheritance UIObject > UIComponent > View > Loader > Screen > Slide

ActionScript Class Name mx.screens.Slide

Method summary for the Slide class

Property | Description
Slide.getChildSlide() | Returns the child slide of this slide at a given index.
Slide.gotoFirstSlide() | Navigates to the first leaf node in the slide's hierarchy of subslides.
Slide.gotoLastSlide() | Navigates to the last leaf node in the slide's hierarchy of subslides.
Slide.gotoNextSlide() | Navigates to the next slide.
Slide.gotoPreviousSlide() | Navigates to the next slide.
Slide.gotoSlide() | Navigates to an arbitrary slide.

Inherits all methods from UIObject, UIComponent, View, Loader component, and Screen class overview (Flash Professional only).

Property summary for the Slide class

Property | Description
Slide.autoKeyNav | Determines whether or not the slide uses default keyboard handling to navigate to the next/previous slide.
Slide.currentSlide | Returns the immediate child of the slide that contains the currently active slide.
Slide.currentSlide | Returns the currently active slide.
Slide.currentFocusedSlide | Returns the "leafmost" slide that contains the global current focus.
Slide.defaultKeydownHandler | Callback handler that overrides the default keypress slide navigation (left and right arrow).
Slide.firstSlide | Returns the slide's first child slide that has no children.
Slide.getChildSlide() | Returns the child slide at a specified index.
Slide.indexInParentSlide | Returns the slide's index (zero-based) in its parent's list of subslides.
Slide.lastSlide | Returns the slide's last child slide that has no children.
Slide.nextSlide | Returns the next leaf node slide.
Slide.numChildSlides | Returns the number of child slides the slide contains.
Slide.overlayChildren | Determines whether the slide's child slides are visible when control flows from one child slide to the next.
Slide.parentIsSlide | Returns a Boolean value indicating whether the parent object of the slide is also a slide (true) or not (false).
Slide.playHidden | Determines whether or not the slide continues to play when hidden.
Slide.previousSlide | Returns the previous leaf node slide.
Slide.revealChild | Returns the root of the slide tree that contains the slide.

Inherits all properties from UIObject, UIComponent, View, Loader component, and Screen class overview (Flash Professional only).

Event summary for the Slide class

Event | Description
Slide.hideChild | Broadcast when all children of a slide changes from visible to invisible.
Slide.revealChild | Broadcast when all children of a slide changes from invisible to visible.

Inherits all events from UIObject, UIComponent, View, Loader component, and Screen class overview (Flash Professional only).


Slide.autoKeyNav

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.autoKeyNav

Description

Property; determines whether or not the slide uses default keyboard handling to navigate to the next/previous slide when mySlide has focus. This property accepts one of the following string values: "true", "false", or "inherit". You can also override this default keyboard handling behavior using the Slide.defaultKeydownHandler property.

You can also set this property using the Property inspector.

When set to "true", pressing the right arrow (Key.RIGHT) or the Spacebar (Key.SPACE) when mySlide has focus advances to the next slide; pressing the left arrow (Key.Left) moves to the previous slide.

When set to "false", no default keyboard handling takes place when mySlide has focus.

When set to "inherit", mySlide checks the autoKeyNav property of its parent slide. If the parent of mySlide is also set to "inherit", then mySlide's parent's parent is examined, and so on, until a parent slide is found whose autoKeyNav property is set to "true" or "false".

If mySlide has no parent slide (that is, if (mySlide.parentIsSlide == false) is true) then it behaves as if autoKeyNav had been set to true.

Example

This example turns off automatic keyboard navigation for the slide named loginSlide.

_root.Presentation.loginSlide.autoKeyNav = "false";

See also

Slide.defaultKeydownHandler


Slide.currentSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.currentSlide

Description

Property (read-only); returns the currently active slide. This is always a "leaf" slide—that is, a slide that contains no child slides.

Example

The following code, attached to a button on the root Presentation slide, advances the slide presentation to the next slide each time the button is pressed.

// Attached to button instance contained by Presentation slide:
on(press) {
  _parent.currentSlide.gotoNextSlide();
}

See also

Slide.gotoNextSlide()


Slide.currentChildSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.currentChildSlide

Description

Property (read-only); returns the immediate child of mySlide that contains the currently active slide; returns null if no child slide contained by mySlide has the current focus.

Example

Consider the following screen outline:

Presentation
  Slide_1
    Bullet1_1
      SubBullet1_1_1
    Bullet1_2
      SubBullet1_2_1
  Slide_2

Assuming that SubBullet1_1_1 is the current slide, then the following statements are all true:

Presentation.currentChildSlide == Slide_1;
Slide_1.currentChildSlide == Bullet_1_1;
SubBullet_1_1_1.currentChildSlide == null;
Slide_2.currentChildSlide == null;

See also

Slide.currentSlide


Slide.currentFocusedSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mx.screens.Slide.currentFocusedSlide

Description

Property (read-only); returns "leaf-most" slide that contains the current global focus. The actual focus may be on the slide itself, or on a movie clip, text object, or component inside that slide; returns null if there is no current focus.

Example

var focusedSlide = mx.screens.Slide.currentFocusedSlide;


Slide.defaultKeydownHandler

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.defaultKeyDownHandler = function (eventObj) {
  // your code here
}

Parameters

eventObj An event object with the following properties:

  • type A string indicating the type of event. Possible values are "keyUp" and "keyDown
  • ascii An integer that represents the ASCII value of the last key pressed; corresponds to the value returned by Key.getAscii().
  • code An integer that represents the key code of the last key pressed; corresponds to the value returned by Key.getCode().
  • shiftKey A Boolean (true or false) value indicating if the Shift key is currently being pressed (true) or not (false).
  • ctrlKey A Boolean (true or false) value indicating if the Control key is currently being pressed (true) or not (false).

Returns

Nothing.

Description

Callback handler; lets you override the default key board navigation with a custom keyboard handler that you create. For example, instead of having the Left and Right arrow keys navigate to the previous and next slides in a presentation, respectively, you could have the Up and Down arrow keys perform those functions. For a discussion of the default keyboard handling behavior see Slide.autoKeyNav.

Example

In that example, the default keyboard handling is altered for child slides of the slide to which the on(load) handler is attached. This handler uses the up/down arrow for navigation instead of left/right arrow.

on (load) {
  this.defaultKeyDownHandler = function(eventObj:Object) {
    switch (eventObj.code) {
    case Key.DOWN :
      this.currentSlide.gotoNextSlide();
      break;
    case Key.UP :
      this.currentSlide.gotoPreviousSlide();
      break;
    default :
      break;
    }
  };
}

See also

Slide.autoKeyNav


Slide.firstSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.firstSlide

Description

Property (read-only); returns the first child slide of mySlide that has no child slides.

Example

For example, in the hierarchy of slides shown below, the following statements are all true:

Presentation.Intro.firstSlide == Intro_bullet_1_1;
Presentation.Intro_bullet_1.firstSlide == Intro_bullet_1-1;


Slide.getChildSlide()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.getChildSlide(childIndex)

Parameters

childIndex The zero-based index of the child slide to return.

Returns

A slide object.

Description

Method; returns the child slide of mySlide whose index is childIndex. This method is useful, for example, to iterate over a set of child slides whose indices are known, as the following example shows.

Example

This example displays in the Output panel the names of all the child slides of the root Presentation slide.

var numSlides = _root.Presentation.numChildSlides;
for(var slideIndex=0; slideIndex < numSlides; slideIndex++) {
  var childSlide = _root.Presentation.getChildSlide(slideIndex);
  trace(childSlide._name);
}

See also

Slide.numChildSlides


Slide.gotoSlide()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.gotoSlide(newSlide)

Parameters

newSlide The slide to navigate to.

Returns

A Boolean value (true or false) indicating if the navigation succeeded (true), or not (false).

Description

Method; navigates to the slide specified by newSlide. For the navigation to succeed, the following must be true:

  • The current slide must be a child slide of mySlide.
  • The slide specified by newSlide and the current slide must share a common ancestor slide—that is, the current slide and newSlide must reside in the same slide subtree.

If either of these conditions isn't met, the navigation fails and the method returns false; otherwise, the method navigates to the specified slide and returns true.

For example, consider the following slide hierarchy:

Presentation
  Slide1
    Slide1_1
    Slide1_2
 Slide2
    Slide2_1
    Slide2_2

If the current slide is Slide1_2, then the following gotoSlide() method call will fail, since the current slide is not a descendant of Slide2:

Slide2.gotoSlide(Slide2_1);

Also consider the following screen hierarchy, where a form object is the parent screen of two separate slide trees.

Form_1
  Slide1
    Slide1_1
    Slide1_2
  Slide2
    Slide2_1
    Slide2_2

If the current slide is Slide1_2, then the following method call will also fail because Slide1 and Slide2 are in different slide subtrees.

Slide1_2.gotoSlide(Slide2_2);

Example

The following code, attached to a Button component, uses the Slide.currentSlide property and gotoSlide() method to send the presentation to the next slide in the presentation.

on(click) {
  _parent.gotoSlide(_parent.currentSlide.nextSlide);
}

Note that this is equivalent to the following code, which uses the Slide.gotoNextSlide() method.

on(click) {
  _parent.currentSlide.gotoNextSlide();
}

See also

Slide.currentSlide, Slide.gotoNextSlide()


Slide.gotoFirstSlide()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.gotoFirstSlide()

Returns

Nothing.

Description

Method; navigates to the first leaf slide in the tree of child slides beneath mySlide. This method is ignored when called from within a slide's on(hide) or on(reveal) event handler if that event was a result of a slide navigation.

To go to the first slide in a presentation, call mySlide.rootSlide.gotoFirstSlide(). For more information on rootSlide, see Slide.revealChild

Example

In the slide hierarchy illustrated below, the following method calls would all navigate to the slide named Intro_bullet_1_1.

Presentation.gotoFirstSlide();
Presenation.Intro.gotoFirstSlide();
Presentation.Intro.Intro_bullet_1.gotoFirstSlide();

This method call would navigate to the slide named Intro_bullet_2_1.

Presentation.Intro.Intro_bullet_2.gotoFirstSlide();

See also

Slide.firstSlide, Slide.revealChild


Slide.gotoLastSlide()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.gotoLastSlide()

Returns

Nothing.

Description

Method; navigates to the last leaf slide in the tree of child slides beneath mySlide. This method is ignored when called from within a slide's on(hide) or on(reveal) event handler if that event was a result of another slide navigation.

Example

In the slide hierarchy illustrated below, the following method calls would navigate to the slide named Intro_bullet_1_2.

Presenation.Intro.gotoLastSlide();
Presentation.Intro.Intro_bullet_1.gotoLastSlide();

These method calls would navigate to the slide named Intro_bullet_2_1.

Presentation.gotoLastSlide();
Presentation.Intro.gotoLastSlide();

See also

Slide.gotoSlide(), Slide.lastSlide


Slide.gotoNextSlide()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.gotoNextSlide()

Returns

A Boolean (true or false) value, or null; returns true if the method successfully navigated to the next slide; returns false if the presentation is already at the last slide when the method is invoked (that is, if currentSlide.nextSlide is null); returns null if invoked on a slide that doesn't contain the current slide.

Description

Method; navigates to the next slide in the slide presentation. As control passes from one slide to the next, the outgoing slide is hidden and the incoming slide is revealed. If the outgoing and incoming slides are in different slide subtrees, then all ancestor slides, starting with the outgoing slide and up to the common ancestor of the incoming and outgoing slides, are hidden and receive a hide event. Immediately following, all ancestor slides of the incoming slide, up to the common ancestor of the outgoing and incoming slide, are made visible and receive a reveal event.

Typically, gotoNextSlide() is called on the leaf node that represents the current slide. If called on a non-leaf node, someNode, then someNode.gotoNextSlide() advances to the first leaf node in the next slide or "section". For more information, see the example below.

This method has no effect when invoked on a slide that does not contain the current slide (see example below).

Also, this method has no effect when called from within an on(hide) or on(reveal) event handler attached to a slide, if that handler was invoked as a result of slide navigation.

Example

Suppose that, in the following slide hierarchy, the slide named Intro_bullet_1_1 is the current slide being viewed (that is, _root.Presentation.currentSlide._name == Intro_bullet_1_1).

In this case, calling Intro_bullet_1_1.gotoNextSlide() would navigate to Intro_bullet_1_2, which is a sibling slide of Intro_bullet_1_1.

However, invoking Intro_bullet_1.gotoNextSlide() would navigate to Intro_bullet_2_1, the first leaf slide contained by Intro_bullet_2, which is the next sibling slide of Intro_bullet_1. Similarly, calling Intro.gotoNextSlide() would navigate to Results_bullet_1, the first leaf slide contained by the Results slide.

Also, still assuming that the current slide is Intro_bullet_1_1, calling Results.gotoNextSlide() will have no effect, since Results does not contain the current slide (that is, Results.currentSlide is null).

See also

Slide.currentSlide, Slide.gotoPreviousSlide(), Slide.nextSlide


Slide.gotoPreviousSlide()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.gotoPreviousSlide()

Returns

A Boolean (true or false) value, or null; returns true if the method successfully navigated to the previous slide; returns false if the presentation is at the first slide when the method is invoked (that is, if currentSlide.nextSlide is null); returns null if invoked on a slide that doesn't contain the current slide.

Description

Method; navigates to the previous slide in the slide presentation. As control passes from one slide to the previous, the outgoing slide is hidden and the incoming slide is revealed. If the outgoing and incoming slides are in different slide subtrees, then all ancestor slides, starting with the outgoing slide and up to the common ancestor of the incoming and outgoing slides, are hidden and receive a hide event. Immediately following, all ancestors slides of the incoming slide, up to the common ancestor of the outgoing and incoming slide, are made visible and receive a reveal event.

Typically, gotoPreviousSlide() is called on the leaf node that represents the current slide. If called on a non-leaf node, someNode, then someNode.gotoPreviousSlide() advances to the first leaf node in the next slide or "section". For more information, see the example below.

This method has no effect when invoked on a slide that does not contain the current slide (see example below).

Also note that this method has no effect when called from within an on(hide) or on(reveal) event handler attached to a slide, if that handler was invoked as a result of slide navigation.

Example

Suppose that, in the following slide hierarchy, the slide named Intro_bullet_1_2 is the current slide being viewed (that is, _root.Presentation.currentSlide._name == Intro_bullet_1_2).

In this case, calling Intro_bullet_1_2.gotoPreviousSlide() would navigate to Intro_bullet_1_1, which is the previous sibling slide of Intro_bullet_1_2.

However, invoking Intro_bullet_2.gotoPreviousSlide() would navigate to Intro_bullet_1_1, the first leaf slide contained by Intro_bullet_1, which is the previous sibling slide of Intro_bullet_2. Similarly, calling Results.gotoPreviousSlide() would navigate to Intro_bullet_1_1, the first leaf slide contained by the Intro slide.

Also, if the current slide is Intro_bullet_1_1, then calling Results.gotoPreviousSlide() will have no effect, since Results does not contain the current slide (that is, Results.currentSlide is null).

See also

Slide.currentSlide, Slide.gotoNextSlide(), Slide.previousSlide


Slide.hideChild

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(hideChild) {
  // your code here
}

Description

Event; broadcasted each time a child of a slide object changes visible to non-visible. This event is only broadcasted by slide objects, not Form objects. The main use of the hideChild event is to apply "out" transitions to all the children of a given slide.

Example

When attached to the root slide (for example, the Presentation slide), this code will display the name of each child slide belonging to the root slide, as it appears.

on(revealChild) {
  var child = eventObj.target._name;
  trace(child + " has just appeared");
}

See also

Slide.revealChild


Slide.indexInParentSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.indexInParent

Description

Property (read-only); returns the index (zero-based) of mySlide in its parent's list of child slides.

Example

The following code uses the indexInParent and Slide.numChildSlides properties to display the index of the current slide being viewed and the total number of slides contained by its parent slide. To use this code, attach it to a parent slide that contains one or more child slides.

on (revealChild) {
  trace("Displaying "+(currentSlide.indexInParentSlide+1)+" of "+currentSlide._parent.numChildSlides);
}

Note that because this property is a zero-based index, its value is incremented by one (currentSlide.indexInParent+1) to display more meaningful values.

See also

Slide.numChildSlides, Slide.revealChild


Slide.lastSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.lastSlide

Description

Property (read-only); returns the last child slide of mySlide that has no child slides.

Example

The following statements are all true concerning the slide hierarchy shown below:

Presentation.lastSlide._name == Results_bullet_1;
Intro.lastSlide._name == Intro_bullet_1_2;
Intro_bullet_1.lastSlide._name == Intro_bullet_1_2;
Results.lastSlide._name = Results_bullet_1;


Slide.nextSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.nextSlide

Description

Property (read-only); returns the slide you would reach if you called mySlide.gotoNextSlide(), but does not actually navigate to that slide. For example, you can use this property to display the name of the next slide in a presentation and let users select whether they want to navigate to that slide.

Example

In this example, the label of a Button component named nextButton displays the name of the next slide in the presentation. If there is no next slide—that is, if myslide.nextSlide is null—then the button's label is updated to indicate that the user is at the end of this slide presentation.

if (mySlide.nextSlide != null) {
    nextButton.label = "Next slide: " + mySlide.nextSlide._name + " > ";
} else {
  nextButton.label = "End of this slide presentation.";
}

See also

Slide.gotoNextSlide(), Slide.previousSlide


Slide.numChildSlides

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.numChildSlides

Description

Property (read-only); returns the number of child slides that mySlide contains. Note that a slide can contain either forms or other slides. If mySlide contains both slides and forms, this property only returns the number of slides, and does not count forms.

Example

This example uses Slide.numChildSlide and the Slide.getChildSlide() method to iterate over all the child slides of the root Presentation slide and displays their names in the Output panel.

var numSlides = _root.Presentation.numChildSlides;
for(var slideIndex=0; slideIndex < numSlides; slideIndex++) {
  var childSlide = _root.Presentation.getChildSlide(slideIndex);
  trace(childSlide._name);
}

See also

Slide.getChildSlide()


Slide.overlayChildren

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.overlayChildren

Description

Property; determines whether or not child slides of mySlide remain visible when navigating from one child slide to the next. When set to true, the previous slide remains visible when control passes to its next sibling slide; when set to false, the previous slide is invisible when control passes to its next sibling slide.

Setting this property to true is useful, for example, when a given slide contains several child "bullet point" slides that are revealed separately (using transitions, perhaps), but all need to remain visible as new bullet points appear.

Note: This property applies only to the immediate descendants of mySlide, not to all (nested) child slides.

Example

For example, the Intro_bullets slide in the following illustration contains three child slides (Finance, Human resources, and Operations) that each display a separate bullet point. By setting Intro_bullets.overlayChildren to true, each bullet slide will remain on the Stage as the other bullets points appear.


Slide.parentIsSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.parentIsSlide

Description

Property (read-only); a Boolean (true or false) value indicating whether the parent object of mySlide is also a Slide. If the parent object of mySlide is a Slide, or a subclass of Slide, then this property will return true; otherwise, it returns false.

If mySlide is the root slide in a presentation then this property will return false since the Presentation slide's parent is the main Timeline (_level0), not a slide. This property will also return false if a form is the parent of mySlide.

Example

The following code determines if the parent object of the slide mySlide is itself a slide. If so, it's assumed that mySlide is the root, or master, slide in the presentation and therefore has no sibling slides. Otherwise, if mySlide.parentIsSlide is true, and the number of mySlide's sibling slides is displayed in the Output panel.

if (mySlide.parentIsSlide) {
  trace("I have " + mySlide._parent.numChildSlides+" sibling slides");
} else {
  trace("I am the root slide and have no siblings");
}

See also

Slide.numChildSlides


Slide.playHidden

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.playHidden

Description

Property; a Boolean value that specifies whether mySlide should continue to play when it is hidden. When this property is true, mySlide will continue to play when hidden. When set to false, mySlide is stopped upon being hidden; upon being revealed play restarts at Frame 1 of mySlide.

You can also set this property in the Property inspector of the Flash authoring environment.


Slide.previousSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.previousSlide

Description

Property (read-only); returns the slide you would reach if you called mySlide.gotoPreviousSlide(), but does not actually navigate to that slide. For example, you can use this property to display the name of the previous slide in a presentation and let users select whether they want to navigate to that slide.

Example

In this example, the label of a Button component named previousButton displays the name of the previous slide in the presentation. If there is no previous slide—that is, if mySlide.previousSlide is null—then the button's label is updated to indicate that the user is at the beginning of this slide presentation.

if (mySlide.previousSlide != null) {
    previousButton.label = "Previous slide: " + mySlide.previous._name + " > ";
} else {
  previousButton.label = "You're at the beginning of this slide presentation.";

See also

Slide.gotoPreviousSlide(), Slide.nextSlide


Slide.revealChild

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

on(revealChild) {
  // your code here
}

Description

Event; broadcasted each time a child slide of a slide object changes non-visible to visible. This event is used primarily to attach "in" transitions to all the child slides of a given slide.

Example

When attached to the root slide (for example, the Presentation slide), this code will display the name of each child slide as it appears.

on(revealChild) {
  var child = eventObj.target._name;
  trace(child + " has just appeared");
}

See also

Slide.hideChild


Slide.rootSlide

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

mySlide.rootSlide

Description

Property (read-only); returns the root slide of the slide tree, or slide subtree, that contains mySlide.

Example

Suppose you have a movie clip on a slide that, when clicked, goes to the first slide in the presentation. To accomplish this you would attach the following code to the movie clip:

on(press) {
  _parent.rootSlide.gotoFirstSlide();
}

In this case, _parent refers to the slide that contains the movie clip object.


About the StyleManager class

ActionScript Class Name mx.styles.StyleManager

The StyleManager class keeps track of known inheriting styles and colors. You only need to use this class if you are creating components and want to add a new inheriting style or color.

To determine which styles are inheriting, please refer to the W3C web site.

Method summary for the StyleManager class

Method | Description
StyleManager.registerColorName() | Registers a new color name with the StyleManager.
StyleManager.registerColorStyle() | Registers a new color style with the StyleManager.
StyleManager.registerInheritingSyle() | Registers a new inheriting style with the StyleManager.


StyleManager.registerColorName()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

StyleManager.registerColorName(colorName, value)

Parameters

colorName A string indicating the name of the color (for example, "gray", "darkGrey", and so on).

value A hexadecimal number indicating the color (for example, 0x808080, 0x404040, and so on).

Returns

Nothing.

Description

Method; associates a color name with a hexadecimal value and registers it with the StyleManager.

Example

The following example registers "gray" as the color name for the color represented by the hexadecimal value 0x808080:

StyleManager.registerColorName("gray", 0x808080 );


StyleManager.registerColorStyle()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

StyleManager.registerColorStyle(colorStyle)

Parameters

colorStyle A string indicating the name of the color (for example, "highlightColor", "shadowColor", "disabledColor", and so on).

Returns

Nothing.

Description

Method; adds a new color style to the StyleManager.

Example

The following example registers "highlightColor" as a color style:

StyleManager.registerColorStyle("highlightColor");


StyleManager.registerInheritingSyle()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

StyleManager.registerInheritingStyle(propertyName)

Parameters

propertyName A string indicating the name of the style property (for example, "newProp1", "newProp2", and so on).

Returns

Nothing.

Description

Method; marks this style property as inheriting. Use this method to register style properties that aren't listed in the CSS specification. Do not use this method to change non-inheriting styles properties to inheriting.

Example

The following example registers newProp1 as an inheriting style:

StyleManager.registerInheritingStyle("newProp1");


About the TextArea component

The TextArea component wraps the native ActionScript TextField object. You can use styles to customize the TextArea component; when an instance is disabled its contents display in a color represented by the "disabledColor" style. A TextArea component can also be formatted with HTML, or as a password field that disguises the text.

A TextArea component can be enabled or disabled in an application. In the disabled state, it doesn't receive mouse or keyboard input. When enabled, it follows the same focus, selection, and navigation rules as an ActionScript TextField object. When a TextArea instance has focus, you can use the following keys to control it:

Key | Description
Arrow keys | Moves the insertion point one line up, down, left, or right.
Page Down | Moves one screen down.
Page Up | Moves one screen up.
Shift + Tab | Moves focus to the previous object.
Tab | Moves focus to the next object.

For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each TextArea instance reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring. If a scroll bar is needed, it appears in the live preview, but it does not function. Text is not selectable in the live preview and you cannot enter text into the component instance on the Stage.

When you add the TextArea component to an application, you can use the Accessibility panel to make it accessible to screen readers.

See also:

  • Using the TextArea component
  • Customizing the TextArea component
  • TextArea class


Using the TextArea component

You can use a TextArea component wherever you need a multiline text field. If you need a single-line text field, use the TextInput component. For example, you could use a TextArea component as a comment field in a form. You could set up a listener that checks if field is empty when a user tabs out of the field. That listener could display an error message indicating that a comment must be entered in the field.

See also:

  • TextArea component parameters
  • Creating an application with the TextArea component

TextArea component parameters

The following are authoring parameters that you can set for each TextArea component instance in the Property inspector or in the Component Inspector panel:

text indicates the contents of the TextArea. You cannot enter carriage returns in the Property inspector or Component Inspector panel. The default value is "" (empty string).

html indicates whether the text is formatted with HTML (true) or not (false). The default value is false.

editable indicates whether the TextArea component is editable (true) or not (false). The default value is true.

wordWrap indicates whether the text wraps (true) or not (false). The default value is true.

You can write ActionScript to control these and additional options for TextArea components using its properties, methods, and events. For more information, see TextArea class.

Creating an application with the TextArea component

The following procedure explains how to add a TextArea component to an application while authoring. In this example, the component is a Comment field with an event listener that determines if a user has entered text.

To create an application with the TextArea component, do the following:

  1. Drag a TextArea component from the Components panel to the Stage.
  2. In the Property inspector, enter the instance name comment.
  3. In the Property inspector, set parameters as you wish. However, leave the text parameter blank, the editable parameter set to true, and the password parameter set to false.
  4. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code:
    textListener = new Object();
textListener.handleEvent = function (evt){
  if (comment.length < 1)  {
  Alert(_root, "Error", "You must enter at least a comment in this field", mxModal | mxOK);
  }
}
comment.addEventListener("focusOut", textListener);

    This code sets up a focusOut event handler on the TextArea comment instance that verifies that the user typed in something in the text field.

  5. Once text is entered in the comment instance, you can get its value as follows:
    var login = comment.text;


Customizing the TextArea component

You can transform a TextArea component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use UIObject.setSize() or any applicable properties and methods of the TextArea class.

When a TextArea component is resized, the border is resized to the new bounding box. The scroll bars are placed on the bottom and right edges if they are required. The text field is then resized within the remaining area; there are no fixed-size elements in a TextArea component. If the TextArea component is too small to display the text, the text is clipped.

See also:

  • Using styles with the TextArea component
  • Using skins with the TextArea component

Using styles with the TextArea component

The TextArea component supports one set of component styles for all text in the field. However, you can also display HTML compatible with Flash Player HTML rendering. To display HTML text, set TextArea.html to true.

The TextArea component has its backgroundColor and borderStyle style properties defined on a class style declaration. Class styles override _global styles; therefore, if you want to set the backgroundColor and borderStyle style properties, you must create a different custom style declaration on the instance.

If the name of a style property ends in "Color", it is a color style property and behaves differently than non-color style properties. For more information, see Using styles to customize component color and text.

A TextArea component supports the following styles:

Style | Description
color | The default color for text.
embedFonts | The fonts to embed in the document.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style, either "normal",or "italic".
fontWeight | The font weight, either "normal" or "bold".
textAlign | The text alignment: either "left", "right", or "center".
textDecoration | The text decoration, either "none" or "underline".

Using skins with the TextArea component

The TextArea component uses the RectBorder class to draw its border. You can use the setStyle() method (see UIObject.setStyle()) to change the following RectBorder style properties:

RectBorder styles | Letter
borderColor | a
highlightColor | b
borderColor | c
shadowColor | d
borderCapColor | e
shadowCapColor | f
shadowCapColor | g
borderCapColor | h

The style properties set the following positions on the border:


TextArea class

Inheritance UIObject > UIComponent > View > ScrollView > TextArea

ActionScript Class Name mx.controls.TextArea

The properties of the TextArea class allow you to set the text content, formatting, and horizontal and vertical position at runtime. You can also indicate whether the field is editable, and whether it is a "password" field. You can also restrict the characters that a user can enter.

Setting a property of the TextArea class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

The TextArea component overrides the default Flash Player focus rectangle and draws a custom focus rectangle with rounded corners.

The TextArea component supports CSS styles and any additional HTML styles supported by Flash Player.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.TextArea.version);

Note: The following code returns undefined: trace(myTextAreaInstance.version);.

Property summary for the TextArea class

Property | Description
TextArea.editable | A Boolean value indicating whether the field is editable (true) or not (false).
TextArea.hPosition | Defines the horizontal position of the text within the scroll pane.
TextArea.hScrollPolicy | Indicates whether the horizontal scroll bar is always on ("on"), never on ("off"), or turns on when needed ("auto").S
TextArea.html | A flag that indicates whether the text field can be formatted with HTML.
TextArea.length | The number of characters in the text field. This property is read-only.
TextArea.maxChars | The maximum number of characters that the text field can contain.
TextArea.maxHPosition | The maximum value of TextArea.hPosition.
TextArea.maxVPosition | The maximum value of TextArea.vPosition.
TextArea.password | A Boolean value indicating whether the field is a password field (true) or not (false).
TextArea.restrict | The set of characters that a user can enter into the text field.
TextArea.text | The text contents of a TextArea component.
TextArea.vPosition | A number indicating the vertical scrolling position
TextArea.vScrollPolicy | Indicates whether the vertical scroll bar is always on ("on"), never on ("off"), or turns on when needed ("auto").S
TextArea.wordWrap | A Boolean value indicating whether the text wraps (true) or not (false).

Event summary for the TextArea class

Event | Description
TextArea.change | Notifies listeners that text has changed.


TextArea.change

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(change){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.change = function(eventObject){
  ...
}
textAreaInstance.addEventListener("change", listenerObject)

Description

Event; notifies listeners that text has changed. This event is broadcast after the text has changed. This event cannot be used prevent certain characters from being added to the component's text field; instead, use TextArea.restrict.

The first usage example uses an on() handler and must be attached directly to a TextArea component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the instance myTextArea, sends "_level0.myTextArea" to the Output panel:

on(change){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (textAreaInstance) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example traces the total of number of times the text field has changed:

myTextArea.changeHandler = function(obj) {
  this.changeCount++;
  trace(obj.target);
  trace("text has changed " + this.changeCount + " times now! it now contains " +
this.text);
}

See also

UIEventDispatcher.addEventListener()


TextArea.editable

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.editable

Description

Property; a Boolean value that indicates whether the component is editable (true) or not (false). The default value is true.


TextArea.hPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.hPosition

Description

Property; defines the horizontal position of the text within the field. The default value is 0.

Example

The following code displays the left-most characters in the field:

myTextArea.hPosition = 0;


TextArea.hScrollPolicy

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.hScrollPolicy

Description

Property; determines whether the horizontal scroll bar is always present ("on"), never present ("off"), or appears automatically according to the size of the field ("auto"). The default value is "auto".

Example

The following code turns horizontal scroll bars on all the time:

text.hScrollPolicy = "on";


TextArea.html

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.html

Description

Property; a Boolean value that indicates whether the text field is formatted with HTML (true) or not (false). If the html property is true, the text field is an HTML text field. If html is false, the text field is a non-HTML text field. The default value is false.

Example

The following example makes the myTextArea field an HTML text field and then formats the text with HTML tags:

myTextArea.html = true;
myTextArea.text = "The <b>Royal</b> Nonesuch"; // displays "The Royal Nonesuch"


TextArea.length

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.length

Description

Property (read-only); indicates the number of characters in a text field. This property returns the same value as the ActionScript text.length property, but is faster. A character such as tab ("\t") counts as one character. The default value is 0.

Example

The following example gets the length of the text field and copies it to the length variable:

var length = myTextArea.length; // find out how long the text string is


TextArea.maxChars

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.maxChars

Description

Property; the maximum number of characters that the text field can contain. A script may insert more text than the maxChars property allows; the maxChars property only indicates how much text a user can enter. If the value of this property is null, there is no limit to the amount of text a user can enter. The default value is null.

Example

The following example limits the number of characters a user can enter to 255:

myTextArea.maxChars = 255;


TextArea.maxHPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.maxHPosition

Description

Property (read-only); the maximum value of TextArea.hPosition. The default value is 0.

Example

The following code scrolls the text to the far right:

myTextArea.hPosition = myTextArea.maxHPosition;

See also

TextArea.vPosition


TextArea.maxVPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.maxVPosition

Description

Property (read-only); indicates the maximum value of TextArea.vPosition. The default value is 0.

Example

The following code scrolls the text to the bottom of the component:

myTextArea.vPosition = myTextArea.maxVPosition;

See also

TextArea.hPosition


TextArea.password

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.password

Description

Property; a Boolean value indicating whether the text field is a password field (true) or not (false). If the value of password is true, the text field is a password text field and hides the input characters. If false, the text field is not a password text field. The default value is false.

Example

The following code makes the text field a password field that displays all characters as asterisks (*):

myTextArea.password = true;


TextArea.restrict

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.restrict

Description

Property; indicates the set of characters that a user may enter into the text field. The default value is undefined. If the value of the restrict property is null, a user can enter any character. If the value of the restrict property is an empty string, no characters may be entered. If the value of the restrict property is a string of characters, you can enter only characters in the string into the text field; the string is scanned from left to right. A range may be specified using the dash (-).

The restrict property only restricts user interaction; a script may put any text into the text field. This property does not synchronize with the Embed Font Outlines check boxes in the Property inspector.

If the string begins with "^", all characters are initially accepted and succeeding characters in the string are excluded from the set of accepted characters. If the string does not begin with "^", no characters are initially accepted and succeeding characters in the string are included in the set of accepted characters.

Example

In the following example, the first line of code limits the text field to uppercase letters, numbers, and spaces. The second line of code allows all characters except lowercase letters.

my_txt.restrict = "A-Z 0-9"; // limit control to uppercase letters, numbers, and spaces
my_txt.restrict = "^a-z"; // allow all characters, except lowercase letters


TextArea.text

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.text

Description

Property; the text contents of a TextArea component. The default value is "" (empty string).

Example

The following code places a string in the myTextArea instance then traces that string to the Output panel:

myTextArea.text = "The Royal Nonesuch";
trace(myTextArea.text); // traces "The Royal Nonesuch"


TextArea.vPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.vPosition

Description

Property; defines the vertical position of text in a text field. The scroll property is useful for directing users to a specific paragraph in a long passage, or creating scrolling text fields. You can get and set this property. The default value is 0.

Example

The following code makes the topmost characters in a field display:

myTextArea.vPosition = 0;


TextArea.vScrollPolicy

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.vScrollPolicy

Description

Property; determines whether the vertical scroll bar is always present ("on"), never present ("off"), or appears automatically according to the size of the field ("auto"). The default value is "auto".

Example

The following code turns vertical scroll bars off all the time:

text.vScrollPolicy = "off";


TextArea.wordWrap

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textAreaInstance.wordWrap

Description

Property; a Boolean value that indicates whether the text wraps (true) or not (false). The default value is true.


About the TextInput component

The TextInput is a single-line component that wraps the native ActionScript TextField object. You can use styles to customize the TextInput component; when an instance is disabled its contents display in a color represented by the "disabledColor" style. A TextInput component can also be formatted with HTML, or as a password field that disguises the text.

A TextInput component can be enabled or disabled in an application. In the disabled state, it doesn't receive mouse or keyboard input. When enabled, it follows the same focus, selection, and navigation rules as an ActionScript TextField object. When a TextInput instance has focus, you can also use the following keys to control it:

Key | Description
Arrow keys | Moves character one character left and right.
Shift + Tab | Moves focus to the previous object.
Tab | Moves focus to the next object.

For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

A live preview of each TextInput instance reflects changes made to parameters in the Property inspector or Component Inspector panel while authoring. Text is not selectable in the live preview and you cannot enter text into the component instance on the Stage.

When you add the TextInput component to an application, you can use the Accessibility panel to make it accessible to screen readers.

See also:

  • Using the TextInput component
  • Customizing the TextInput component
  • TextInput class


Using the TextInput component

You can use a TextInput component wherever you need a single-line text field. If you need a multiline text field, use the TextArea component. For example, you could use a TextInput component as a password field in a form. You could set up a listener that checks if field has enough characters when a user tabs out of the field. That listener could display an error message indicating that the proper number of characters must be entered.

See also:

  • TextInput component parameters
  • Creating an application with the TextInput component

TextInput component parameters

The following are authoring parameters that you can set for each TextInput component instance in the Property inspector or in the Component Inspector panel:

text specified the contents of the TextInput. You cannot enter carriage returns in the Property inspector or Component Inspector panel. The default value is "" (empty string).

editable indicates whether the TextInput component is editable (true) or not (false). The default value is true.

password indicates whether the field is a password field (true) or not (false). The default value is false.

You can write ActionScript to control these and additional options for TextInput components using its properties, methods, and events. For more information, see TextInput class.

Creating an application with the TextInput component

The following procedure explains how to add a TextInput component to an application while authoring. In this example, the component is a password field with an event listener that determines if the proper number of characters have been entered.

To create an application with the TextInput component, do the following:

  1. Drag a TextInput component from the Components panel to the Stage.
  2. In the Property inspector, enter the instance name passwordField.
  3. In the Property inspector, do the following:
    • Leave the text parameter blank.
    • Set the editable parameter to true.
    • Set the password parameter to true.
  4. Select Frame 1 in the Timeline, open the Actions panel, and enter the following code:
    textListener = new Object();
textListener.handleEvent = function (evt){
  if (evt.type == "enter"){
    trace("You must enter at least 8 characters");
  }
}
passwordField.addEventListener("enter", textListener);

    This code sets up an enter event handler on the TextInput passwordField instance that verifies that the user entered the proper number of characters.

  5. Once text is entered in the passwordField instance, you can get its value as follows:
    var login = passwordField.text;


Customizing the TextInput component

You can transform a TextInput component horizontally both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use UIObject.setSize() or any applicable properties and methods of the TextInput class.

When a TextInput component is resized, the border is resized to the new bounding box. The TextInput component doesn't use scroll bars, but the insertion point scrolls automatically as the user interacts with the text. The text field is then resized within the remaining area; there are no fixed-size elements in a TextInput component. If the TextInput component is too small to display the text, the text is clipped.

See also:

  • Using styles with the TextInput component
  • Using skins with the TextInput component

Using styles with the TextInput component

The TextInput component has its backgroundColor and borderStyle style properties defined on a class style declaration. Class styles override _global styles, therefore, if you want to set the backgroundColor and borderStyle style properties, you must create a different custom style declaration or on the instance.

A TextInput component supports the following styles:

Style | Description
color | The default color for text.
embedFonts | The fonts to embed in the document.
fontFamily | The font name for text.
fontSize | The point size for the font.
fontStyle | The font style, either "normal" or "italic".
fontWeight | The font weight, either "normal" or "bold".
textAlign | The text alignment: either "left", "right", or "center".
textDecoration | The text decoration, either "none" or "underline".

Using skins with the TextInput component

The TextArea component uses the RectBorder class to draw its border. You can use the setStyle() method (see UIObject.setStyle()) to change the following RectBorder style properties:

RectBorder styles | Letter
borderColor | a
highlightColor | b
borderColor | c
shadowColor | d
borderCapColor | e
shadowCapColor | f
shadowCapColor | g
borderCapColor | h

The style properties set the following positions on the border:


TextInput class

Inheritance UIObject > UIComponent > TextInput

ActionScript Class Name mx.controls.TextInput

The properties of the TextInput class allow you to set the text content, formatting, and horizontal position at runtime. You can also indicate whether the field is editable, and whether it is a "password" field. You can also restrict the characters that a user can enter.

Setting a property of the TextInput class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

The TextInput component uses the FocusManager to override the default Flash Player focus rectangle and draw a custom focus rectangle with rounded corners. For more information, see FocusManager class.

The TextInput component supports CSS styles and any additional HTML styles supported by Flash Player. For information about CSS support, see the W3C specification.

You can manipulate the text string by using the string returned by the text object.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.controls.TextInput.version);

Note: The following code returns undefined: trace(myTextInputInstance.version);.

Method summary for the TextInput class

Inherits all methods from UIObject and UIComponent.

Property summary for the TextInput class

Property | Description
TextInput.editable | A Boolean value indicating whether the field is editable (true) or not (false).
TextInput.hPosition | The horizontal scrolling position of the text field.
TextInput.length | The number of characters in a TextInput text field. This property is read only.
TextInput.maxChars | The maximum number of characters that a user can enter in a TextInput text field.
TextInput.maxHPosition | The maximum possible value for TextField.hPosition. This property is read-only.
TextInput.password | A Boolean value that indicates whether or not the input text field is a password field that hides the entered characters.
TextInput.restrict | Indicates which characters a user can enter in a text field.
TextInput.text | Sets the text content of a TextInput text field.

Inherits all methods from UIObject and UIComponent.

Event summary for the TextInput class

Event | Description
TextInput.change | Broadcast when the Input field changes.
TextInput.enter | Broadcast when the enter key is pressed.

Inherits all methods from UIObject and UIComponent.


TextInput.change

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(change){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.change = function(eventObject){
  ...
}
textInputInstance.addEventListener("change", listenerObject)

Description

Event; notifies listeners that text has changed. This event is broadcast after the text has changed. This event cannot be used prevent certain characters from being added to the component's text field; instead, use TextInput.restrict. This event is only triggered by user input, not by programmatic change.

The first usage example uses an on() handler and must be attached directly to a TextInput component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the instance myTextInput, sends "_level0.myTextInput" to the Output panel:

on(change){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (textInputInstance) dispatches an event (in this case, change) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example sets a flag in the application that indicates if contents in the TextInput field have changed:

form.change = function(eventObj){
  // eventObj.target is the component which generated the change event,
  // i.e., the Input component.
  myFormChanged.visible = true;  // set a change indicator if the contents changed;
}
myInput.addEventListener("change", form);

See also

UIEventDispatcher.addEventListener()


TextInput.editable

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textInputInstance.editable

Description

Property; a Boolean value that indicates whether the component is editable (true) or not (false). The default value is true.


TextInput.enter

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(enter){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.enter = function(eventObject){
  ...
}
textInputInstance.addEventListener("enter", listenerObject)

Description

Event; notifies listeners that the enter key has been pressed.

The first usage example uses an on() handler and must be attached directly to a TextInput component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the instance myTextInput, sends "_level0.myTextInput" to the Output panel:

on(enter){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (textInputInstance) dispatches an event (in this case, enter) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

This example sets a flag in the application that indicates if contents in the TextInput field have changed:

form.enter = function(eventObj){
  // eventObj.target is the component which generated the enter event,
  // i.e., the Input component.
  myFormChanged.visible = true;
// set a change indicator if the user presses enter;
}
myInput.addEventListener("enter", form);

See also

UIEventDispatcher.addEventListener()


TextInput.hPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textInputInstance.hPosition

Description

Property; defines the horizontal position of the text within the field. The default value is 0.

Example

The following code displays the leftmost characters in the field:

myTextInput.hPosition = 0;


TextInput.length

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

inputInstance.length

Description

Property (read-only); a number that indicates the number of characters in a TextInput component. A character such as tab ("\t") counts as one character. The default value is 0.

Example

The following code determines the number of characters in the myTextInput string and copies it to the length variable:

var length = myTextInput.length;


TextInput.maxChars

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textInputInstance.maxChars

Description

Property; the maximum number of characters that the text field can contain. A script may insert more text than the maxChars property allows; the maxChars property only indicates how much text a user can enter. If the value of this property is null, there is no limit to the amount of text a user can enter. The default value is null.

Example

The following example limits the number of characters a user can enter to 255:

myTextInput.maxChars = 255;


TextInput.maxHPosition

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textInputInstance.maxHPosition

Description

Property (read-only); indicates the maximum value of TextInput.hPosition. The default value is 0.

Example

The following code scrolls to the far right:

myTextInput.hPosition = myTextInput.maxHPosition;


TextInput.password

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textInputInstance.password

Description

Property; a Boolean value indicating whether the text field is a password field (true) or not (false). If the value of password is true, the text field is a password text field and hides the input characters. If false, the text field is not a password text field. The default value is false.

Example

The following code makes the text field a password field that displays all characters as asterisks (*):

myTextInput.password = true;


TextInput.restrict

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textInputInstance.restrict

Description

Property; indicates the set of characters that a user may enter into the text field. The default value is undefined. If the value of the restrict property is null or empty string (""), a user can enter any character. If the value of the restrict property is a string of characters, you can enter only characters in the string into the text field; the string is scanned from left to right. A range may be specified using the dash (-).

The restrict property only restricts user interaction; a script may put any text into the text field. This property does not synchronize with the Embed Font Outlines check boxes in the Property inspector.

If the string begins with "^", all characters are initially accepted and succeeding characters in the string are excluded from the set of accepted characters. If the string does not begin with "^", no characters are initially accepted and succeeding characters in the string are included in the set of accepted characters.

The backslash character may be used to enter the characters "-", "^", and "\", as in the following:

\^
\-
\\

When you enter the \ character in the Actions panel within "" (double quotes), it has a special meaning for the Actions panel's double quotes interpreter. It signifies that the character following the \ should be treated as is. For example, the following code is used to enter a single quotation mark:

var leftQuote = "\"";

The Actions panel's .restrict interpreter also uses \ as an escape character. Therefore, you may think that the following should work:

myText.restrict = "0-9\-\^\\";

However, since this expression is contained within double quotes, the following value is sent to the .restrict interpreter: 0-9-^\, and the .restrict interpreter doesn't understand this value.

Because you must enter this expression within double quotes, you must not only provide the expression for the .restrict interpreter, but you must also escape the Actions panel's built-in interpreter for double quotes. To send the value 0-9\-\^\\ to the .restrict interpreter, you must enter the following code:

myText.restrict = "0-9\\-\\^\\\\";

Example

In the following example, the first line of code limits the text field to uppercase letters, numbers, and spaces. The second line of code allows all characters except lowercase letters.

my_txt.restrict = "A-Z 0-9";
my_txt.restrict = "^a-z";

The following code allows a user to enter the characters "0 1 2 3 4 5 6 7 8 9 - ^ \" in the instance myText. You must use a double backslash to escape the characters "-, ^, and \". The first "\" escapes the " ", the second "\" tells the interpreter that the next character should not be treated as a special character, as in the following:

myText.restrict = "0-9\\-\\^\\\\";


TextInput.text

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

textInputInstance.text

Description

Property; the text contents of a TextInput component. The default value is "" (empty string).

Example

The following code places a string in the myTextInput instance then traces that string to the Output panel:

myTextInput.text = "The Royal Nonesuch";
trace(myTextInput.text); // traces "The Royal Nonesuch"


About the TransferObject interface

ActionScript Class Name mx.data.to.TransferObject

The TransferObject interface defines a set of methods that items managed by the DataSet component must implement. The DataSet.itemClassName property specifies the name of the transfer object class that will be instantiated each time a new item is needed. You can also specify this property for a selected DataSet component using the Property inspector.

Method summary for TransferObject interface

Method | Description
TransferObject.clone() | Creates a new instance of the transfer object.
TransferObject.getPropertyData() | Returns the data for this transfer object.
TransferObject.setPropertyData() | Sets the data for this transfer object.


TransferObject.clone()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

class itemClass implements mx.data.to.TransferObject
  function clone() {
    // your code here
  }
}

Returns

A copy of the transfer object.

Description

Method; creates an instance of the transfer object. The implementation of this method creates a copy of the existing transfer object and its properties and then returns that object.

Example

class itemClass implements mx.data.to.TransferObject {
  function clone():Object {
    var b:ContactClass = new ContactClass();
    for (var p in this) {
      b[p] = this[p];
    }
    return b;
  }
}


TransferObject.getPropertyData()

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

class itemClass implements mx.data.to.TransferObject {
  function getPropertyData() {
  // your code here
  }
}

Returns

An object.

Description

Method; returns the data for this transfer object. The implementation of this method can return an anonymous ActionScript object with properties and corresponding values.

Example

class Contact implements mx.data.to.TransferObject {
function getPropertyData():Object {
  var internalData:Object = { name:name, readOnly:_readOnly, phone:phone, zip:zip.zipPlus4 };
  return( internalData );
}


TransferObject.setPropertyData()

Availability

Flash Player 7.

Edition

Flash MX 2004.

Usage

class yourClass implements TransferObject {
  function setPropertyData(propData) {
  // your code here
  }
}

Parameters

propData An object that contains the data assigned to this transfer object.

Returns

Nothing.

Description

Method; sets the data for this transfer object. The propData parameter is an object whose fields contain the data assigned by the DataSet component to this transfer object.

Example

class Contact implements mx.data.to.TransferObject {

  function setPropertyData( data: Object ):Void {
    _readOnly = data.readOnly;
    phone = data.phone;
    zip = new mx.data.types.ZipCode( data.zip );
  }

  public var name:String;
  public var phone:String;
  public var zip:ZipCode;
  private var _readOnly:Boolean; // indicates if immutable
}


About the Tree component (Flash Professional only)

The Tree component allows a user to view hierarchical data. The tree appears within a box like the List component, but each item in a tree is called a node and can be either a leaf or a branch. By default, a leaf is represented by a text label beside a file icon and a branch is represented by a text label beside a folder icon with a disclosure triangle that a user can open to expose children. The children of a branch can either be leaves or branches themselves.

The data of a tree component must be provided from an XML data source. For more information, see Using the Tree component (Flash Professional only).

When a Tree instance has focus either from clicking or tabbing, you can use the following keys to control it:

Key | Description
Down arrow | Moves selection down one.
Up arrow | Moves selection up one.
Right arrow | Opens a selected branch node. If a branch is already open, moves to first child node.
Left arrow | Closes a selected branch node. If on a leaf node of a closed branch node, moves to parent node.
Space | Opens or closes a selected branch node.
End | Moves selection to the bottom of the list.
Home | Moves selection to the top of the list.
Page Down | Moves selection down one page.
Page Up | Moves selection up one page.
Control | Allows multiple noncontiguous selections.
Shift | Allows multiple contiguous selections.

The Tree component cannot be made accessible to screen readers.

See also:

  • Using the Tree component (Flash Professional only)
  • Customizing the Tree component (Flash Professional only)
  • Tree class (Flash Professional only)


Using the Tree component (Flash Professional only)

The Tree component can be used to represent hierarchical data such as e-mail client folders, file browser panes, or category browsing systems for inventory. Most often, the data for a tree is retrieved from a server in the form of XML, but it can also be well-formed XML that is created while authoring in Flash. The best way to create XML for the tree is to use the TreeDataProvider interface (Flash Professional only). You can also use the ActionScript XML class or build an XML string. After you create an XML data source (or load one from an external source) you assign it to Tree.dataProvider.

The Tree component is composed of two sets of APIs: the Tree class and the TreeDataProvider interface. The Tree class contains the visual configuration methods and properties. The TreeDataProvider interface allows you to construct XML and add it to multiple tree instances. A TreeDataProvider object broadcasts changes to any trees that use it. As well, any XML or XMLNode object that exists on the same frame as a tree or a menu is automatically given the TreeDataProvider methods and properties. For more information, see TreeDataProvider interface (Flash Professional only).

See also:

  • Formatting XML for the Tree component
  • Tree parameters
  • Creating an application with the Tree component

Formatting XML for the Tree component

The Tree component is designed to display hierarchical data structures. XML is the data model for the Tree component. It is important to understand the relationship of the XML data source to the Tree component.

Consider the following XML data source sample:

<node>
  <node label="Mail">
       <node label="INBOX"/>
       <node label="Personal Folder">
           <node label="Business" isBranch="true" />
           <node label="Demo" isBranch="true" />
           <node label="Personal" isBranch="true" />
           <node label="Saved Mail" isBranch="true" />
           <node label="bar" isBranch="true" />
       </node>
       <node label="Sent" isBranch="true" />
       <node label="Trash"/>
  </node>
</node>

Note: The isBranch attribute is read-only; you cannot set it directly. To set it, call the Tree.setIsBranch() method.

Nodes in the XML data source can have any name. Notice in the sample above that each node is named with the generic name "node". The tree reads through the XML and builds the display hierarchy based on the nested relationship of the nodes.

Each XML node can be displayed as one of two types in the Tree: branch or leaf. Branch nodes can contain multiple child nodes and appear as a folder icon with a disclosure triangle that allows users to open and close the folder. Leaf nodes appear as a file icon and cannot contain child nodes. Both leaves and branches can be roots; root nodes appear at the top level of the tree and have no parent. The icons are customizable; for more information, see Using skins with the Tree component.

There are many ways to structure XML. The Tree component is not designed to use all types of XML structures, so it's important to use XML that the Tree component can interpret. Do not nest node attributes in a child node; each node should contain all its necessary attributes. Also, the attributes of each node should be consistent to be useful. For example, to describe a mailbox structure with a Tree component, use the same attributes on each node (message, data, time, attachments, and so on). This allows the tree to know what it expects to render, and allows you to loop through the hierarchy to compare data.

When a Tree displays a node it uses the label attribute of the node by default as the text label. If any other attributes exist, they become additional properties of the node's attributes within the Tree.

The actual root node is interpreted as the Tree component itself. This means that the firstChild (in the sample, <node label="Mail">), is rendered as the root node in the Tree view. This means that a tree can have multiple root folders. In this sample, there is only one root folder displayed in the tree: "Mail". However, if you were to add sibling nodes at that level in the XML, multiple root nodes would be displayed in the Tree.

A data provider for a Tree always wants a node that has children it can display. It displays the first child of the XMLNode. When the XML is wrapped up in an XML object, the structure ends up looking like the following:

<XMLDocumentObject>
> <node>
>   <node label="Mail">
>        <node label="INBOX"/>
>        <node label="Personal Folder">
>            <node label="Business" isBranch="true" />
>            <node label="Demo" isBranch="true" />
>            <node label="Personal" isBranch="true" />
>            <node label="Saved Mail" isBranch="true" />
>            <node label="bar" isBranch="true" />
>        </node>
>        <node label="Sent" isBranch="true" />
>        <node label="Trash"/>
>   </node>
> </node>
</XMLDocumentObject>

The Flash Player wraps the XML nodes in an extra document node, which is passed to the tree. When the tree tries to display the XML, it tries to display <node> which doesn't have a label so it doesn't display correctly.

To avoid this issue, the data provider for the Tree component should point at the XMLDocumentObject's firstChild, as in the following:

myTree.dataProvider = myXML.firstChild;

Tree parameters

The following are authoring parameters that you can set for each Tree component instance in the Property inspector or in the Component Inspector panel:

multipleSelection A Boolean value that indicates whether a user can select multiple items (true) or not (false). The default value is false.

rowHeight The height of each row in pixels. The default value is 20.

You can write ActionScript to control these and additional options for the Tree component using its properties, methods, and events. For more information, see Tree class (Flash Professional only).

You cannot enter data parameters in the Property inspector or in the Component Inspector panel for the Tree component like you can with other components. For more information, see Using the Tree component (Flash Professional only) and Creating an application with the Tree component.

Creating an application with the Tree component

In this example, a developer is creating an e-mail application and chooses to use a Tree component to display the mailboxes.

You cannot enter data parameters in the Property inspector or in the Component Inspector panel like you can with other components. Because the data structure is more complex for Tree components, you must either import an XML object at runtime or build one in Flash while authoring. To create XML in Flash, you can use the TreeDataProvider, use the ActionScript XML object, or build an XML string. Each of these options is explained in the following procedures.

To add a Tree component to an application:

  1. In Flash, select File > New and select Flash Document.
  2. In the Components panel, double-click the Tree component to add it to the Stage.
  3. In the Property inspector, enter the instance name myTree.
  4. In the Actions panel on Frame 1, enter the following code that creates a change event handler:
    listenerObject = new Object();
listenerObject.change = function(evtObject){
  trace(evtObject.target.selectedItem.attributes.label + " was selected");
}
myTree.addEventListener("change", listenerObject);

    The trace action inside the handler sends a message to the Output panel every time an item in the tree is selected.

  5. Complete one of the following procedures to load or create an XML data source for the tree.

To load XML from an external file, do the following:

  1. Follow the steps above to add a Tree component to an application and create a change event handler.
  2. In the Actions panel on Frame 1, enter the following code:
    myTreeDP = new XML();
myTreeDP.ignoreWhite = true;
myTreeDP.load("http://myServer.myDomain.com/source.xml");
myTreeDP.onLoad = function(){
  myTree.dataProvider = myTreeDP;
}

    This code creates an ActionScript XML object called myTreeDP and calls the XML.load() method to load an XML data source. The code then defines an onLoad event handler that sets the dataProvider property of the myTree instance to the new XML object when the XML loads. For more information about the XML object, see its entry in ActionScript Dictionary Help.

  3. Select Control > Test Movie.

    In the SWF file, you can see the XML structure displayed in the Tree. Click items in the Tree to see the trace actions in the change event handler send the data values to the Output panel.

To use the TreeDataProvider class to create XML in Flash while authoring, do the following:

  1. Follow the steps in the first procedure above to add a Tree component to an application and create a change event handler.
  2. In the Actions panel on Frame 1, enter the following code:
    var myTreeDP = new XML();
myTreeDP.addTreeNode("Local Folders", 0);

// Use XML.firstChild to nest child nodes below Local Folders
var myTreeNode = myTreeDP.firstChild;
myTreeNode.addTreeNode("Inbox", 1);
myTreeNode.addTreeNode("Outbox", 2);
myTreeNode.addTreeNode("Sent Items", 3);
myTreeNode.addTreeNode("Deleted Items", 4);

// Assign the myTreeDP data source with the myTree component
myTree.dataProvider = myTreeDP;

// Set each of the 4 child nodes to be branches
for(var i=0; i<myTreeNode.childNodes.length; i++){
    var node = myTreeNode.getTreeNodeAt(i);
    myTree.setIsBranch(node, true);
}

    This code creates an XML object called myTreeDP. Any XML object on the same frame as a Tree component automatically receives all the properties and methods of the TreeDataProvider API. The second line of code creates a single root node called Local Folders. For detailed information about the rest of the code, see the comments (lines preceded with //) throughout the code.

  3. Select Control > Test Movie.

    In the SWF file, you can see the XML structure displayed in the Tree. Click items in the Tree to see the trace actions in the change event handler send the data values to the Output panel.

To use the ActionScript XML class to create XML, do the following:

  1. Follow the steps in the first procedure above to add a Tree component to an application and create a change event handler.
  2. In the Actions panel on Frame 1, enter the following code:
    // Create an XML object
var myTreeDP = new XML();
// Create node values
var myNode0 = myTreeDP.createElement("node");
myNode0.attributes.label = "Local Folders";
myNode0.attributes.data = 0;

var myNode1 = myTreeDP.createElement("node");
myNode1.attributes.label = "Inbox";
myNode1.attributes.data = 1;

var myNode2 = myTreeDP.createElement("node");
myNode2.attributes.label = "Outbox";
myNode2.attributes.data = 2;

var myNode3 = myTreeDP.createElement("node");
myNode3.attributes.label = "Sent Items";
myNode3.attributes.data = 3;

var myNode4 = myTreeDP.createElement("node");
myNode4.attributes.label = "Deleted Items";
myNode4.attributes.data = 4;
// Assign nodes to the hierarchy in the XML tree
myTreeDP.appendChild(myNode0);
myTreeDP.firstChild.appendChild(myNode1);
myTreeDP.firstChild.appendChild(myNode2);
myTreeDP.firstChild.appendChild(myNode3);
myTreeDP.firstChild.appendChild(myNode4);
// Assign the myTreeDP data source with the Tree control
myTree.dataProvider = myTreeDP;

    Please read the comments in the code (lines that begin with //) for a description of the code. For more information about the XML object, see its entry in ActionScript Dictionary Help.

  3. Select Control > Test Movie.

    In the SWF file, you can see the XML structure displayed in the Tree. Click items in the Tree to see the trace actions in the change event handler send the data values to the Output panel.

To use a well-formed string to create XML in Flash while authoring, do the following:

  1. Follow the steps in the first procedure above to add a Tree component to an application and create a change event handler.
  2. In the Actions panel on Frame 1, enter the following code:
    myTreeDP = new XML("<node label='Local Folders'><node label='Inbox' data='0'/><node label='Outbox' data='1'/></node>");
myTree.dataProvider = myTreeDP;

    The code above creates an XML object myTreeDP and assigns it to the dataProvider property of myTree.

  3. Select Control > Test Movie.

    In the SWF file, you can see the XML structure displayed in the Tree. Click items in the Tree to see the trace actions in the change event handler send the data values to the Output panel.


Customizing the Tree component (Flash Professional only)

You can transform a Tree component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use the setSize() method (see UIObject.setSize()). When a tree isn't wide enough to display the text of the nodes, the text clips.

See also:

  • Using styles with the Tree component
  • Using skins with the Tree component

Using styles with the Tree component

For the latest information about this feature, click the Update button at the top of the Help tab.

Using skins with the Tree component

For the latest information about this feature, click the Update button at the top of the Help tab.


Tree class (Flash Professional only)

Inheritance UIObject > UIComponent > View > ScrollView > ScrollSelectList > List > Tree

ActionScript Class Name mx.controls.Tree

Method summary for the Tree class

Method | Description
Tree.addTreeNode() | Adds a node to a tree instance.
Tree.addTreeNodeAt() | Adds a node at a specific location in a tree instance.
Tree.getDisplayIndex() | Returns the display index of a given node.
Tree.getIsBranch() | Specifies whether the folder is a branch (has a folder icon and an expander arrow).
Tree.getIsOpen() | Indicates whether a branch is open or closed.
Tree.getNodeDisplayedAt() | Returns the display index of a given node.
Tree.getTreeNodeAt() | Returns a node on the root of the tree.
 | Updates the component.
Tree.removeAll() | Removes all nodes from a tree instance and refreshes the tree.
Tree.removeTreeNodeAt() | Removes a node at a specified position and refreshes the tree.
Tree.setIsBranch() | Indicates whether a node is a branch (receives folder icon and expander arrow).
Tree.setIcon() | Specifies whether a node is open or closed.
Tree.setIsOpen() | Specifies a symbol to be used as an icon for a node.

Inherits all methods from UIComponent, UIObject, View, ScrollView, ScrollSelectList, and List class.

Property summary for the Tree class

Property | Description
Tree.dataProvider | Specifies an XML data source.
Tree.firstVisibleNode | Specifies the first node at the top of the display.
Tree.selectedNode | Specifies the selected node in a tree instance.
Tree.selectedNodes | Specifies the selected nodes in a tree instance.

Inherits all properties from UIComponent, UIObject, View, ScrollView, ScrollSelectList, and List class.

Event summary for the Tree class

Event | Description
Tree.nodeClose | Broadcast when a node is closed by a user.
Tree.nodeOpen | Broadcast when a node is opened by a user.

Inherits all events from UIComponent, UIObject, View, ScrollView, ScrollSelectList, and List class.


Tree.addTreeNode()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

myTree.addTreeNode(label [, data])

Usage 2:

myTree.addTreeNode(child)

Parameters

label A string that displays the node, or an object with a "label" field (or whatever label field name is specified by the labelField property).

data An object of any type that is associated with the node. This parameter is optional.

child Any XMLNode object.

Returns

The added XML node.

Description

Method; adds a child node to the tree. The node is either constructed from the information supplied in the label and data parameters (Usage 1), or from the prebuilt child node which is an XMLNode object (Usage 2). Adding a preexisting node removes the node from its previous location.

Note: Calling this method refreshes the view.

Example

The following code adds a new node to the root of myTree. The second line of code moves a node from the root of mySecondTree to the root of myTree:

myTree.addTreeNode("Inbox", 3);
myTree.addTreeNode(mySecondTree.getTreeNodeAt(3));


Tree.addTreeNodeAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

myTree.addTreeNodeAt(index, label [, data])

Usage 2:

myTree.addTreeNodeAt(index, child)

Parameters

index The order (among the child nodes) in which the node should be added.

label A string that displays the node.

data An object of any type that is associated with the node. This parameter is optional.

child Any XMLNode object.

Returns

The added XML node.

Description

Method; adds a node at the specified location in the tree. The node is either constructed from the information supplied in the label and data parameters (Usage 1), or from the prebuilt XMLNode object (Usage 2). Adding a preexisting node removes the node from its previous location.

Note: Calling this method refreshes the view.

Example

The following example adds a new node as the second child of the root of myTree. The second line moves a node from mySecondTree to become the fourth child of the root of myTree:

myTree.addTreeNodeAt(1, "Inbox", 3);
myTree.addTreeNodeAt(3,mySecondTree.getTreeNodeAt(3));


Tree.dataProvider

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.dataProvider

Description

Property; the dataProvider property can be either XML or a string. If the dataProvider is an XML object, it is added directly to the tree. If the dataProvider is a string, it must contain valid XML that is read by the tree and converted to an XML object.

You can either load XML from an external source at runtime or create it in Flash while authoring. To create XML, you can use either the TreeDataProvider methods, or the built-in ActionScript XML class methods and properties. You can also create a string that contains XML.

XML objects that are on the same frame as a Tree component automatically contain the TreeDataProvider methods and properties. You can use the ActionScript XML or XMLNode objects.

Example

The following example imports an XML file and assigns it to the myTree instance of the Tree component:

myTreeDP = new XML();
myTreeDP.ignoreWhite = true;
myTreeDP.load("http://myServer.myDomain.com/source.xml");
myTreeDP.onLoad = function(){
   myTree.dataProvider = myTreeDP;
}

Note: Most XML files contain white space and Flash does not ignore that white space unless you set the ignoreWhite property to true.


Tree.firstVisibleNode

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.firstVisibleNode

Description

Property; the first node at the top of the display. If the node is under a node that hasn't been expanded, setting firstVisibleNode has no effect. The default value is the first visible node or undefined if there is no visible node. This value of this property is an XMLNode object.

Note: Setting this property is analogous to setting List.vPosition.

Example

The following example sets the scroll position to the top of the display:

myTree.firstVisibleNode = myTree.getTreeNodeAt(0);


Tree.getIsBranch()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.getIsBranch(node)

Parameters

node An XMLNode object.

Returns

A Boolean value that indicates whether the node is a branch (true) or not (false).

Description

Method; indicates whether the specified node has a folder icon and expander arrow (is a branch). This is set automatically when children are added to the node. You only need to call setIsBranch() to create empty folders. For more information, see Tree.setIsBranch().

Example

The following code assigns the node state to a variable:

var open = myTree.getIsBranch(myTree.getTreeNodeAt(1));

See also

Tree.setIsBranch()


Tree.getIsOpen()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.getIsOpen(node)

Parameters

node An XMLNode object.

Returns

A Boolean value that indicates whether the tree is open (true) or not (false).

Description

Method; indicates whether the specified node is open or closed.

Example

The following code assigns the state of the node to a variable:

var open = myTree.getIsOpen(myTree.getTreeNodeAt(1));


Tree.getDisplayIndex()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.getDisplayIndex(node)

Parameters

node An XMLNode object.

Returns

The index of the node specified, or undefined if the node is not currently displayed.

Description

Method; returns the display index of the node specified in the node parameter.

The display index is an array of items that can be viewed in the tree window. For example, any children of a closed not are not in the display index. The display index starts with 0 and proceeds through the visible items regardless of parent. In other words, the display index is the row number, starting with 0, of the displayed rows.

Example

The following code gets the display index of myNode:

var x = myTree.getDisplayIndex(myNode);


Tree.getNodeDisplayedAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.getNodeDisplayedAt(index)

Parameters

index An integer representing the display position in the viewable area of the tree. This number is zero-based; the node at the first position is 0, second position is 1, and so on.

Returns

The specified XMLNode object.

Description

Method; maps a display index of the tree onto the node that is displayed there. For example, if the fifth row of the tree showed a node that is eight levels deep into the hierarchy, that node would be returned by checking getNodeDisplayedAt(4).

The display index is an array of items that can be viewed in the tree window. For example, any children of a closed not are not in the display index. The display index starts with 0 and proceeds through the visible items regardless of parent. In other words, the display index is the row number, starting with 0, of the displayed rows.

Note: Display indices change every time nodes open and close.

Example

The following code gets a reference to the XML node that is the second row displayed in myTree:

myTree.getNodeDisplayedAt(1);


Tree.getTreeNodeAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.getTreeNodeAt(index)

Parameters

index The index number of a tree.

Returns

An XMLNode object.

Description

Method; returns the specified node on the root of myTree.

Example

The following code gets the second node on the first level in the tree myTree:

myTree.getTreeNodeAt(1);


Tree.nodeClose

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.nodeClose = function(eventObject){
  // insert your code here
}
myTreeInstance.addEventListener("nodeClose", listenerObject)

Description

Event; broadcast to all registered listeners when the nodes of a Tree component are closed by a user.

V2 components use a dispatcher/listener event model. The Tree component broadcasts a nodeClose event when one of its nodes is clicked closed and the event is handled by a function, also called a handler, that is attached to a listener object (listenerObject) that you create.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The Tree.nodeClose event's event object has one additional property: node (the XML node that closed). For more information about event objects, see Event Objects.

Example

In the following example, a handler called myTreeListener is defined and passed to the myTree.addEventListener() method as the second parameter. The event object is captured by the nodeClose handler in the evtObject parameter. When the nodeClose event is broadcast, a trace statement is sent to the Output panel, as follows:

myTreeListener = new Object();
myTreeListener.nodeClose = function(evtObject){
  trace(evtObject.node + " node was closed");
}
myTree.addEventListener("nodeClose", myTreeListener);


Tree.nodeOpen

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

listenerObject = new Object();
listenerObject.nodeOpen = function(eventObject){
  // insert your code here
}
myTreeInstance.addEventListener("nodeOpen", listenerObject)

Description

Event; broadcast to all registered listeners when a user opens a node on a Tree component.

V2 components use a dispatcher/listener event model. The Tree component dispatches a nodeOpen event when a node is clicked open by a user and the event is handled by a function, also called a handler, that is attached to a listener object (listenerObject) that you create. You call the addEventListener() method and pass it the name of the handler as a parameter.

When the event is triggered, it automatically passes an event object (eventObject) to the handler. Each event object has a set of properties that contain information about the event. You can use these properties to write code that handles the event. The Tree.nodeOpen event's event object has one additional property: node (the XML node that was opened). For more information about event objects, see Event Objects.

Example

In the following example, a handler called myTreeListener is defined and passed to the myTree.addEventListener() method as the second parameter. The event object is captured by nodeOpen handler in the evtObject parameter. When the nodeOpen event is broadcast, a trace statement is sent to the Output panel, as follows:

myTreeListener = new Object();
myTreeListener.nodeOpen = function(evtObject){
  trace(evtObject.node + " node was opened");
}
myTree.addEventListener("nodeOpen", myTreeListener);


Tree.refresh()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.refresh()

Parameters

None.

Returns

Nothing.

Description

Method; updates the tree.


Tree.removeAll()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.removeAll()

Parameters

None.

Returns

Nothing.

Description

Method; removes all nodes and refreshes the tree.

Example

The following code empties myTree:

myTree.removeAll();


Tree.removeTreeNodeAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.removeTreeNodeAt(index)

Parameters

index The index number of a tree child. Each child of a tree is assigned a zero-based index in the order that is was created.

Returns

An XMLNode object, or undefined if there is an error.

Description

Method; removes a node (specified by its index position) on the root of the tree and refreshes the tree.

Example

The following code removes the fourth child of the root of the tree myTree:

myTree.removeTreeNodeAt(3);


Tree.setIsBranch()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.setIsBranch(node, isBranch)

Parameters

node An XML node.

isBranch A Boolean value indicating whether the node is a branch (true), or not (false).

Returns

Nothing.

Description

Method; specifies whether the node has a folder icon and expander arrow and either has children or can have children. A node is automatically set as a branch when it has children; you only need to call setIsBranch() when you want create an empty folder. You may want to create branches that don't yet have children if, for example, you only want child nodes to load when a user opens a folder.

Calling the setIsBranch() method refreshes any views.

Example

The following code makes a node of myTree a branch;

myTree.setIsBranch(myTree.getTreeNodeAt(1), true);


Tree.setIcon()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.setIcon(node, linkID[, linkID2])

Parameters

node An XML node.

linkID The linkage identifier of a symbol to be used as an icon beside the node. This parameter is used for leaf nodes and for the closed state of branch nodes.

linkID2 The linkage identifier of a symbol to be used as an icon beside the node. This parameter is used for the icon that represents the open state of branch nodes.

Returns

Nothing.

Description

Method; specifies an icon for the specified node. This method takes one parameter (linkID) for leaf nodes and two parameters (linkID and linkID2) for branches (the closed and open icons). The second parameter is ignored for leaf (non-branch) nodes, and if only one parameter is specified for a branch node, the icon is used for both the closed and open states.

Example

The following code specifies that a symbol with the linkage identifier "imageIcon" be used beside the second node of myTree:

myTree.setIcon(myTree.getTreeNodeAt(1), "imageIcon");


Tree.setIsOpen()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.setIsOpen(node, isOpen[, noEvent])

Parameters

node An XML node.

isOpen A Boolean value that opens a node (true) or closes it (false).

noEvent A Boolean value that animates the opening transition (true) or not (false). This parameter is optional.

Returns

Nothing.

Description

Method; opens or closes a node.

Example

The following code opens a node of myTree:

myTree.setIsOpen(myTree.getTreeNodeAt(1), true);


Tree.selectedNode

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.selectedNode

Description

Property; specifies the selected node in a tree instance.

Example

The following example specifies the first child node in myTree:

myTree.selectedNode = myTree.getTreeNodeAt(0);

See also

Tree.selectedNodes


Tree.selectedNodes

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myTree.selectedNodes

Description

Property; specifies the selected nodes in a tree instance.

Example

The following example selects the first and third child nodes in myTree:

myTree.selectedNodes = [myTree.getTreeNodeAt(0), myTree.getTreeNodeAt(2)];

See also

Tree.selectedNode


About the TreeDataProvider interface (Flash Professional only)

The TreeDataProvider is an interface; it does not need to be instantiated to be used. If a Tree class is packaged in a SWF file, all XML instances in the SWF file contain the TreeDataProvider API. All nodes in a Tree are XML objects that contain the TreeDataProvider API.

It's best to use the TreeDataProvider API methods to create XML for the Tree.dataProvider property because only TreeDataProvider broadcasts events to Tree components that refresh the tree's display. Built-in XML class methods can be used to create XML, but they don't broadcast events that will refresh the display.

You can use the TreeDataProvider API methods to control the data model and the data display. You can use built-in XML class methods for read-only tasks like traversing through the tree hierarchy.

The property that holds the text to be displayed can be selected by specifying a labelField or a labelFunction property. For example, the code myTree.labelField = "fred"; results in the value of the property myTreeDP.attributes.fred being queried for the display text.

Method summary for the TreeDataProvider interface

Event | Description
TreeDataProvider.addTreeNode() | Adds a child node at the end of a parent node.
TreeDataProvider.addTreeNodeAt() | Adds a child node at a specified location on the parent node.
TreeDataProvider.getTreeNodeAt() | Returns the specified child of a node.
TreeDataProvider.removeTreeNode() | Removes a node and all the node's descendents from the node's parent.
TreeDataProvider.removeTreeNodeAt() | Removes a node and all the node's descendents from the index position of the child node.

Property summary for the TreeDataProvider interface

Property | Description
TreeDataProvider.attributes.data | Specifies the data to associate with a node.
TreeDataProvider.attributes.label | Specifies the text to be displayed next to a node.


TreeDataProvider.addTreeNode()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

someNode.addTreeNode(label, data)

Usage 2:

someNode.addTreeNode(child)

Parameters

label A string that displays the node.

data An object of any type that is associated with the node.

child Any XMLNode object.

Returns

The added XML node.

Description

Method; adds a child node at the root of the tree. The node is either constructed from the information supplied in the label and data parameters (Usage 1), or from the prebuilt child node, which is an XMLNode object (Usage 2). Adding a preexisting node removes the node from its previous location.

Calling this method refreshes the display of the tree instance.

Example

The first line of code in the following example locates the node to which to add a child. The second line adds a new node to a specified node, as follows:

var myTreeNode = myTreeDP.firstChild.firstChild;
myTreeNode.addTreeNode("Inbox", 3);

The following code moves a node from one tree to the root of another tree:

myTreeNode.addTreeNode(mySecondTree.getTreeNodeAt(3));


TreeDataProvider.addTreeNodeAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

Usage 1:

someNode.addTreeNodeAt(index, label, data)

Usage 2:

someNode.addTreeNodeAt(index, child)

Parameters

index An integer that indicates the index position among the child nodes to which the node should be added.

label A string that displays the node.

data An object of any type that is associated with the node.

child Any XMLNode object.

Returns

The added XML node.

Description

Method; adds a child node at the specified location in the parent node. The node is either constructed from the information supplied in the label and data parameters (Usage 1), or from the prebuilt child node, which is an XMLNode object (Usage 2). Adding a preexisting node removes the node from its previous location.

Calling this method refreshes the display of the tree instance.

Example

The following code locates the node to which you will add a node and adds a new node as the second child of the root:

var myTreeNode = myTreeDP.firstChild.firstChild;
myTreeNode.addTreeNodeAt(1, "Inbox", 3);

The following code moves a node from one tree to become the fourth child of the root of another tree:

myTreeNode.addTreeNodeAt(3, mySecondTree.getTreeNodeAt(3));


TreeDataProvider.attributes.data

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

someNode.attributes.data

Description

Property; specifies the data to associate with the node. This adds the value as an attribute within the XML node object. Setting this property does not refresh any tree displays. This property can be of any data type.

Example

The following code locates the node to adjust and sets its data property:

var myTreeNode = myTreeDP.firstChild.firstChild;
myTreeNode.attributes.data = "hi"; // results in <node data = "hi">;

See also

TreeDataProvider.attributes.label


TreeDataProvider.attributes.label

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

someNode.attributes.label

Description

Property; a string that specifies the text displayed for the node. This is written to an attribute of the XML node object. Setting this property does not refresh the displays of any tree.

Example

The following code locates the node to adjust and sets its label property. The result of the following code is "<node label="Mail">":

var myTreeNode = myTreeDP.firstChild.firstChild;
myTreeNode.attributes.label = "Mail";

See also

TreeDataProvider.attributes.data


TreeDataProvider.getTreeNodeAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

someNode.getTreeNodeAt(index)

Parameters

index An integer representing the position of the child node in the current node.

Returns

The specified node.

Description

Method; returns the specified child node of the node.

Example

The following code locates a node and then gets the second child of myTreeNode:

var myTreeNode = myTreeDP.firstChild.firstChild;
myTreeNode.getTreeNodeAt(1);


TreeDataProvider.removeTreeNode()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

someNode.removeTreeNode()

Parameters

None.

Returns

The removed XML node, or undefined if an error occurs.

Description

Method; removes the specified node, and any descendents, from its parent.

Example

The following code removes a node:

myTreeDP.firstChild.removeTreeNode();


TreeDataProvider.removeTreeNodeAt()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

someNode.removeTreeNodeAt(index)

Parameters

index An integer indicating the position of the node to be removed.

Returns

The removed XML node, or undefined if an error occurs.

Description

Method; removes a node (and all descendents) specified by the current node and index position of the child node. Calling this method refreshes the view.

Example

The following code removes the fourth child of a given node:

myTreeDP.firstChild.removeTreeNodeAt(3);


About the UIComponent class

All v2 components extend UIComponent; it is not a visual component. The UIComponent class contains functions and properties that allow Macromedia components to share some common behavior. The UIComponent class allows you to do the following:

  • Receive focus and keyboard input
  • Enable and disable components
  • Resize by layout

To use the methods and properties of the UIComponent, you call them directly from whichever component you are using. For example, to call the UIComponent.setFocus() method from the RadioButton component, you would write the following code:

myRadioButton.setFocus();

You only need to create an instance of UIComponent if you are using the Macromedia Component V2 Architecture to create a new component. Even in that case, UIComponent is often created implicitly by other subclasses like Button. If you do need to create an instance of UIComponent, use the following code:

class MyComponent extends UIComponent;

See also:

  • UI Component class (API)


UI Component class (API)

Inheritance UIObject > UIComponent

ActionScript Class Name mx.core.UIComponent

Method summary for the UIComponent class

Method | Description
UIComponent.getFocus() | Returns a reference to the object that has focus.
UIComponent.setFocus() | Sets focus to the component instance.

Inherits all methods from the UIObject class.

Property summary for the UIComponent class

Property | Description
UIComponent.enabled | Indicates whether the component can receive focus and input.
UIComponent.tabIndex | A number indicating the tab order for a component in a document.

Inherits all properties from the UIObject class.

Event summary for the UIComponent class

Event | Description
UIComponent.focusIn | Broadcast when an object receives focus.
UIComponent.focusOut | Broadcast when an object loses focus.
UIComponent.keyDown | Broadcast when a key is pressed.
UIComponent.keyUp | Broadcast when a key is released.

Inherits all events from the UIObject class.


UIComponent.focusIn

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

on(focusIn){
  ...
}
listenerObject = new Object();
listenerObject.focusIn = function(eventObject){
  ...
}
componentInstance.addEventListener("focusIn", listenerObject)

Description

Event; notifies listeners that the object has received keyboard focus.

The first usage example uses an on() handler and must be attached directly to a component instance.

The second usage example uses a dispatcher/listener event model. A component instance (componentInstance) dispatches an event (in this case, focusIn) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following code disables a button while a user types in the text field txt:

txtListener.handleEvent = function(eventObj) {
  form.button.enabled = false;
}
txt.addEventListener("focusIn", txtListener);

See also

UIEventDispatcher.addEventListener()


UIComponent.focusOut

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

on(focusOut){
  ...
}
listenerObject = new Object();
listenerObject.focusOut = function(eventObject){
  ...
}
componentInstance.addEventListener("focusOut", listenerObject)

Description

Event; notifies listeners that the object has lost keyboard focus.

The first usage example uses an on() handler and must be attached directly to a component instance.

The second usage example uses a dispatcher/listener event model. A component instance (componentInstance) dispatches an event (in this case, focusOut) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following code enables a button when a user leaves the text field txt:

txtListener.handleEvent = function(eventObj){
  if (eventObj.type == focusOut){
       form.button.enabled = true;
  }
}
txt.addEventListener("focusOut", txtListener);

See also

UIEventDispatcher.addEventListener()


UIComponent.enabled

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.enabled

Description

Property; indicates whether the component can accept focus and mouse input. If the value is true, it can receive focus and input; if the value is false, it can't. The default value is true.

Example

The following example sets the enabled property of a CheckBox component to false:

checkBoxInstance.enabled = false;


UIComponent.getFocus()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.getFocus();

Parameters

None.

Returns

A reference to the object that currently has focus.

Description

Method; returns a reference to the object that has keyboard focus.

Example

The following code returns a reference to the object that has focus and assigns it to the tmp variable:

var tmp = checkbox.getFocus();


UIComponent.keyDown

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

on(keyDown){
  ...
}
listenerObject = new Object();
listenerObject.keyDown = function(eventObject){
  ...
}
componentInstance.addEventListener("keyDown", listenerObject)

Description

Event; notifies listeners when a key is pressed. This is a very low-level event that should not be used unless necessary because it can impact system performance.

The first usage example uses an on() handler and must be attached directly to a component instance.

The second usage example uses a dispatcher/listener event model. A component instance (componentInstance) dispatches an event (in this case, keyDown) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following code makes an icon blink when a key is pressed:

formListener.handleEvent = function(eventObj)
{
  form.icon.visible = !form.icon.visible;
}
form.addEventListener("keyDown", formListener);


UIComponent.keyUp

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

on(keyUp){
  ...
}
listenerObject = new Object();
listenerObject.keyUp = function(eventObject){
  ...
}
componentInstance.addEventListener("keyUp", listenerObject)

Description

Event; notifies listeners when a key is released. This is a very low-level event that should not be used unless necessary because it can impact system performance.

The first usage example uses an on() handler and must be attached directly to a component instance.

The second usage example uses a dispatcher/listener event model. A component instance (componentInstance) dispatches an event (in this case, keyUp) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following code makes an icon blink when a key is released:

formListener.handleEvent = function(eventObj)
{
  form.icon.visible = !form.icon.visible;
}
form.addEventListener("keyUp", formListener);


UIComponent.setFocus()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.setFocus();

Parameters

None.

Returns

Nothing.

Description

Method; sets the focus to this component instance. The instance with focus receives all keyboard input.

Example

The following code sets focus to the checkbox instance:

checkbox.setFocus();


UIComponent.tabIndex

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

instance.tabIndex

Description

Property; a number indicating the tabbing order for a component in a document.

Example

The following code sets the value of tmp to the tabIndex property of the checkbox instance:

var tmp = checkbox.tabIndex;


About the UIEventDispatcher

ActionScript Class Name mx.events.EventDispatcher; mx.events.UIEventDispatcher

Events allow you to know when the user has interacted with a component, and also to know when important changes have happened in the appearance or life cycle of a component, such as the creation or destruction of a component or if its size changes.

Each component broadcasts different events and those events are listed in each component entry. There are several ways to use component events in ActionScript code. For more information, see About component events.

Use the UIEventDispatcher.addEventListener() to register a listener with a component instance. The listener is invoked when a component's event is triggered.

See also:

  • UIEventDispatcher.addEventListener()
  • Event Objects


UIEventDispatcher.addEventListener()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004.

Usage

componentInstance.addEventListener(event, listener)

Parameters

event A string that is the name of the event.

listener A reference to a listener object or function.

Returns

Nothing.

Description

Method; registers a listener object with a component instance that is broadcasting an event. When the event is triggered, the listener object or function is notified. You can call this method from any component instance. For example, the following code registers a listener to the component instance myButton:

myButton.addEventListener("click", myListener);

You must define the listener as either an object or a function before you call addEventListener() to register the listener with the component instance. If the listener is an object, it must have a callback function defined that is invoked when the event is triggered. Usually, that callback function has the same name as the event with which the listener is registered. If the listener is a function, the function is invoked when the event is triggered. For more information, see Using component event listeners.

You can register multiple listeners to a single component instance, but you must use a separate call to addEventListener() for each listener. Also, you can register one listener to multiple component instances, but you must use a separate call to addEventListener() for each instance. For example, the following code defines one listener object and assigns it to two Button component instances:

lo = new Object();
lo.click = function(evt){
  if (evt.target == button1){
    trace("button 1 clicked");
  } else if (evt.target == button2){
    trace("button 2 clicked");
  }
}
button1.addEventListener("click", lo);
button2.addEventListener("click", lo);

Execution order is not guaranteed. You cannot expect one listener to be called before another.

An event object is passed to the listener as a parameter. The event object has properties that contain information about the event that occurred. You can use the event object inside the listener callback function to access information about the type of event that occurred and which instance broadcast the event. In the example above, the event object is evt (you can use any identifier as the event object name) and it is used within the if statements to determine which button instance was clicked. For more information, see Event Objects.

Example

The following example defines a listener object, myListener, and defines the callback function click. It then calls addEventListener() to register the myListener listener object with the component instance myButton. To test this code, place a button component on the Stage with the instance name myButton, and place the following code in Frame 1:

myListener = new Object();
myListener.click = function(evt){
  trace(evt.type + " triggered");
}
myButton.addEventListener("click", myListener);


UIEventDispatcher.removeEventListener()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004 and Flash MX Professional 2004.

Usage

componentInstance.removeEventListener(event, listener)

Parameters

event A string that is the name of the event.

listener A reference to a listener object or function.

Returns

Nothing.

Description

Method; unregisters a listener object from a component instance that is broadcasting an event.


Event Objects

An event object is passed to a listener as a parameter. The event object is an ActionScript object that has properties that contain information about the event that occurred. You can use the event object inside the listener callback function to access the name of the event that was broadcast, or the instance name of the component that broadcast the event. For example, the following code uses the target property of the evtObj event object to access the label property of the myButton instance and send the value to the Output panel:

listener = new Object();
listener.click = function(evtObj){
  trace("The " + evtObj.target.label + " button was clicked");
}
myButton.addEventListener("click", listener);

Some event object properties are defined in the W3C specification but aren't implemented in version 2 (v2) of the Macromedia Component Architecture. Every v2 event object has the properties listed in the table below. Some events have additional properties defined, and if so, the properties are listed in the event's entry.

Properties of the event object

Property | Description
type | A String indicating the name of the event.
target | A reference to the component instance broadcasting the event.


About the UIObject class

Inheritance MovieClip > UIObject

ActionScript Class Name mx.core.UIObject

UIObject is the base class for all v2 components; it is not a visual component. The UIObject class wraps the ActionScript MovieClip object and contains functions and properties that allow Macromedia v2 components to share some common behavior. Wrapping the MovieClip class allows Macromedia to add new events and extend functionality in the future without breaking content. Wrapping the MovieClip class also allows users who aren't familiar with the traditional Flash concepts of "movie" and "frame" to use the API to create component-based applications without learning those concepts.

The UIObject class implements the following:

  • Styles
  • Events
  • Resize by scaling

To use the methods and properties of the UIObject, you call them directly from whichever component you are using. For example, to call the UIObject.setSize() method from the RadioButton component, you would write the following code:

myRadioButton.setSize(30, 30);

You only need to create an instance of UIObject if you are using the Macromedia Component v2 Architecture to create a new component. Even in that case, UIObject is often created implicitly by other subclasses like Button. If you do need to create an instance of UIObject, use the following code:

class MyComponent extends UIObject;

Method summary for the UIObject class

Method | Description
UIObject.createObject() | Creates a subobject on an object.
UIObject.createClassObject() | Creates an object on the specified class.
UIObject.destroyObject() | Destroys a component instance.
UIObject.invalidate() | Marks the object so it will be redrawn on the next frame interval.
UIObject.move() | Moves the object to the requested position.
UIObject.redraw() | Forces validation of the object so it draws in the current frame.
UIObject.setSize() | Resizes the object to the requested size.
UIObject.setSkin() | Sets a skin in the object.

Property summary for the UIObject class

Property | Description
UIObject.bottom | The position of the bottom edge of the object relative to the bottom edge of its parent. Read-only.
UIObject.height | The height of the object in pixels. Read-only.
UIObject.left | The left position of the object in pixels. Read-only.
UIObject.right | The position of the right edge of the object relative to the right edge of its parent. Read-only.
UIObject.scaleX | A number indicating the scaling factor in the x direction of the object relative to its parent.
UIObject.scaleY | A number indicating the scaling factor in the y direction of the object relative to its parent.
UIObject.top | The position of the top edge of the object relative to its parent. Read-only.
UIObject.visible | A Boolean value indicating whether the object is visible (true) or not (false).
UIObject.width | The width of the object in pixels. Read-only.
UIObject.x | The left position of the object in pixels. Read-only.
UIObject.y | Returns the position of the top edge of the object relative to its parent. Read-only.

Event summary for the UIObject class

Event | Description
UIObject.draw | Broadcast when an object is about to draw its graphics.
UIObject.hide | Broadcast when an object's state changes from visible to invisible.
UIObject.load | Broadcast when subobjects are being created.
UIObject.move | Broadcast when the object has moved.
UIObject.resize | Broadcast when the subobjects are being unloaded.
UIObject.reveal | Broadcast when an object's state changes from invisible to visible.
UIObject.unload | Broadcast when the subobjects are being unloaded.


UIObject.bottom

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.bottom

Description

Property (read-only); a number indicating the bottom position of the object in pixels relative to its parent's bottom. To set this property, call the UIObject.move() method.

Example

This example moves the check box so it aligns under the bottom edge of the list box:

myCheckbox.move(myCheckbox.x, form.height - listbox.bottom);


UIObject.createObject()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.createObject(linkageName, instanceName, depth, initObject)

Parameters

linkageName A string indicating the linkage identifier of a symbol in the Library panel.

instanceName A string indicating the instance name of the new instance.

depth A number indicating the depth of the new instance.

initObject An object containing initialization properties for the new instance.

Returns

A UIObject that is an instance of the symbol.

Description

Method; creates a subobject on an object. Generally only used by component or advanced developers.

Example

The following example creates a CheckBox instance on the form object:

form.createObject("CheckBox", "sym1", 0);


UIObject.createClassObject()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.createClassObject(className, instanceName, depth, initObject)

Parameters

className An object indicating the class of the new instance.

instanceName A string indicating the instance name of the new instance.

depth A number indicating the depth of the new instance.

initObject An object containing initialization properties for the new instance.

Returns

A UIObject that is an instance of the specified class.

Description

Method; creates a subobject of an object. Generally only used by component or advanced developers. This method allows you to create components at runtime.

You need to specify the class package name. Do one of the following:

import mx.controls.Button;
createClassObject(Button,"button2",5,{label:"Test Button"});

or

createClassObject(mx.controls.Button,"button2",5,{label:"Test Button"});

Example

The following example creates a CheckBox object:

form.createClassObject(CheckBox, "cb", 0, {label:"Check this"});


UIObject.destroyObject()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.destroyObject(instanceName)

Parameters

instanceName A string indicating the instance name of the object to be destroyed.

Returns

Nothing.

Description

Method; destroys a component instance.


UIObject.draw

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

on(draw){
  ...
}
listenerObject = new Object();
listenerObject.draw = function(eventObject){
  ...
}
componentInstance.addEventListener("draw", listenerObject)

Description

Event; notifies listeners that the object is about to draw its graphics. This is a very low-level event that should not be used unless necessary because it can affect system performance.

The first usage example uses an on() handler and must be attached directly to a component instance.

The second usage example uses a dispatcher/listener event model. A component instance (componentInstance) dispatches an event (in this case, draw) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following code redraws the object form2 when the form object is drawn:

formListener.draw = function(eventObj){
  form2.redraw(true);
}
form.addEventListener("draw", formListener);

See also

UIEventDispatcher.addEventListener()


UIObject.height

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.height

Description

Property (read-only); a number indicating the height of the object in pixels. To change the height property, call the UIObject.setSize() property.

Example

The following example makes the check box taller:

myCheckbox.setSize(myCheckbox.width, myCheckbox.height + 10);


UIObject.hide

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

on(hide){
  ...
}
listenerObject = new Object();
listenerObject.hide = function(eventObject){
  ...
}
componentInstance.addEventListener("hide", listenerObject)

Description

Event; broadcast when the object's visible property is changed from true to false.

Example

The following handler displays a message in the Output panel when the object it's attached to becomes invisible.

on(hide) {
  trace("I've become invisible.");
}

See also

UIObject.reveal


UIObject.getStyle()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.getStyle(propertyName)

Parameters

propertyName A string indicating the name of the style property (for example, "fontWeight", "borderStyle", and so on).

Returns

The value of the style property. The value can be of any data type.

Description

Method; gets the style property from the styleDeclaration or object. If the style property is an inheriting style, the parents of the object may be the source of the style value.

For a list of the styles supported by each component, see their individual entries.

Example

The following code sets the ib instance's fontWeight style property to bold if the cb instance's fontWeight style property is bold:

if (cb.getStyle("fontWeight") == "bold")
{
   ib.setStyle("fontWeight", "bold");
};


UIObject.invalidate()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.invalidate()

Parameters

None.

Returns

Nothing.

Description

Method; marks the object so it will be redrawn on the next frame interval.

Example

The following example marks the ProgressBar instance pBar for redraw:

pBar.invalidate();


UIObject.left

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.left

Description

Property (read-only); a number indicating the left edge of the object in pixels relative to its parent. To set this property, call the UIObject.move() method.


UIObject.load

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(load){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.load = function(eventObject){
  ...
}
componentInstance.addEventListener("load", listenerObject)

Description

Event; notifies listeners that the subobject for this object is being created.

The first usage example uses an on() handler and must be attached directly to a component instance.

The second usage example uses a dispatcher/listener event model. A component instance (componentInstance) dispatches an event (in this case, load) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example creates an instance of MySymbol once the form instance is loaded:

formListener.handleEvent = function(eventObj)
{
  form.createObject("MySymbol", "sym1", 0);
}
form.addEventListener("load", formListener);


UIObject.move

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(move){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.move = function(eventObject){
  ...
}
componentInstance.addEventListener("move", listenerObject)

Description

Event; notifies listeners that the object has moved.

The first usage example uses an on() handler and must be attached directly to a component instance.

The second usage example uses a dispatcher/listener event model. A component instance (componentInstance) dispatches an event (in this case, move) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example calls the move() method to keep form2 100 pixels down and to the right of form1:

formListener.handleEvent = function(){
  form2.move(form1.x + 100, form1.y + 100);
}
form1.addEventListener("move", formListener);


UIObject.move()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.move(x, y)

Parameters

x A number that indicates the position of the object's upper left corner relative to its parent.

y A number that indicates the position of the object's upper left corner relative to its parent.

Returns

Nothing.

Description

Method; moves the object to the requested position. You should only pass integral values to the UIObject.move() or the component may appear fuzzy.

Example

This example move the checkbox to the right 10 pixels:

myCheckbox.move(myCheckbox.x + 10, myCheckbox.y);


UIObject.redraw()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.redraw(always)

Parameters

always A Boolean value. If true, draws the object even if invalidate() wasn't called. If false, draws the object only if invalidate() was called.

Returns

Nothing.

Description

Method; forces validation of the object so it draws in the current frame

Example

The following example creates a check box and a button and draws them because other scripts are not expected to modify the form:

form.createClassObject(mx.controls.CheckBox, "cb", 0);
form.createClassObject(mx.controls.Button, "b", 1);
form.redraw(true)


UIObject.resize

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(resize){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.resize = function(eventObject){
  ...
}
componentInstance.addEventListener("resize", listenerObject)

Description

Event; notifies listeners that object has been resized.

The first usage example uses an on() handler and must be attached directly to a component instance.

The second usage example uses a dispatcher/listener event model. A component instance (componentInstance) dispatches an event (in this case, resize) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example calls the setSize() method to make sym1 half the width and a fourth of the height when form is moved:

formListener.handleEvent = function(eventObj){
  form.sym1.setSize(sym1.width / 2, sym1.height / 4);
}
form.addEventListener("resize", formListener);


UIObject.reveal

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

on(reveal){
  ...
}
listenerObject = new Object();
listenerObject.reveal = function(eventObject){
  ...
}
componentInstance.addEventListener("reveal", listenerObject)

Description

Event; broadcast when the object's visible property changes from false to true.

Example

The following handler displays a message in the Output panel when the object it's attached to becomes visible.

on(reveal) {
  trace("I've become visible.");
}

See also

UIObject.hide


UIObject.right

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.right

Description

Property (read-only); a number indicating the right position of the object in pixels relative to its parent's right side. To set this property, call the UIObject.move() method.

Example

The following example moves the check box so it aligns under the right edge of the list box:

myCheckbox.move(form.width - listbox.right, myCheckbox.y);


UIObject.scaleX

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.scaleX

Description

Property; a number indicating the scaling factor in the x direction of the object relative to its parent.

Example

The following example makes the check box twice as wide and sets the tmp variable to the horizontal scale factor:

checkbox.scaleX = 200;
var tmp = checkbox.scaleX;


UIObject.scaleY

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.scaleY

Description

Property; a number indicating the scaling factor in the y direction of the object relative to its parent.

Example

The following example makes the check box twice as high and sets the tmp variable to the vertical scale factor:

checkbox.scaleY = 200;
var tmp = checkbox.scaleY;


UIObject.setSize()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.setSize(width, height)

Parameters

width A number that indicates the width of the object in pixels.

height A number that indicates the height of the object in pixels.

Returns

Nothing.

Description

Method; resizes the object to the requested size. You should only pass integral values to the UIObject.setSize() or the component may appear fuzzy. This method (and all methods and properties of UIObject) is available from any component instance.

When you call this method on an instance of the ComboBox, the combo box is resized and the rowHeight property of the contained list is also changed.

Example

This example resizes the pBar component instance to 100 pixels wide and 100 pixels high:

pBar.setSize(100, 100);


UIObject.setSkin()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.setSkin(id, linkageName)

Parameters

id A number indicating the variable. This value is usually a constant defined in the class definition.

linkageName A string indicating an asset in the library.

Returns

Nothing.

Description

Method; sets a skin in the component instance. Use this method when you are developing components. You cannot use this method to set a component's skins at runtime.

Example

This example sets a skin in the checkbox instance:

checkbox.setSkin(CheckBox.skinIDCheckMark, "MyCustomCheckMark");


UIObject.setStyle()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.setStyle(propertyName, value)

Parameters

propertyName A string indicating the name of the style property (for example, "fontWeight", "borderStyle", and so on).

value The value of the property.

Returns

A UIObject that is an instance of the specified class.

Description

Method; sets the style property on the style declaration or object. If the style property is an inheriting style, the children of the object are notified of the new value.

For a list of the styles supported by each component, see their individual entries.

Example

The following code sets the fontWeight style property of the check box instance cb to bold:

cb.setStyle("fontWeight", "bold");


UIObject.top

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.top

Description

Property (read-only); a number indicating the top edge of the object in pixels relative to its parent. To set this property, call the UIObject.move() method.


UIObject.unload

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(unload){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.unload = function(eventObject){
  ...
}
componentInstance.addEventListener("unload", listenerObject)

Description

Event; notifies listeners that the subobjects of this object are being unloaded.

The first usage example uses an on() handler and must be attached directly to a component instance.

The second usage example uses a dispatcher/listener event model. A component instance (componentInstance) dispatches an event (in this case, unload) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. Each event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example deletes sym1 when the unload event is triggered:

formListener.handleEvent = function(eventObj){
  // eventObj.target is the component which generated the change event,
  form.destroyObject(sym1);
}
form.addEventListener("unload", formListener);


UIObject.visible

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.visible

Description

Property; a Boolean value indicating whether the object is visible (true) or not (false).

Example

The following example makes the myLoader loader instance visible:

myLoader.visible = true;


UIObject.width

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.width

Description

Property (read-only); a number indicating the width of the object in pixels. To change the width, call the UIObject.setSize() method.

Example

The following example makes the check box wider:

myCheckbox.setSize(myCheckbox.width + 10, myCheckbox.height);


UIObject.x

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.x

Description

Property (read-only); a number indicating the left edge of the object in pixels. To set this property, call the UIObject.move() method.

Example

The following example moves the check box to the right 10 pixels:

myCheckbox.move(myCheckbox.x + 10, myCheckbox.y);


UIObject.y

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

componentInstance.y

Description

Property (read-only); a number indicating the top edge of the object in pixels. To set this property, call the UIObject.move() method.

Example

The following example moves the check box down 10 pixels:

myCheckbox.move(myCheckbox.x, myCheckbox.y + 10);


About Web service classes

The classes found in the mx.services package consist of classes for accessing web services that use Simple Object Access Protocol (SOAP). This WebService API is not the same as the WebServiceConnector component API. The former is a set of classes that can you use only in ActionScript code, and is common with various Macromedia products. The latter is an API unique to Flash MX 2004, and provides an ActionScript interface to the visual authoring tool for the WebServiceConnector component.

See also:

  • Making web service classes available at runtime (Flash Professional only)
  • Classes in the mx.services package (Flash Professional only)
  • Log class (Flash Professional only)
  • PendingCall class (Flash Professional only)
  • SOAPCall class (Flash Professional only)


Making web service classes available at runtime (Flash Professional only)

In order to make the web service classes available at runtime, the WebServiceClasses component must be in your FLA file's library. This component contains the runtime classes that let you work with web services. For details on adding these classes to your FLA, see Working with data binding and web services at runtime (Flash Professional only).

Note: These classes are automatically made available to your Flash document when you add a WebServiceConnector component to your FLA.


Classes in the mx.services package (Flash Professional only)

The following table lists the classes in the mx.services package. These classes are closely integrated, so when first learning about this package, you may want to read the information in the order the classes are listed in the table.

Class | Description
WebService class (Flash Professional only) | Using a WSDL file that defines the web service, constructs a new WebService object for calling web service methods and handling callbacks from the web service.
PendingCall class (Flash Professional only) | Object returned from a web service method call that you implement to handle the results and faults of the call.
Log class (Flash Professional only) | Optional object used to record activity related to a WebService object.
SOAPCall class (Flash Professional only) | Advanced class that contains information about the web service operation, and provides control over certain behaviors.


Log class (Flash Professional only)

The Log class is part of the mx.services package and is intended to be used with the WebService class (see WebService class (Flash Professional only)). For an overview of the classes in the mx.data.services package, see Web service classes (Flash Professional only).

You can create a new Log object to record activity related to a WebService object. To execute code when messages are sent to a Log object, use the Log.onLog() callback function. There is no log file; the logging mechanism is whatever you have used in the onLog() callback, such as sending the log messages to a trace command.

The constructor for this object creates a Log object that can be passed as an optional argument to the WebService constructor (see WebService class (Flash Professional only)).

ActionScript Class Name mx.services.Log

Callback summary for the Log object

Callback | Description
Log.onLog() | Sends a log message to a log object.

Constructor for the Log class

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myWebSrvcLog = new Log([logLevel] [, logName]);

Parameters

logLevel Log level to indicate the types of information you want to record in the log. In the web services code, the log messages are broken down into categories or levels. The logLevel parameter of the Log object constructor relates to these categories. Three logLevels are available:

  • Log.BRIEF: The log records primary life-cycle event and error notifications.
  • Log.VERBOSE: The log records all life-cycle event and error notifications.
  • Log.DEBUG: The log records metrics and fine-grained events and errors.

The default logLevel is log.BRIEF.

logName Optional name that is included with each log message. If you are using multiple log objects, you can use the logName to determine which log recorded a given message.

Returns

Nothing.

Description

Constructor; creates a Log object. Use this constructor to create a log. After you create the Log object, you can pass this object to a web service to get messages.

Example

You can call on the new Log constructor which returns a log object to pass to your web service:

// creates a new log object
myWebSrvcLog = new Log();
myWebSrvcLog.onLog = function(txt)
{
  myTrace(txt)
}

You then pass this Log object as a parameter to the WebService constructor:

myWebSrvc = new WebService("http://www.myco.com/info.wsdl", myWebSrvcLog);

As the web services code executes and messages are sent to the log object, the onLog() function of your Log object is called. This is the only place to put code that displays the log messages if you want to see them in real time.

The following are examples of log messages:

7/30 15:22:43 [INFO] SOAP: Decoding PendingCall response
7/30 15:22:43 [DEBUG] SOAP: Decoding SOAP response envelope
7/30 15:22:43 [DEBUG] SOAP: Decoding SOAP response body
7/30 15:22:44 [INFO] SOAP: Decoded SOAP response into result [16 millis]
7/30 15:22:46 [INFO] SOAP: Received SOAP response from network [6469 millis]
7/30 15:22:46 [INFO] SOAP: Parsed SOAP response XML [15 millis]
7/30 15:22:46 [INFO] SOAP: Decoding PendingCall response
7/30 15:22:46 [DEBUG] SOAP: Decoding SOAP response envelope
7/30 15:22:46 [DEBUG] SOAP: Decoding SOAP response body
7/30 15:22:46 [INFO] SOAP: Decoded SOAP response into result [16 millis]


Log.onLog()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myWebSrvcLog.onLog = function(message)

Parameters

message The log message passed to the handler. For more information about log messages, see Log class (Flash Professional only).

Returns

None.

Description

Log callback function; Flash Player calls this function when a log message is sent to a log file. This handler is a good place to put code that records or displays the log messages, such as a trace command. The Log construction is described in Log class (Flash Professional only).

Example

The following example creates a new log object, passes it to a new WebService object and handles the logging messages.

// creates a new log object
myWebSrvcLog = new Log();
// passes the log object to the web service
myWebService = new WebService(wsdlURI, myWebSrvcLog);
// handles in-coming log messages
myWebSrvcLog.onLog = function(message)
{
  mytrace("Log Event:\r myWebSrvcLog.message="+message+);
}


PendingCall class (Flash Professional only)

The PendingCall class is part of the mx.services package and is intended to be used with the WebService class (see WebService class (Flash Professional only)). For an overview of the classes in the mx.data.services package, see Web service classes (Flash Professional only).

When you call a method on a WebService object, the WebService object returns a PendingCall object. The PendingCall object is not constructed by the developer. You use the onResult and onFault callbacks of the PendingCall object to handle the asynchronous response from the web service method. If the web service method returns a fault, Flash Player calls the PendingCall.onFault callback and passes a SOAPFault object that represents the XML SOAP fault returned by the server/web service. If the web service invocation is successful, Flash Player calls the PendingCall.onResult callback and passes a result object. The result object is the XML response from the web service decoded or deserialized into ActionScript. For more information about the WebService object, see WebService class (Flash Professional only).

The PendingCall object also offers you access to output parameters when there are more than one. Many web services return only a single result, but some web services return more than one result. The "return value" referred to in this API is simply the first (or only) result. The PendingCall.getOuptutXXX functions give you access to all of the results, not just the first. So while the "return value" is handed to you in the argument to the onResult() callback, if there are other output parameters you want to access, use getOutputValues() (returns an Array) and getOutputValue(index) (returns an individual one) to get the ActionScript decoded values.

You can also access the SOAPParameter object directly. The SOAPParameter object is an ActionScript object with two properties: value contains the ActionScript value of an output parameter, and element contains the XML value of the output parameter. The following functions return a SOAPParameter object, or an array of SOAPParameter objects, which contains the value (param.value) as well as the XML element (param.element): getOutputParameters(), getOutputParameterByName(name), and getOutputParameter(index).

ActionScript Class Name mx.services.PendingCall

Function summary for the PendingCall object

Function | Description
PendingCall.getOutputParameter() | Gets a SOAPParameter object based on the index passed in.
PendingCall.getOutputParameterByName() | Gets a SOAPParameter object based on the localName passed in.
PendingCall.getOutputParameters() | Gets an array of SOAPParameter objects.
PendingCall.getOutputValue() | Gets the output value based on the index passed in.
PendingCall.getOutputValues() | Gets an array of all the output values.

Property summary for the PendingCall object

Property | Description
PendingCall.myCall | The SOAPCall operation descriptor for the PendingCall operation.
PendingCall.request | The SOAP request in raw XML format.
PendingCall.response | The SOAP response in raw XML format.

Callback summary for the PendingCall object

Callback | Description
PendingCall.onFault() | Called by a web service when the method fails.
PendingCall.onResult() | Called when a method has succeeded and returned a result.

Constructor for the PendingCall class

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Description

The PendingCall object is not constructed by the developer. Instead, when you call a function on a WebService object, the WebService object returns a PendingCall object.


PendingCall.getOutputParameter()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myPendingCall.getOutputParameter(var index)

Parameters

index The index of the parameter.

Returns

SOAPParameter object with the following elements:

Element | Description
value | The ActionScript value of the parameter.
element | The raw XML of the parameter in the SOAP envelope.

Description

Function; gets an additional output parameter of the SOAPParameter object, which contains the value and the XML element. SOAP RPC calls may return multiple output parameters. The first (or only) return value is always handed to you in the results argument of the onResult() callback, but to get access to the others you need to use functions such as this one or getOutputValue(). The getOutputParameter() function returns the nth output parameter as a SOAPParameter object.

See also PendingCall.getOutputValue(), PendingCall.getOutputValues(), PendingCall.getOutputParameterByName() and PendingCall.getOutputParameters().

Example

Given the SOAP descriptor file below, getOutputParameter(1) would return a SOAPParameter object with value="Hi there!" and element=the <outParam2> XMLNode.

...
<SOAP:Body>
  <rpcResponse>
    <outParam1 xsi:type="xsd:int">54</outParam1>
    <outParam2 xsi:type="xsd:string">Hi there!</outParam2>
    <outParam3 xsi:type="xsd:boolean">true</outParam3>
  </rpcResponse>
</SOAP:Body>
...


PendingCall.getOutputParameterByName()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myPendingCall.getOutputParameterByName(var localName)

Parameters

localName The local name of the parameter. In other words, the name of an XML element, stripped of any namespace information. For example, the local name of both of the following elements is bob:

<bob abc="123">
<xsd:bob def="ghi">

Returns

SOAPParameter object with the following elements:

Element | Description
value | The ActionScript value of the parameter.
element | The raw XML of the parameter in the SOAP envelope.

Description

Function; gets any output parameter as a SOAPParameter object, which contains the value and the XML element. SOAP RPC calls may return multiple output parameters. The first (or only) return value is always handed to you in the results argument of the onResult() callback, but to get access to the others you need to use APIs such as this one. The getOutputParameterByName() call returns the output parameter with the name localName.

See also PendingCall.getOutputValue(), PendingCall.getOutputValues(), PendingCall.getOutputParameter() and PendingCall.getOutputParameters().

Example

Given the SOAP descriptor file below, getOutputParameterByName("outParam2") would return a SOAPParameter object with value="Hi there!" and element=the <outParam2> XMLNode.

...
<SOAP:Body>
  <rpcResponse>
    <outParam1 xsi:type="xsd:int">54</outParam1>
    <outParam2 xsi:type="xsd:string">Hi there!</outParam2>
    <outParam3 xsi:type="xsd:boolean">true</outParam3>
  </rpcResponse>
</SOAP:Body>
...


PendingCall.getOutputParameters()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myPendingCall.getOutputParameterByName()

Parameters

None.

Returns

Array of SOAPParameter objects with the following elements:

Element | Description
value | The ActionScript value of the parameter.
element | The raw XML of the parameter in the SOAP envelope.

Description

Function; gets additional output parameters of the SOAPParameter object, which contains the values and the XML elements. SOAP RPC calls may return multiple output parameters. The first (or only) return value is always handed to you in the results argument of the onResult() callback, but to get access to the others you need to use APIs such as this one or getOutputValues().

See also PendingCall.getOutputValue(), PendingCall.getOutputValues(), PendingCall.getOutputParameterByName() and PendingCall.getOutputParameter().


PendingCall.getOutputValue()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myPendingCall.getOutputValue(var index)

Parameters

index The index of an output parameter. The first parameter is index 0.

Returns

The nth output parameter.

Description

Function; gets the decoded ActionScript value of an individual output parameter. SOAP RPC calls may return multiple output parameters. The first (or only) return value is always handed to you in the results argument of the onResult() callback, but to get access to the others you need to use APIs such as this one or getOutputParameter(). The getOutputValue() call returns the nth output parameter.

See also PendingCall.getOutputParameter(), PendingCall.getOutputValues(), PendingCall.getOutputParameterByName() and PendingCall.getOutputParameters().

Example

Given the SOAP descriptor file below, getOutputValue(2) would return true.

...
<SOAP:Body>
  <rpcResponse>
    <outParam1 xsi:type="xsd:int">54</outParam1>
    <outParam2 xsi:type="xsd:string">Hi there!</outParam2>
    <outParam3 xsi:type="xsd:boolean">true</outParam3>
  </rpcResponse>
</SOAP:Body>
...


PendingCall.getOutputValues()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myPendingCall.getOutputValues()

Parameters

None.

Returns

Array of all output parameters' decoded values.

Description

Function; gets the decoded ActionScript value of all output parameters. SOAP RPC calls can return multiple output parameters. The first (or only) return value is always handed to you in the results argument of the onResult() callback, but to get access to the others you need to use APIs such as this one or getOutputParameters().

See also PendingCall.getOutputValue(), PendingCall.getOutputParameter(), PendingCall.getOutputParameterByName() and PendingCall.getOutputParameters().


PendingCall.myCall

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

PendingCall.myCall

Description

Property; the SOAPCall object corresponding to the PendingCall's operation. The SOAPCall object contains information about the web service operation, and provides control over certain behaviors. For more information, see SOAPCall class (Flash Professional only).

Example

The following onResult callback traces the name of the SOAPCall operation.

callback.onResult = function(result)
{
  // Check my operation name
  trace("My operation name is " + this.myCall.name);
}


PendingCall.onFault()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myPendingCallObj.onFault = function(fault)
{
  // handles any faults, for example, by telling the
  // user that the server isn't available or to contact technical
  // support

}

Parameters

fault Decoded ActionScript object version of the error with properties. If the error information came from a server in the form of XML, then the SOAPFault object will be the decoded ActionScript version of that XML.

The type of error object returned to PendingCall.onfault() is a SOAPFault object. It is not constructed directly by developers, but returned as the result of a failure. This object is an ActionScript mapping of the SOAP Fault XML type.

SOAPFault property | Description
faultcode | String; a short string describing the error.
faultstring | String; the human-readable description of the error.
detail | String; the application-specific information associated with the error, such as a stack trace or other information returned by the web service engine.
element | XML; the XML object representing the XML version of the fault.
faultactor | String; the source of the fault (optional if an intermediary is not involved).

Returns

Nothing.

Description

PendingCall object callback function; you provide this handler that Flash Player calls when a web service method has failed and returned an error. The fault parameter is an ActionScript SOAPFault object.

Example

The following example handles errors returned from the web service method.

// handles any error returned from the use of a web service method
myPendingCallObj = myWebService.methodName(params)
myPendingCallObj.onFault = function(fault)
{
  // catches the SOAP fault
  DebugOutputField.text = fault.faultstring;

  // add code to handle any faults, for example, by telling the
  // user that the server isn't available or to contact technical
  // support

}


PendingCall.onResult()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myPendingCallObj.onResult = function(result)
{
  // catches the result and handles it for this application

}

Parameters

result Decoded ActionScript object version of the XML result returned by a web service method called with myPendingCallObj = myWebService.methodName(params).

Returns

None.

Description

PendingCall callback function; you provide this handler that Flash Player calls when a web service method succeeds and returns a result. The result is a decoded ActionScript object version of the XML returned by the operation. To get the raw XML returned instead of the decoded result, access the PendingCall.response property (see PendingCall.response).

Example

The following example handles results returned from the web service method.

// handles results returned from the use of a web service method
myPendingCallObj = myWebService.methodName(params)
myPendingCallObj.onResult = function(result)
{
  // catch the result and handle it for this application
  ResultOutputField.text = result;
}


PendingCall.request

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

rawXML = myPendingCallback.request;

Description

PendingCall property; contains the raw XML form of the current request sent with myPendingCallback = myWebService.methodName(). Normally, you would not have any use for PendingCall.request, but you can use it if you are interested in the SOAP that gets sent over the wire. Use this property to access the raw XML of the request. Use myPendingCallback.onResult() to get the ActionScript version of the results of the request.


PendingCall.response

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

rawXML = myPendingCallback.response;

Description

PendingCall property; contains the raw XML form of the response to the most recent web service method call sent with myPendingCallback = myWebService.methodName(). Normally, you would not have any use for PendingCall.response, but you can use it if you are interested in the SOAP that gets sent over the wire. Use myPendingCallback.onResult() to get the corresponding ActionScript version of the results of the request.


SOAPCall class (Flash Professional only)

The SOAPCall class is part of the mx.services package and is intended as an advanced feature to be used with the WebService class (see WebService class (Flash Professional only)). For an overview of the classes in the mx.data.services package, see Web service classes (Flash Professional only).

When you create a new WebService object, it contains the methods corresponding to operations in the WSDL URL you pass in. Behind the scenes, a SOAPCall object is created for each operation in the WSDL as well. The SOAPCall is the descriptor of the operation, and as such contains all the information about that particular operation (how the XML should look on the wire, the operation style, and so on). It also provides control over certain behaviors. You can get the SOAPCall for a given operation by using the getCall(operationName) function. There is a single SOAPCall for each operation, shared by all active calls to that operation. Once you have the SOAPCall, you can customize the descriptor, by doing the following:

  • Turn on/off decoding of the XML response.
  • Turn on/off the delay of converting SOAP arrays into ActionScript objects.
  • Change the concurrency configuration for a given operation.
  • Add a header to the SOAPCall object.

ActionScript Class Name mx.services.SOAPCall

Function summary for the SOAPCall object

Function | Description
SOAPCall.addHeader() | Adds a header to the SOAPCall object.

Property summary for the SOAPCall object

Property | Description
SOAPCall.concurrency | Changes the concurrency configuration for a given operation.
SOAPCall.doDecoding | Turns on/off decoding of the XML response.
SOAPCall.doLazyDecoding | Turns on/off the delay of turning SOAP arrays into ActionScript objects.

Constructor for the SOAPCall class

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Description

The SOAPCall object is not constructed by the developer. Instead, when you call a method on a WebService object, the WebService object returns a PendingCall object. To access the associated SOAPCall object, use myPendingCall.myCall.


SOAPCall.addHeader()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

SOAPCall.addHeader(var header)

Parameters

header Header to be added.

Returns

None.

Description

Function; adds a header to the SOAPCall object.

Example

The following example creates a new SOAP header and attaches it to the SOAPCall. The following code:

import mx.services.QName;

var qname = new QName("bar", "http://foo");
var value = "hi there!";
var header = new SOAPHeader(qname, value);
soapCall.addHeader(header);

creates the following SOAP header:

...
<SOAP:Header>
  <ns1:bar
    xmlns:ns1="http://foo"
    xsi:type="xsd:string">hi there!</ns1:bar>
</SOAP:Header>
...


SOAPCall.concurrency

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

SOAPCall.concurrency

Description

Property; number of concurrent requests. Possible values are listed in the table below:

Value | Description
SOAPCall.MULTIPLE_CONCURRENCY | Allow multiple active calls.
SOAPCall.SINGLE_CONCURRENCY | Allow only one call at a time by faulting after one is active.
SOAPCall.LAST_CONCURRENCY | Allow only one call by cancelling previous ones.


SOAPCall.doDecoding

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

SOAPCall.doDecoding

Description

Property; turns on/off decoding of the XML response—by default the XML response is converted (decoded) into ActionScript objects. If you just want the XML, you can set SOAPCall.doDecoding = false.


SOAPCall.doLazyDecoding

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

SOAPCall.doLazyDecoding

Description

Property; turns on/off "lazy decoding" of arrays. By default we use a "lazy" decoding algorithm to delay turning SOAP arrays into ActionScript objects until the last moment—this makes operations return a lot faster when large data sets are returned. This means any arrays you get back from the remote end are ArrayProxy objects. Then when you access a particular index (foo[5]) that element is automatically decoded if necessary. This behavior can be turned off (which will cause all arrays to be fully decoded) by setting SOAPCall.doLazyDecoding = false.


WebService class (Flash Professional only)

The WebService class is part of the mx.services package and is intended to be used with the following classes:

  • Log class (Flash Professional only)
  • PendingCall class (Flash Professional only)
  • SOAPCall class (Flash Professional only)

Note: This WebService API is not the same as the WebServiceConnector component API. The former is a set of classes that can you use only in ActionScript code, and is common with various Macromedia products. The latter is an API unique to Flash MX 2004, and provides an ActionScript interface to the visual authoring tool for the WebServiceConnector component.

For an overview of the classes in the mx.services package, see Web service classes (Flash Professional only).

The WebServices object acts as a local reference to a remote web service. When you create a new WebService object, the WSDL file that defines the web service gets downloaded, parsed, and placed in the object. You can then call the methods of the web service directly on the WebService object, and handle any callbacks from the web service. When the WSDL has been successfully processed and the WebService object is ready, the onLoad() callback is invoked. If there is a problem loading the WSDL, the onFault() callback is invoked.

When you call a method on a WebService object, the return value is a callback object. The object type of the callback returned from all web service method invocations is PendingCall. These objects are normally not constructed by developers, but instead are constructed automatically as a result of the webServiceObject.webServiceMethodName() command. These objects are not the result of the WebService call, which comes later. Instead, the PendingCall object represents the call in progress. When the WebService operation completes (usually several seconds after a method call is made), the various PendingCall data fields are filled in, and the onResult or onFault callback you provide is called. For more information about the PendingCall object, see PendingCall class (Flash Professional only).

The Player queues up any calls you make before the WSDL is parsed, and attempts to execute them after parsing the WSDL. This is because the WSDL contains information that is necessary to correctly encode and send a SOAP request. Function calls that you make after the WSDL has been parsed do not need to be queued; they happen immediately. If a queued call doesn't match the name of any of the operations defined in the WSDL, Flash Player returns a fault to the callback object you were given when you originally made the call.

ActionScript Class Name mx.services.WebService

See also:

  • Using the WebServices API
  • Supported types
  • WebService security


Using the WebServices API

The WebServices API, included under the mx.services package, consists of the WebService class, the Log class, the PendingCall class, and the PendingCall class.

Making the WebServices classes available at runtime (Flash Professional only)

In order to make the web service classes available at runtime, you must have the WebServiceClasses component in your FLA file's library. If you're only using ActionScript to access a web service at runtime, then you have to add this component manually to your document's library. For information on how to add this component to your document, see Working with data binding and web services at runtime (Flash Professional only).


Supported types

The WebService feature supports a subset of XML Schema types as defined in the tables below.

Complex types and the SOAP-Encoded Array type are also supported, and these may be composed of other complex types, arrays, or built-in XML Schema types:

  • Numeric Simple types
  • Date and Time Simple types
  • Name and String Simple types
  • Boolean type
  • Object types
  • Supported XML schema object elements

Numeric Simple types

XML Schema type | ActionScript Binding
decimal | Number
integer | Number
negativeInteger | Number
nonNegativeInteger | Number
positiveInteger | Number
long | Number
int | Number
short | Number
byte | Number
unsignedLong | Number
unsignedShort | Number
unsignedInt | Number
unsignedByte | Number
float | Number
double | Number

Date and Time Simple types

XML Schema type | ActionScript Binding
date | Date object
datetime | Date object
duration | Date object
gDay | Date object
gMonth | Date object
gMonthDay | Date object
gYear | Date object
gYearMonth | Date object
time | Date object

Name and String Simple types

XML Schema type | ActionScript Binding
string | ActionScript String
normalizedString | ActionScript String
QName | mx.services.Qname object

Boolean type

XML Schema type | ActionScript Binding
Boolean | Boolean

Object types

XML Schema type | ActionScript Binding
Any | XML object
Complex Type | ActionScript object composed of properties of any supported type
Array | ActionScript array composed of any supported object or type

Supported XML schema object elements

schema
     complexType
          complexContent
               restriction
          sequence | simpleContent
               restriction
     element
          complexType | simpleType


WebService security

The WebService API conforms to the Flash Player security model.

See also:

  • User Authentication and Authorization
  • Message Integrity
  • Function summary for the WebService object
  • Callback summary for the WebService object

User Authentication and Authorization

The authentication and authorization rules are the same for the WebService API as they are for any XML network operation from Flash. SOAP itself does not specify any means of authentication and authorization. For example, when the underlying HTTP transport returns an HTTP BASIC response in the HTTP Headers, the browser responds by presenting a dialog for the user and subsequently attaching the user's input to the HTTP Headers in subsequent messages. This mechanism exists at a level lower than SOAP and is part of the Flash HTTP authentication design.

Message Integrity

Message-level security involves the encryption of the SOAP messages themselves, at a conceptual layer above the network packets on which the SOAP messages are delivered.

Transport Security The underlying network transport for Flash Player SOAP web services is always HTTP POST. Therefore, any means of security that can be applied at the Flash HTTP transport layer—such as SSL—is supported through web services invocations from Flash. SSL/HTTPS provides the most common form of transport security for SOAP messaging, and use of HTTP BASIC authentication, coupled with SSL at the transport layer, is the most common form of security for websites today.

Function summary for the WebService object

Function | Description
WebService.myMethodName() | Invokes a specific web service operation defined by the WSDL.
WebService.getCall() | Gets the SOAPCall for a given operation

Callback summary for the WebService object

Callback | Description
WebService.onLoad() | Called when the web service has successfully loaded and parsed its WSDL file.
WebService.onFault() | Called when an error occurred during WSDL parsing.

Constructor for the WebService class

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myWebServiceObject = new WebService(wsdlURI [, logObject]);

Parameters

The constructor parameters are as follows:

wsdlURI URL of the web service WSDL file.

logObject Optional parameter specifying the name of the Log object for this web service (see Log class (Flash Professional only)).

Returns

None.

Description

To create a WebService object, you call new WebService() and provide a WSDL URL. Flash Player returns a WebService object. The WebService object constructor can optionally accept a Log object and a proxy URL:

myWebServiceObject = new WebService(wsdlURI [, logObject]);

If you want to, you can utilize two callbacks for the WebService object. Flash Player calls the webServiceObject.onLoad(WSDLDocument) function when it finishes parsing the WSDL file and the object is complete. This is a good place to put code you want to execute only after the WSDL file has been completely parsed. For example, you might choose to put your first web service method call in this function.

Flash Player calls the webServiceObject.onFault(fault) when an error occurs in finding or parsing the WSDL file. This is a good place to put debugging code and code that tells the user that the server is unavailable, that they should try again later, or similar information. For more information, see the individual entries for these functions.

Invoking a web service operation: You invoke a web service operation as a method directly available on the web service. For example, if your web service has the method getCompanyInfo(tickerSymbol), then invoke the method in the following manner:

myPendingCallObject = myWebServiceObject.getCompanyInfo(tickerSymbol);

In the previous example, the callback object is named myPendingCallObject. All method invocations are asynchronous, and return a callback object of type PendingCal. Asynchronous means that the results of the web service call are not available immediately.

When you make the call

x = stockService.getQuote("macr");

the object x is not the results of getQuote (it's a PendingCall object). The actual results are only available later on (usually several seconds later), when the web service operation completes. Your ActionScript code is notified by a call to the onResult callback function.

Handling the PendingCall object: This callback object is a PendingCall object that you use for handling the results and errors from the web service method that was called (see PendingCall class (Flash Professional only)). For example:

MyPendingCallObject = myWebServiceObject.myMethodName(param1, ..., paramN);
MyPendingCallObject.onResult = function(result)
{
  OutputField.text = result
}
MyPendingCallObject.onFault = function(fault)
{
  DebugField.text = fault.faultCode + "," + fault.faultstring;

  // add code to handle any faults, for example, by telling the
  // user that the server isn't available or to contact technical
  // support

}


WebService.getCall()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

getCall(var operationName)

Parameters

operationName The web service operation of the corresponding SOAPCall that you want to retrieve.

Returns

SOAPCall object.

Description

When you create a new WebService object, it contains the methods corresponding to operations in the WSDL URL you pass in. Behind the scenes, a SOAPCall object is created for each operation in the WSDL as well. The SOAPCall is the descriptor of the operation, and as such contains all the information about that particular operation (how the XML should look on the wire, the operation style, and so on). It also provides control over certain behaviors. You can get the SOAPCall for a given operation by using the getCall(operationName) method. There is a single SOAPCall for each operation, shared by all active calls to that operation. Once you have the SOAPCall, you can change the operator descriptor by using the SOAPCall API. For more information, see SOAPCall class (Flash Professional only).

Example

For an example on using this call, see SOAPCall class (Flash Professional only).


WebService.onFault()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

MyWebServiceObject.onFault

Parameters

fault Decoded ActionScript object version of the error with properties. If the error information came from a server in the form of XML, then the SOAPFault object will be the decoded ActionScript version of that XML.

The type of error object returned to webservice.onFault() methods is a SOAPFault object. It is not constructed directly by developers, but returned as the result of a failure. This object is an ActionScript mapping of the SOAP Fault XML type.

SOAPFault property | Description
faultcode | String; the short standard QName describing the error.
faultstring | String; the human-readable description of the error.
detail | String; the application-specific information associated with the error, such as a stack trace or other information returned by the web service engine.
element | XML; the XML object representing the XML version of the fault.
faultactor | String; the source of the fault, optional if an intermediary is not involved.

Returns

Nothing.

Description

WebService callback function; Flash Player calls this function when the new webService(WSDLUrl) method has failed and returned an error. This can happen when the WSDL file cannot be parsed or the file cannot be found. The fault parameter is a ActionScript SOAPFault object.

Example

The following example handles any error returned from the creation of the WebService object.

MyWebServiceObject.onFault = function(fault)
{
  // captures the fault
  DebugOutputField.text = fault.faultstring;

  // add code to handle any faults, for example, by telling the
  // user that the server isn't available or to contact technical
  // support

}


WebService.onLoad()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

myService.onLoad

Parameters

wsdlDocument WSDL XML document.

Returns

None.

Description

Webservice callback function; Flash Player calls this callback when the WebService object has successfully loaded and parsed its WSDL file. Operations can be invoked in an application before this event occurs, but when this happens they will be queued internally and not actually transmitted until the WSDL has loaded.

Example

The following example specifies the WSDL URL, creates a new web service object, and receives the WSDL document after loading.

// specify the WSDL URL
var wsdlURI = "http://www.flash-db.com/services/ws/companyInfo.wsdl";

// creates a new web service object
stockService = new WebService(wsdlURI);

// receives the WSDL document after loading
stockService.onLoad = function(wsdlDocument);
{
  // code to execute when the WSDL loading is complete and the
  // object has been created
}


WebService.myMethodName()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

callbackObj = myWebServiceObject.myMethodName(param1, ... paramN);

Parameters

Parameters required depend on the web service method being called.

Returns

callbackObj PendingCall object to which you can attach function for handling results and errors on the invocation. For more information, see PendingCall class (Flash Professional only).

The callback invoked when the response comes back from the WebService method is PendingCall.onResult(), or onFault(). By uniquely identifying your callback objects, you can manage multiple onResult callbacks, as in the following example:

myWebService = new WebService("http://www.myCompany.com/myService.wsdl");
callback1 = myWebService.getWeather("02451");
callback1.onResult = function(result)
{
  //do something
}
callback2 = myWebService.getDetailedWeather("02451");
callback2.onResult = function(result)
{
  //do something else
}

Description

To invoke a web service operation, invoke it as a method directly available on the web service. For example, if your web service has the method getCompanyInfo(tickerSymbol), then call:

myCallbackObject.myservice.getCompanyInfo(tickerSymbol);

All invocations are asynchronous, and return a callback object, of the object type PendingCall.


About the WebServiceConnector component (Flash Professional only)

The WebServiceConnector component enables you to access remote methods exposed by a server using the industry-standard SOAP (Simple Object Access Protocol) protocol. A web service may accept parameters and return a result. Using the Flash MX Professional 2004 authoring tool and the WebServiceConnector component you can introspect, access and bind data between a remote web service and your Flash application.

The WebServiceConnector component and the XMLConnector component implement the RPC (Remote Procedure Call) Component API, a set of methods, properties, and events that define an easy way to send parameters to, and receive results from, an external data source.

A single instance of WebServiceConnector component can be used to make multiple calls to the same operation. You need to use a different instance of WebServiceConnector for each different operation you want to call.

Note: The WebServiceConnector appears on the Stage during application authoring but is not visible in the runtime application.

See Working with schemas in the Schema tab (Flash Professional only).See also:

  • WebServiceConnector class (Flash Professional only)

Using the WebServiceConnector (Flash Professional only)

You can use the WebServiceConnector to connect to a web service and make the properties of the web service available for binding to properties of UI components in your application. To connect to a web service, you must first enter the URL for the WSDL file that represents the web service.

You can enter the URL for a web service in the Component Inspector panel or the Web Services panel. See Connecting to web services (Flash Professional only) and Connecting to web services (Flash Professional only).

For more information on working with the WebServiceConnector component, see Data binding (Flash Professional only).

WebServiceConnector parameters

The following are authoring parameters that you can set for each WebServiceConnector component instance, in the Component Inspector panel Parameters tab:

multipleSimultaneousAllowed (Boolean type) indicates whether multiple calls can take place at the same time; the default value is false. If false, then the trigger() function will not perform a call if a call is already in progress. A status event will be emitted, with the code CallAlreadyInProgress. If true, then the call will take place.

operation (String type) is the name of an operation that appears within the SOAP port in a WSDL file.

suppressInvalidCalls (Boolean type) indicates whether to suppress a call if parameters are invalid; the default value is false. If true, then the trigger() function will not perform a call if the databound parameters fail the validation. A status event will be emitted, with the code InvalidParams. If false, then the call will take place, using the invalid data as required.

WSDLURL (String type) is the URL of the WSDL file that defines the web service operation. When you set this URL during authoring, the WSDL file is immediately fetched and parsed. The resulting parameters and results information can be seen in the Schema tab of the Component Inspector panel. The service description is also added to the Web Service panel. For example, see www.xmethods.net/sd/2001/TemperatureService.wsdl.

Common workflow for the WebServiceConnector component

The typical workflow for the WebServiceConnector component is as follows.

To use a WebServiceConnector component:

  1. Use the Web Services panel to enter the URL for a web service WSDL file.
  2. Add a call to a method of the web service by selecting the method, right-clicking (Windows) or Control-clicking (Macintosh), and selecting Add Method Call from the context menu. This creates a WebServiceConnector component instance in your application. The schema for the component can then be found on the Schema tab of the Component Inspector panel. You are free to edit this schema as needed—for example, to provide additional formatting or validation settings.

    Note: The schema for the params and results component properties is updated each time the author changes the WSDLURL or operation parameter. This overwrites any settings that you have edited.

  3. Use the Binding tab in the Component Inspector panel to bind the web service parameters and results that are now defined in your schema to UI components within your application.
  4. Add a trigger to initiate the data binding operation using one of the following methods:
    • Attach the Trigger Data Source behavior to a button.
    • Add your own ActionScript to call the trigger() function on the WebServiceConnector component.
    • Create a binding between a web service parameter and a UI control and set its Kind property to AutoTrigger (see Schema Kinds for more information).

For a step-by-step example that connects and displays a web service using the WebServiceConnector component, see Web Service Tutorial: Update the Stock Quote Web Service (Flash Professional Only) or Web Service Tutorial: Update the Stock Quote Web Service (Flash Professional Only).


WebServiceConnector class (Flash Professional only)

Inheritance RPC > WebServiceConnector

ActionScript Class Name mx.data.components.WebServiceConnector

Property summary for the WebServiceConnector class

Property | Description
WebServiceConnector.multipleSimultaneousAllowed | Indicates whether multiple calls can take place at the same time.
WebServiceConnector.multipleSimultaneousAllowed | Indicates the name of an operation that appears within the SOAP port in a WSDL file.
WebServiceConnector.params | Specifies data that will be sent to the server when the next trigger() operation is executed.
WebServiceConnector.results | Identifies data that was received from the server as a result of the trigger() operation.
WebServiceConnector.suppressInvalidCalls | Indicates whether to suppress a call if parameters are invalid.
WebServiceConnector.timeout | Specifies a time period (in seconds) within which the web service connection will fail if results do not come back.
WebServiceConnector.WSDLURL | Specifies the URL of the WSDL file that defines the web service operation.

Method summary for the WebServiceConnector class

Method | Description
WebServiceConnector.trigger() | Initiates a remote procedure call.

Event summary for the WebServiceConnector class

Event | Description
WebServiceConnector.result | Broadcast when a call to a web service completes successfully.
WebServiceConnector.send | Broadcast when the trigger() function is in process, after the parameter data has been gathered but before the data is validated and the call to the web service is initiated.
WebServiceConnector.status | Broadcast when a call to a web service is initiated, to inform the user of the status of the operation.


WebServiceConnector.multipleSimultaneousAllowed

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.multipleSimultaneousAllowed;

Description

Property; indicates whether multiple calls can take place at the same time. If false, then the trigger() function will perform a call if another call is already in progress. A status event will be emitted, with the code CallAlreadyInProgress. If true, then the call will take place.

When multiple calls are simultaneously in progress, there is no guarantee that they will complete in the same order as they were triggered. Also, Flash Player may place limits on the number of simultaneous network operations. This limit varies by version and platform.

Example

The following example enables multiple simultaneous calls to myXmlUrl take place:

myXmlUrl.multipleSimultaneousAllowed = true;


WebServiceConnector.operation

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.operation;

Description

Property; the name of an operation that appears within the SOAP port in a WSDL file.


WebServiceConnector.params

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.params;

Description

Property; specifies data that will be sent to the server when the next trigger() operation is executed. The data type is determined by the WSDL description of the web service.

When you call web service methods, the data type of the params property must be an ActionScript object or array as follows:

If the web service is in document format, then the data type of params is an XML document of some kind.

If you use the Property Inspector or Component Inspector panel to set the WSDLURL and operation at during authoring, you can provide params as an array of parameters in the same order as required by the web service method, such as [1, "hello", 2432].

Example

The following example sets the params property for a web service component named wsc:

wsc.params = [param_txt.text];


WebServiceConnector.result

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.addEventListener("result", myListenerObject);

Description

Event; broadcasts when a Remote Procedure Call operation successfully completes.

The parameter to the event handler is an object with the following fields:

  • type: the string "result"
  • target: a reference to the object that emitted the event (for example, a WebServiceConnector component)

You can retrieve the actual result value using the results property.

Example

The following example defines a function res for the result event and assigns the function to the addEventListener event handler:

var res = function (ev) {
trace(ev.target.results);
};
wsc.addEventListener("result", res);


WebServiceConnector.results

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.results;

Description

Property; identifies data that was received from the server as a result of a trigger() operation. Each RPC component defines how this data is fetched, and what the valid types are. This data appears when the RPC operation has successfully completed, as signaled by the result event. It is available until the component is unloaded, or until the next RPC operation.

It is possible for the returned data to be very large. You can manage this in two ways:

  • Select an appropriate movie clip, Timeline, or screen as the parent for the RPC component. The component's storage will become available for garbage collection when the parent goes away.
  • In ActionScript, you can assign null to this property at any time.


WebServiceConnector.send

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.addEventListener("send", myListenerObject);

Description

Event; broadcasts during the processing of a trigger() operation, after the parameter data has been gathered but before the data is validated and the Remote Procedure Call is initiated. This is a good place to put code that will modify the parameter data before the call.

The parameter to the event handler is an object with the following fields:

  • type: the string "send"
  • target: a reference to the object that emitted the event (for example, a WebServiceConnector component)

You can retrieve or modify the actual parameter values using the params property.

Example

The following example defines a function sendFunction for the send event and assigns the function to the addEventListener event handler:

var sendFunction = function (sendEnv) {
sendEnv.target.params = [newParam_txt.text];
};
wsc.addEventListener("send", sendFunction);


WebServiceConnector.status

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.addEventListener("status", myListenerObject);

Description

Event; broadcasts when a Remote Procedure Call is initiated, to inform the user of the status of the operation.

The parameter to the event handler is an object with the following fields:

  • type: the string "status"
  • target: a reference to the object that emitted the event (for example, a WebServiceConnector component)
  • code: a string giving the name of the specific condition that occurred.
  • data: an object whose contents depend on the code.

The following are the codes and associated data available for the status event:

Code | Data | Description
StatusChange | {callsInProgress:nnn} | This event is emitted whenever a web service call starts or finishes. The item "nnn" gives the number of calls currently in progress.
CallAlreadyInProgress | no data | This event is emitted if (a) the trigger() function is called, and (b) multipleSimultaneousAllowed is false, and (c) a call is already in progress. After this event occurs, the attempted call is considered complete, and there will be no "result" or "send" event.
InvalidParams | no data | This event is emitted if the trigger() function found that the "params" property did not contain valid data. If the "suppressInvalidCalls" property is true, then the attempted call is considered complete, and there will be no "result" or "send" event.

Here are the possible web service faults:

faultcode | faultstring | detail
Timeout | Timeout while calling method xxx |
MustUnderstand | No callback for header xxx |
Server.Connection | Unable to connect to endpoint: xxx |
VersionMismatch | Request implements version: xxx Response implements version yyy |
Client.Disconnected | Could not load WSDL | Unable to load WSDL, if currently online, please verify the URI and/or format of the WSDL xxx
Server | Faulty WSDL format | Definitions must be the first element in a WSDL document
Server.NoServicesInWSDL | Could not load WSDL | No elements found in WSDL at xxx
WSDL.UnrecognizedNamespace | The WSDL parser had no registered document for the namespace xxxx |
WSDL.UnrecognizedBindingName | The WSDL parser couldn't find a binding named xxx in namespace yyy |
WSDL.UnrecognizedPortTypeName | The WSDL parser couldn't find a portType named xxx in namespace yyy |
WSDL.UnrecognizedMessageName | The WSDL parser couldn't find a message named xxx in namespace yyy |
WSDL.BadElement | Element xxx not resolvable |
WSDL.BadType | Type xxx not resolvable |
Client.NoSuchMethod | Couldn't find method 'xxx' in service |
yyy | yyy - errors reported from server, this depends on which server you talk to |
No.WSDLURL.Defined | the WebServiceConnector component had no WSDL URL defined |
Unknown.Call.Failure | WebService invocation failed for unknown reasons |
Client.Disconnected | Could not load imported schema | Unable to load schema; if currently online, please verify the URI and/or format of the schema at (XXXX))

Example

The following example defines a function statusFunction for the status event and assigns the function to the addEventListener event handler:

var statusFunction = function (stat) {
trace(stat.code);
trace(stat.data.faultcode);
trace(stat.data.faultstring);
};
wsc.addEventListener("status", statusFunction);


WebServiceConnector.suppressInvalidCalls

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.suppressInvalidCalls;

Description

Property; indicates whether to suppress a call if parameters are invalid. If true, then the trigger() function will not perform a call if the bound parameters fail the validation. A "status" event will be emitted, with the code InvalidParams. If false, then the call will take place, using the invalid data as required.


WebServiceConnector.timeout

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.timeout;

Description

Property; a time period in seconds within which the web service connection will fail if results do not come back. A status event (inherited from the RPC component) is emitted, with the code WebServiceFault, faultcode Timeout.


WebServiceConnector.trigger()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.trigger();

Description

Method; initiates a call to a web service. Each web service defines exactly what this involves. If the operation is successful, the results of the operation will appear in the results property for the web service.

The trigger() method performs the following steps:

  1. If any data is bound to the params property, the method executes all the bindings to ensure that up-to-date data is available. This also causes data validation to occur.
  2. If the data is not valid and suppressInvalidCalls is set to true, the operation is discontinued.
  3. If the operation continues, the send event is emitted.
  4. The actual remote call is initiated using the connection method indicated (for example, HTTP).


WebServiceConnector.WSDLURL

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.WSDLURL;

Description

Property; the URL of the WSDL file that defines the web service operation. When you set this URL during authoring, the WSDL file is immediately fetched and parsed. The resulting parameters and results appear in the Schema tab of the Component Inspector panel. The service description also appears in the Web Service panel.


About the Window component

A Window component displays the contents of a movie clip inside a window with a title bar, a border, and an optional close button.

A Window component can be modal or non-modal. A modal window prevents mouse and keyboard input from going to other components outside the window. The Window component also supports dragging; a user can click the title bar and drag the window and its contents to another location. Dragging the borders doesn't resize the window.

A live preview of each Window instance reflects changes made to all parameters except contentPath in the Property inspector or Component Inspector panel while authoring.

When you add the Window component to an application, you can use the Accessibility panel to make it accessible to screen readers. First, you must add the following line of code to enable accessibility:

mx.accessibility.WindowAccImpl.enableAccessibility();

You only enable accessibility for a component once no matter how many instances you have of the component. For more information, see Creating Accessible Content.See also:

  • Using the Window component
  • Customizing the Window component
  • Window class


Using the Window component

You can use a window in an application whenever you need to present a user with information or a choice that takes precedence over anything else in the application. For example, you might need a user to fill out a login window, or a window that changes and confirms a new password.

There are several ways to add a window to an application. You can drag a window from the Components panel to the Stage. You can also call createClassObject() (see UIObject.createClassObject()) to add a window to an application. The third way of adding a window to an application is to use the PopUpManager class. Use the PopUpManager to create modal windows that overlap other objects on the Stage. For more information, see Window class.

If you use the PopUpManager to add a Window component to a document, the Window instance will have its own FocusManager, distinct from the rest of the document. If you don't use the PopUpManager, the window's contents participate focus ordering with the other components in the document. For more information about controlling focus, see Creating custom focus navigation or FocusManager class.

See also:

  • Window component parameters
  • Creating an application with the Window component

Window component parameters

The following are authoring parameters that you can set for each Window component instance in the Property inspector or in the Component Inspector panel:

contentPath specifies the contents of the window. This can be the linkage identifier of the movie clip or the symbol name of a screen, form, or slide that contains the contents of the window. This can also be an absolute or relative URL for a SWF or JPG file to load into the window. The default value is "". Loaded content clips to fit the Window.

title indicates the title of the window.

closeButton indicates whether a close button is displayed (true) or not (false). Clicking the close button broadcasts a click event, but doesn't close the window. You must write a handler that calls Window.deletePopUp() to explicitly close the window. For more information about the click event, see Window.click.

You can write ActionScript to control these and additional options for Window components using its properties, methods, and events. For more information, see Window class.

Creating an application with the Window component

The following procedure explains how to add a Window component to an application. In this example, the window asks a user to change her password and confirm the new password.

To create an application with the Window component, do the following:

  1. Create a new movie clip that contains password and password confirmation fields, and OK and Cancel buttons. Name the movie clip PasswordForm.

    This is the content that will fill the Window. The content should be aligned at 0,0 because it is positioned in the upper left corner of the Window.

  2. In the library, select the PasswordForm movie clip and select Linkage from the Options menu.
  3. Check Export for ActionScript.

    The linkage identifier PasswordForm is automatically entered in the Identifier box.

  4. Enter mx.core.View in the class field and click OK.
  5. Drag a Window component from the Components panel to the Stage and delete the component from the Stage. This adds the component to the library.
  6. In the library, select the Window SWC and select Linkage from the Options menu.
  7. Check Export for ActionScript if it isn't already.
  8. Drag a button component from the Components panel to the Stage and in the Property inspector, give it the instance name button.
  9. Open the Actions panel, and enter the following click handler on Frame 1:
    buttonListener = new Object();
buttonListener.click = function(){
  myWindow = mx.managers.PopUpManager.createPopUp(_root, mx.containers.Window, true, { title:"Change Password", contentPath:"PasswordForm"});
  myWindow.setSize(240,110);
}
button.addEventListener("click", buttonListener);

    This handler calls PopUpManager.createPopUp() to instantiate a Window component with the title bar "Change Password" that displays the contents of the PasswordForm movie clip when the button is clicked. To close the Window when the OK or Cancel button is clicked, you will have to write another handler.


Customizing the Window component

You can transform a Window component horizontally and vertically both while authoring and at runtime. While authoring, select the component on the Stage and use the Free Transform tool or any of the Modify > Transform commands. At runtime, use UIObject.setSize().

Resizing the window does not change the size of the close button or title caption. The title caption is aligned to the left and the close bar to the right.

See also:

  • Using styles with the Window component
  • Using skins with the Window component

Using styles with the Window component

The style declaration of the title bar of a Window component is indicated by the Window.titleStyleDeclaration property.

A Window component that uses the Halo theme supports the following styles:

Style | Description
borderStyle | The component border; either "none", "inset", "outset", or "solid". This style does not inherit its value.

Using skins with the Window component

The Window component uses the RectBorder class which uses the ActionScript drawing API to draw its borders. You can use the setStyle() method (see UIObject.setStyle()) to change the following RectBorder style properties:

RectBorder styles | Letter
borderColor | a
highlightColor | b
borderColor | c
shadowColor | d
borderCapColor | e
shadowCapColor | f
shadowCapColor | g
borderCapColor | h

The style properties set the following positions on the border:

If you use UIObject.createClassObject() or PopUpManager.createPopUp() to create a Window instance dynamically (at runtime), you can also skin it dynamically. To skin a component at runtime, set the skin properties of the initObject parameter that is passed to the createClassObject() method. These skin properties set the names of the symbols to use as the button's states, both with and without an icon. For more information, see UIObject.createClassObject(), and PopUpManager.createPopUp().

A Window component uses the following skin properties:

Property | Description
skinTitleBackgroud | The title bar. The default value is TitleBackground.
skinCloseUp | The close button. The default value is CloseButtonUp.
skinCloseDown | The close button it its down state. The default value is CloseButtonDown.
skinCloseDisabled | The close button in its disabled state. The default value is CloseButtonDisabled.
skinCloseOver | The close button in its over state. The default value is CloseButtonOver.


Window class

Inheritance UIObject > UIComponent > View > ScrollView > Window

ActionScript Class Name mx.containers.Window

The properties of the Window class allow you to set the title caption, add a close button, and set the display content at runtime. Setting a property of the Window class with ActionScript overrides the parameter of the same name set in the Property inspector or Component Inspector panel.

The best way to instantiate a window is to call PopUpManager.createPopUp(). This method creates a window that can be modal (overlapping and disabling existing objects in an application) or non-modal. For example, the following code creates a modal Window instance (the last parameter indicates modality):

var newWindow = PopUpManager.createPopUp(this, Window, true);

Modality is simulated by creating a large transparent window underneath the Window component. Due to the way transparent windows are rendered, you may notice a slight dimming of the objects under the transparent window. The effective transparency can be set by changing the _global.style.modalTransparency value from 0 (fully transparent) to 100 (opaque). If you make the window partially transparent, you can also set the color of the window by changing the Modal skin in the default theme.

If you use PopUpManager.createPopUp() to create a modal Window, you must call Window.deletePopUp() to remove it to so that the transparent window is also removed. For example, if you use the closeButton on the window you would write the following code:

obj.click = function(evt){
   this.deletePopUp();
}
window.addEventListener("click", obj);

Note: Code does not stop executing when a modal window is created. In other environments (for example Microsoft Windows), if you create a modal window, the lines of code that follow the creation of the window do not run until the window is closed. In Flash, the lines of code are run after the window is created and before it is closed.

Each component class has a version property which is a class property. Class properties are only available on the class itself. The version property returns a string that indicates the version of the component. To access the version property, use the following code:

trace(mx.containers.Window.version);

Note: The following code returns undefined: trace(myWindowInstance.version);.

Method summary for the Window class

Method | Description
Window.deletePopUp() | Removes a window instance created by PopUpManager.createPopUp().

Inherits all methods from UIObject, UIComponent, and View.

Property summary for the Window class

Property | Description
Window.closeButton | Indicates whether a close button is included on the title bar (true) or not (false).
Window.content | A reference to the content specified in the contentPath property.
Window.contentPath | A path to the content that is displayed in the window.
Window.title | The text that displays in the title bar.
Window.titleStyleDeclaration | The style declaration that formats the text in the title bar.

Inherits all properties from UIObject, UIComponent, and ScrollView.

Event summary for the Window class

Event | Description
Window.click | Broadcast when the close button is released.
Window.complete | Broadcast when a Window is created.
Window.mouseDownOutside | Broadcast when the mouse is pressed outside the modal window.

Inherits all events from UIObject, UIComponent, View, and ScrollView.


Window.click

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(click){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.click = function(eventObject){
  ...
}
windowInstance.addEventListener("click", listenerObject)

Description

Event; broadcast to all registered listeners when the mouse is clicked (released) over the close button.

The first usage example uses an on() handler and must be attached directly to a Window component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the Window component instance myWindow, sends "_level0.myWindow" to the Output panel:

on(click){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (windowInstance) dispatches an event (in this case, click) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. The event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example creates a modal window and then defines a click handler that deletes the window. You must add a Window component to the Stage and then delete it to add the component to the document library, then add the following code to Frame 1:

import mx.managers.PopUpManager
import mx.containers.Window
var myTW = PopUpManager.createPopUp(_root, Window, true, {closeButton: true, title:"My Window"});
windowListener = new Object();
windowListener.click = function(evt){
  _root.myTW.deletePopUp();
}
myTW.addEventListener("click", windowListener);

See also

UIEventDispatcher.addEventListener(), Window.closeButton


Window.closeButton

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

windowInstance.closeButton

Description

Property; a Boolean value that indicates whether the title bar should have a close button (true) or not (false). This property must be set in the initObject parameter of the PopUpManager.createPopUp() method. The default value is false.

Example

The following code creates a window that displays the content in the movie clip "LoginForm" and has a close button on the title bar:

var myTW = PopUpManager.createPopUp(_root, Window, true,
  {contentPath:"LoginForm", closeButton:true});

See also

Window.click, PopUpManager.createPopUp()


Window.complete

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

listenerObject = new Object();
listenerObject.complete = function(eventObject){
  ...
}
windowInstance.addEventListener("complete", listenerObject)

Description

Event; broadcast to all registered listeners when a window is created. Use this event to size a window to fit its contents.

A component instance (windowInstance) dispatches an event (in this case, complete) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. The event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example creates a window and then defines a complete handler that resizes the window to fit its contents. Add a Window component to the Stage and then delete it to add the component to the document library, then add the following code to Frame 1:

import mx.managers.PopUpManager
import mx.containers.Window
var myTW = PopUpManager.createPopUp(_root, Window, true, {title:"Password Change", contentPath: "PasswordForm"});
lo = new Object();
lo.handleEvent = function(evtObj){
  if(evtObj.type == "complete"){
    _root.myTW.setSize(myTW.content._width, myTW.content._height + 25);
  }
}
myTW.addEventListener("complete", lo);

See also

UIEventDispatcher.addEventListener()


Window.content

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

windowInstance.content

Description

Property; a reference to the content (root movie clip) of the window. This property returns a MovieClip object. When you attach a symbol from the library, the default value is an instance of the attached symbol. When you load content from a URL, the default value is undefined until the load operation has started.

Example

Set the value of the text property within the content inside the window component:

loginForm.content.password.text = "secret";


Window.contentPath

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

windowInstance.contentPath

Description

Property; sets the name of the content to display in the window. This value can be the linkage identifier of a movie clip in the library or the absolute or relative URL of a SWF or JPG file to load. The default value is "" (empty string).

Example

The following code creates a Window instance that displays the movie clip with the linkage identifier "LoginForm":

var myTW = PopUpManager.createPopUp(_root, Window, true, {contentPath:"LoginForm"});


Window.deletePopUp()

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

windowInstance.deletePopUp();

Parameters

None.

Returns

Nothing.

Description

Method; deletes the window instance and removes the modal state. This method can only be called on window instances that were created by PopUpManager.createPopUp().

Example

The following code creates a modal window, then creates a listener that deletes the window with the close button is clicked:

var myTW = PopUpManager.createPopUp(_root, Window, true);
twListener = new Object();
twListener.click = function(){
  myTW.deletePopUp();
}
myTW.addEventListener("click", twListener);


Window.mouseDownOutside

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

Usage 1:

on(mouseDownOutside){
  ...
}

Usage 2:

listenerObject = new Object();
listenerObject.mouseDownOutside = function(eventObject){
  ...
}
windowInstance.addEventListener("mouseDownOutside", listenerObject)

Description

Event; broadcast to all registered listeners when the mouse is clicked (released) outside the modal window. This event is rarely used, but you can use it to dismiss a window if the user tries to interact with something outside of it.

The first usage example uses an on() handler and must be attached directly to a Window component instance. The keyword this, used inside an on() handler attached to a component, refers to the component instance. For example, the following code, attached to the Window component instance myWindowComponent, sends "_level0.myWindowComponent" to the Output panel:

on(click){
  trace(this);
}

The second usage example uses a dispatcher/listener event model. A component instance (windowInstance) dispatches an event (in this case, mouseDownOutside) and the event is handled by a function, also called a handler, on a listener object (listenerObject) that you create. You define a method with the same name as the event on the listener object; the method is called when the event is triggered. When the event is triggered, it automatically passes an event object (eventObject) to the listener object method. The event object has a set of properties that contains information about the event. You can use these properties to write code that handles the event. Finally, you call the UIEventDispatcher.addEventListener() method on the component instance that broadcasts the event to register the listener with the instance. When the instance dispatches the event, the listener is called.

For more information about event objects, see Event Objects.

Example

The following example creates a window instance and defines a mouseDownOutside handler that calls a beep() method if the user clicks outside the window:

var myTW = PopUpManager.createPopUp(_root, Window, true, undefined, true);
// create a listener
twListener = new Object();
twListener.mouseDownOutside = function()
{
    beep(); // make a noise if user clicks outside
}
myTW.addEventListener("mouseDownOutside", twListener);

See also

UIEventDispatcher.addEventListener()


Window.title

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

windowInstance.title

Description

Property; a string indicating the caption of the title bar. The default value is "" (empty string).

Example

The following code sets the title of the window to "Hello World":

myTW.title = "Hello World";


Window.titleStyleDeclaration

Availability

Flash Player 6 r79.

Edition

Flash MX 2004.

Usage

windowInstance.titleStyleDeclaration

Description

Property; a string indicating the style declaration that formats the title bar of a window. The default value is undefined which indicates bold, white text.

Example

The following code creates a window that displays the content of the movie clip with the linkage identifier "ChangePassword" and uses the CSSStyleDeclaration "MyTWStyles":

var myTW = PopUpManager.createPopUp(_root, Window, true, {contentPath:"LoginForm",
                                   titleStyleDeclaration:"MyTWStyles"});

For more information about styles, see Using styles to customize component color and text.


About the XMLConnector component (Flash Professional only)

The XMLConnector component is a Flash MX 2004 v2 component whose purpose is to read or write XML documents using HTTP get operations or post operations. It acts as a connector between other components and external XML data sources. The XMLConnector communicates with components in your application using either data binding features in the Flash MX Professional 2004 authoring environment, or ActionScript code. The XMLConnector component has properties, methods, and events but it has no runtime visual appearance.

The XMLConnector component and the WebServiceConnector component implement the RPC (Remote Procedure Call) Component API, a set of methods, properties, and events that define an easy way to send parameters to, and receive results from, an external data source.

Note: Although the XMLConnector component has properties and events (like other components), it is not visible at runtime.

Using the XMLConnector component (Flash Professional only)

The XMLConnector component provides your application with access to any external data source that returns or receives XML through HTTP. The easiest way to connect with an external XML data source and use the parameters and results of that data source for your application is to specify a schema, the structure of the XML document that identifies the data elements in the document to which you can bind.

For more information on working with the XMLConnector component, see Connecting to XML (Flash Professional only).For more information on connecting to XML, see Connecting to XML (Flash Professional only) in Using Flash Help.

XMLConnector component parameters

The following are authoring parameters that you can set for each XMLConnector component instance, in the Component Inspector panel Parameters tab:

direction A string that defines what type of operation to perform via HTTP when trigger() is called: send, sendAndLoad, or load correspond to receive, receive/send, and send, respectively.

ignoreWhite A Boolean value; the default setting is false. When this parameter is set to true, the text nodes that contain only white space are discarded during the parsing process. Text nodes with leading or trailing white space are unaffected.

multipleSimultaneousAllowed A Boolean value; when this parameter is set to true, it allows a trigger() operation to initiate when another trigger() operation is already in progress. Multiple simultaneous trigger() operations may not be completed in the same order they were called. Also, Flash Player may place limits on the number of simultaneous network operations. This limit varies by version and platform. When the parameter is set to false, a trigger() operation cannot initiate if another one is in progress.

suppressInvalidCall A Boolean value; when this parameter is set to true, it suppresses the trigger() operation if the data parameters are invalid. When it is set to false, the trigger() operation executes and uses invalid data if necessary.

URL A string that points to an external XML data source.

Common workflow for the XMLConnector component

The typical workflow for the XMLConnector component is as follows.

To use an XMLConnector component:

  1. Add an instance of the XMLConnector component to your application and give it an instance name.
  2. Use the Parameters tab of the Component Inspector panel to enter the URL for the external XML data source that you want to access.
  3. Use the Schema tab of the Component Inspector panel to specify a schema for the XML document.

    Note: You can use the Import Sample Schema button to automate this process.

  4. Use the Bindings tab of the Component Inspector panel to bind data elements (params and results) from the XML document to properties of the visual components in your application. For example, you can connect to an XML document that provides weather data and bind the Location and Temperature data elements to label components in your application. The name and temperature of a specified city appears in the application at runtime.
  5. Add a trigger to initiate the data binding operation using one of the following methods:
    • Attach the Trigger Data Source behavior to a button.
    • Add your own ActionScript to call the trigger() function on the XMLConnector.
    • Create a binding between an XML parameter and a UI control and set its Kind property to AutoTrigger (for more information, see Schema Kinds).

For a step-by-step example that connects and displays XML using the XMLConnector component, see XML Tutorial: Timesheet (Flash Professional Only).


XMLConnector class (Flash Professional only)

Inheritance RPC > XMLConnector

ActionScript Class Name mx.data.components.XMLConnector

Property summary for the XMLConnector class

Property | Description
XMLConnector.direction | Indicates whether data is being sent, received, or both.
XMLConnector.multipleSimultaneousAllowed | Indicates whether multiple calls can take place at the same time.
XMLConnector.params | Specifies data that will be sent to the server when the next trigger() operation is executed.
XMLConnector.results | Identifies data that was received from the server as a result of the trigger() operation.
XMLConnector.suppressInvalidCalls | Indicates whether to suppress a call if parameters are invalid.
XMLConnector.URL | The URL used by the component in HTTP operations.

Method summary for the XMLConnector class

Method | Description
XMLConnector.trigger() | Initiates a remote procedure call.

Event summary for the XMLConnector class

Event | Description
XMLConnector.result | Broadcast when a Remote Procedure Call completes successfully.
XMLConnector.send | Broadcast when the trigger() function is in process, after the parameter data has been gathered but before the data is validated and the Remote Call is initiated.
XMLConnector.status | Broadcast when a Remote Procedure Call is initiated, to inform the user of the status of the operation.


XMLConnector.direction

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.direction;

Description

Property; indicates whether data is being sent, received, or both. The values are the following:

  • send XML data for the params property is sent via HTTP POST to the URL for the XML document. Any data that is returned is ignored. The results property is not set to anything, and there is no result event (

    Note: The params and results property and the result event are inherited from the RPC component API.

  • receive No params data is sent to the URL. The URL for the XML document is accessed via HTTP GET, and valid XML data is expected from the URL.
  • send/receive Params data is sent to the URL and valid XML data is expected from the URL.

Example

The following example sets the direction to receive for the document mysettings.xml:

myXMLConnector.direction = "receive";
myXMLConnector.URL = "mysettings.xml";
myXMLConnector.trigger();


XMLConnector.multipleSimultaneousAllowed

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.multipleSimultaneousAllowed;

Description

Property; indicates whether multiple calls can take place at the same time. If false, then the trigger() function will perform a call if another call is already in progress. A status event will be emitted, with the code CallAlreadyInProgress. If true, then the call will take place.

When multiple calls are simultaneously in progress, there is no guarantee that they will complete in the same order as they were triggered. Also, Flash Player may place limits on the number of simultaneous network operations. This limit varies by version and platform.


XMLConnector.params

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.params;

Description

Property; specifies data that will be sent to the server when the next trigger() operation is executed. Each RPC component defines how this data is used, and what the valid types are.

Example

The following example defines name and city params for myXMLConnector:

myXMLConnector.params = new XML("<mydoc><name>Bob</name><city>Oakland</city></mydoc>");


XMLConnector.result

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.addEventListener("result", myListenerObject);

Description

Event; broadcasts when an Remote Procedure Call operation successfully completes.

The parameter to the event handler is an object with the following fields:

  • type: the string "result"
  • target: a reference to the object that emitted the event (for example, a WebServiceConnector component)

You can retrieve the actual result value using the results property.

Example

The following example defines a function res for the result event and assigns the function to the addEventListener event handler:

var res = function (ev) {
trace(ev.target.results);
};
xcon.addEventListener("result", res);


XMLConnector.results

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.results;

Description

Property; identifies data that was received from the server as a result of a trigger() operation. Each RPC component defines how this data is fetched, and what the valid types are. This data appears when the RPC operation has successfully completed, as signaled by the result event. It is available until the component is unloaded, or until the next RPC operation.

It is possible for the returned data to be very large. You can manage this in two ways:

  • Select an appropriate movie clip, Timeline, or screen as the parent for the RPC component. The component's storage will become available for garbage collection when the parent goes away.
  • In ActionScript, you can assign null to this property at any time.

Example

The following example traces the results property for myXMLConnector:

trace(myXMLConnector.results);


XMLConnector.send

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.addEventListener("send", myListenerObject);

Description

Event; broadcasts during the processing of a trigger() operation, after the parameter data has been gathered but before the data is validated and the Remote Procedure Call is initiated. This is a good place to put code that will modify the parameter data before the call.

The parameter to the event handler is an object with the following fields:

  • type: the string "send"
  • target: a reference to the object that emitted the event (for example, a WebServiceConnector component)

You can retrieve or modify the actual parameter values using the params property.

Example

The following example defines a function sendFunction for the send event and assigns the function to the addEventListener event handler:

var sendFunction = function (sendEnv) {
sendEnv.target.params = [newParam_txt.text];
};
xcon.addEventListener("send", sendFunction);


XMLConnector.status

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.addEventListener("status", myListenerObject);

Description

Event; broadcasts when a Remote Procedure Call is initiated, to inform the user of the status of the operation.

The parameter to the event handler is an object with the following fields:

  • type: the string "status"
  • target: a reference to the object that emitted the event (for example, a WebServiceConnector component)
  • code: a string giving the name of the specific condition that occurred.
  • data: an object whose contents depend on the code.

The code field for the status event is set to Fault if problems occur with the call, as follows:

Code | Data | Description
Fault | {faultcode: code, faultstring: string, detail: detail, element: element, faultactor: actor} | This event is emitted if other problems occur during the processing of the call. The data is a SOAPFault object. After this event occurs, the attempted call is considered complete, and there will be no "result" or "send" event.

The following are the faults that can occur with the status event:

FaultCode | FaultString | Notes
XMLConnector.Not.XML | params is not an XML object | The params must be an actionscript XML object.
XMLConnector.Parse.Error | params had XML parsing error NN. | The "status" property of the params XML object had a non-zero value NN. See the Flash Help information for XML.status to see the possible errors NN.
XMLConnector.No.Data.Received | no data was received from the server | RESTRICTION: due to various browser limitations, this message can either mean (a) the server URL was invalid, not responding, or returned an HTTP error code; or (b) the server request succeeded but the response happened to be 0 bytes of data. The recommended workaround is: design your application so that the server will NEVER return 0 bytes of data. If you get "XMLConnector.No.Data.Received", you will know for sure that there was a server error, and can inform the end-user accordingly.
XMLConnector.Results.Parse.Error | received data had an XML parsing error NN | The received XML was not valid, as determined by the Flash Player built-in XML parser. See Flash Help information on XML.status to see the possible errors NN.
XMLConnector.Params.Missing | Direction is 'send' or 'send/receive', but params are null. |

Example

The following example defines a function statusFunction for the status event and assigns the function to the addEventListener event handler:

var statusFunction = function (stat) {
trace(stat.code);
trace(stat.data.faultcode);
trace(stat.data.faultstring);
};
xcon.addEventListener("status", statusFunction);


XMLConnector.suppressInvalidCalls

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.suppressInvalidCalls;

Description

Property; indicates whether to suppress a call if parameters are invalid. If true, then the trigger() function will not perform a call if the bound parameters fail the validation. A "status" event will be emitted, with the code InvalidParams. If false, then the call will take place, using the invalid data as required.


XMLConnector.trigger()

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.trigger();

Description

Method; initiates a Remote Procedure Call. Each RPC component defines exactly what this involves. If the operation is successful, the results of the operation will appear in the RPC component's results property.

The trigger() method performs the following steps:

  1. If any data is bound to the params property, the method executes all the bindings to ensure that up-to-date data is available. This also causes data validation to occur.
  2. If the data is not valid and suppressInvalidCalls is set to true, the operation is discontinued.
  3. If the operation continues, the send event is emitted.
  4. The actual remote call is initiated using the connection method indicated (for example, HTTP).


XMLConnector.URL

Availability

Flash Player 6 r79.

Edition

Flash MX Professional 2004.

Usage

componentInstance.URL;

Description

Property; the URL that this component uses when doing HTTP operations. This URL may be either an absolute or relative URL. The URL is subject to all the standard Flash Player security protections.


About the XUpdateResolver component (Flash Professional only)

You use resolver components in combination with the DataSet component (part of the data management functionality in the Macromedia Flash data architecture). The resolver components enable you to convert changes made to the data within your application into a format that is appropriate for the external data source that you are updating. These components have no visual appearance at runtime.

XUpdate is a standard for describing changes that are made to an XML document and is supported by a variety of XML databases, such as Xindice or XHive. The XUpdateResolver component translates the changes made to a DataSet component into XUpdate statements. The updates from the XUpdateResolver component are sent in the form of an XUpdate data packet, which is communicated to the database or server through a connection object. The XUpdateResolver component gets a DeltaPacket from a DataSet component, sends its own update packet to a connector, receives server errors back from the connection, and communicates them back to the DataSet component—all using bindable properties.

For information about the working draft of the XUpdate language specification, see www.xmldb.org/xupdate/xupdate-wd.html. For more information, also see RDBMSResolver component (Flash Professional only), DataSet component (Flash Professional only), WebServiceConnector component (Flash Professional only), and XMLConnector component (Flash Professional only). For more information about the Flash data architecture, see Resolver components (Flash Professional only).For more information about resolving XML data, see Resolving XML data (Flash Professional only).

Note: You can also use the XUpdateResolver component to send data updates to any external data source that can parse the XUpdate language; for example, an ASP page, a Java servlet, or a ColdFusion component.

Using the XUpdateResolver component (Flash Professional only)

The XUpdateResolver component is used only when your Flash application contains a DataSet component and must send an update back to an external data source.

The XUpdateResolver component communicates with the DataSet component using the DataSetDeltaToXUpdateDelta encoder. This encoder is responsible for creating XPath statements that uniquely identify nodes within an XML file based on the information contained within the DataSet component's DeltaPacket. This information is used by the XUpdateResolver component to generate XUpdate statements. For more information on the DataSetDeltaToXUpdateDelta encoder, see Schema encoders (Flash Professional only).

For more information on working with the XUpdateResolver component, see Resolver components (Flash Professional only).XUpdateResolver component parameter

The XUpdateResolver component has one parameter, the includeDeltaPacketInfo parameter (Boolean type). When this parameter is set to true, the update packet includes additional information from the data set that can be used by an external data source to generate results that can be sent back to your application. This information includes a unique transaction and operation ID that is used internally by the data set.

Note: The additional information that is included in the update packet invalidates the XUpdate. This is expected behavior. You would choose to add this information only if you were going to store it within a server object and use it to generate a result packet. In this scenario, your server object would pull the information out of the update packet for it s own needs and then pass on the (now valid) XUpdate to the database.

Example (with false setting):

<xupdate:modifications version="1.0" xmlns:xupdate="http://www.xmldb.org/xupdate">
    <xupdate:remove select="/datapacket/row[@id='100']"/>
</xupdate:modifications>

Example (with true setting):

<xupdate:modifications version="1.0" xmlns:xupdate="http://www.xmldb.org/xupdate"
      transId="46386292065:Wed Jun 25 15:52:34 GMT-0700 2003">
    <xupdate:remove select="/datapacket/row[@id='100']" opId="0123456789"/>
</xupdate:modifications>

Common workflow for the XUpdateResolver component

The typical workflow for the XUpdateResolver component is as follows.

To use an XUpdateResolver component:

  1. Add two instances of the XMLConnector component and one instance each of the DataSet component and XUpdateResolver component to your application and give them instance names.
  2. Select the first XMLConnector component, and use the Parameters tab of the Component Inspector panel to enter the URL for the external XML data source that you want to access.
  3. With the XMLConnector component still selected, click the Schema tab of the Component Inspector panel and import a sample XML file to generate your schema.

    Note: You may need to create a virtual schema for your XML file if you want to access a subelement of the array that you are binding to the data set. For more information, see Virtual XML schemas.

  4. Use the Bindings tab of the Component Inspector panel to bind an array within the XMLConnector component to the dataProvider property of the DataSet component.
  5. Select the DataSet component and use the Schema tab of the Component Inspector panel to create the DataSet fields that will be bound to the fields of the object within the array.
  6. Use the Bindings tab of the Component Inspector panel to bind data elements (DataSet fields) to the visual components in your application.
  7. Select the Schema tab of the XUpdateResolver component. With the deltaPacket component property selected, use the Schema Attributes pane to set the encoder property to the DataSetDeltaToXUpdateDelta encoder.
  8. Select Encoder Options and enter the rowNodeKey value that uniquely identifies the row node within the XML file.

    Note: The rowNodeKey value combines an XPath statement with a field parameter to define how unique XPath statements should be generated for the update data contained within the DeltaPacket. See information on the DataSetDeltaToXUpdateDelta encoder in Schema encoders (Flash Professional only).

  9. Click the Bindings tab and create a binding between the XUpdateResolver component's deltaPacket property and the DataSet component's deltaPacket property.
  10. Create another binding from the xupdatePacket property to the second XMLConnector component to send the data back to the external data source.

    Note: The xupdatePacket property contains the formatted DeltaPacket (XUpdate statements) that will be sent to the server.

  11. Add a trigger to initiate the data binding operation: use the Trigger Data Source behavior attached to a button, or add ActionScript.

    Note: In addition to these steps, you an also create bindings to apply the result packet sent back from the server to the data set via the XUpdateResolver component.

For more information, see XUpdateResolver component (Flash Professional only).For a step-by-step example that resolves data to an external data source using XUpdate, see XUpdateTutorial: Update the Timesheet (Flash Professional Only).


XUpdateResolver class

Inheritance MovieClip

ActionScript Class Name mx.data.components.XUpdateResolver

Property summary for the XUpdateResolver component

Property | Description
XUpdateResolver.deltaPacket | Contains a description of the changes to the DataSet component.
XUpdateResolver.includeDeltaPacketInfo | Includes additional information from the deltaPacket in attributes on the XUpdate nodes.
XUpdateResolver.updateResults | Describes results of update.
XUpdateResolver.xupdatePacket | Contains the XUpdate translation of the changes to the DataSet component.

Event summary for the XUpdateResolver component

Event | Description
XUpdateResolver.beforeApplyUpdates | Called by the resolver component to make custom modifications immediately after the XML packet has been created and immediately prior to that packet being sent.
XUpdateResolver.reconcileResults | Called by the resolver component to compare two packets.


XUpdateResolver.beforeApplyUpdates

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.beforeApplyUpdates(eventObject)

Parameters

eventObject Resolver event object; describes the customizations to the XML packet before the update is sent through the connector to the database. This resolver event object should contain the following properties:

Property | Description
target | Object; resolver firing this event.
type | String; name of the event.
updatePacket | XML object; XML object about to be applied.

Returns

None.

Description

Event; called by the resolver component to make custom modifications immediately after the XML packet has been created for a new deltaPacket, and immediately prior to that packet being sent out using data binding. You can use this event handler to make custom modifications to the XML before sending the updated data to a connector.

Example

The following example adds the user authentication data to the XML packet:

on (beforeApplyUpdates) {
   // add user authentication data
   var userInfo = new XML( ""+getUserId()+" "+getPassword()+"" );
   xupdatePacket.firstChild.appendChild( userInfo );
}


XUpdateResolver.deltaPacket

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.deltaPacket

Description

Property; property of type deltaPacket that receives a deltaPacket to be translated into an xupdatePacket, and outputs a deltaPacket from any server results placed into the updateResults property. This event handler provides a way for you to make custom modifications to the XML before sending the updated data to a connector.

Messages in the updateResults property are treated as errors. This means that a delta with messages is added to the deltaPacket again so it can be resent the next time the deltaPacket is sent to the server. You must write code that handles deltas that have messages so that the messages are presented to the user and the deltas can be modified before being added to the next deltaPacket.


XUpdateResolver.includeDeltaPacketInfo

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.includeDeltaPacketInfo

Description

Property; property of type Boolean that, if true, includes additional information from the deltaPacket in attributes on the XUpdate nodes. This information will includes the transaction ID and operation ID.

For an example of the resulting XML, see Property summary for the XUpdateResolver component.


XUpdateResolver.reconcileResults

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.reconcileResults(eventObject)

Parameters

eventObject ResolverEvent object; describes the event object used to compare two updatePackets. This resolver event object should contain the following properties:

Property | Description
target | Object; resolver firing this event.
type | String; name of the event.

Returns

None.

Description

Event; use this callback to insert any code after the results have been received from the server and immediately prior to the transmission, through data binding, of the deltaPacket containing operation results. This is a good place to put code that handles messages from the server.

Example

The following example reconciles two updatePackets and clears the updates on success:

on (reconcileResults) {
     // examine results
     if( examine( updateResults ))
       myDataSet.purgeUpdates();
     else
       displayErrors( results );
}


XUpdateResolver.updateResults

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.updateResults

Description

Property; property of type deltaPacket that contains the results of an update returned from the server using a connector. Use this property to transmit errors and updated data from the server to a DataSet component; for example, when the server assigns new IDs for an auto-assigned field. Bind this property to a connector's Results property so that it can receive the results of an update and transmit the results back to the DataSet component.

Messages in the updateResults property are treated as errors. This means that a delta with messages is added to the deltaPacket again so it can be resent the next time the deltaPacket is sent to the server. You must write code that handles deltas that have messages so that the messages are presented to the user and the deltas can be modified before being added to the next deltaPacket.


XUpdateResolver.xupdatePacket

Availability

Flash Player 7.

Edition

Flash MX Professional 2004.

Usage

resolveData.xupdatePacket

Description

Property; property of type xml contains the XUpdate translation of the changes to the DataSet component. Bind this to the connector component's property that transmits the translated update packet of changes back to the DataSet component.


Overview of Client-Side Communication ActionScript

This document is designed to be used in combination with the ActionScript documentation included with Macromedia Flash MX 2004 and Macromedia Flash MX Professional 2004. To write Macromedia Flash Communication Server MX 1.5 applications, you must be familiar with writing ActionScript in general. Most of the sample code in this document uses syntax that is supported by ActionScript 2.0, which is new in Flash MX 2004. Refer to the Flash MX 2004 documentation for general scripting information, and use this document to add Flash Communication Server functionality to your Flash applications.

For an overview of the Flash Communication Server classes, see Developing Communication Applications.

Entries in this document are alphabetical by class name and then by method, property, or event handler name. The following table lists all classes, methods, properties, and event handlers individually in alphabetical order.

ActionScript element | See entry
activityLevel | Camera.activityLevel, Microphone.activityLevel
attachAudio | MovieClip.attachAudio(), NetStream.attachAudio()
attachVideo | NetStream.attachVideo(), Video.attachVideo()
bandwidth | Camera.bandwidth
bufferLength | NetStream.bufferLength
bufferTime | NetStream.bufferTime
call | NetConnection.call()
Camera | Camera class
clear | SharedObject.clear() , Video.clear()
close | NetConnection.close(), NetStream.close(), SharedObject.close()
connect | NetConnection.connect(), SharedObject.connect()
currentFps | Camera.currentFps, NetStream.currentFps
data | SharedObject.data
deblocking | Video.deblocking
flush | SharedObject.flush()
fps | Camera.fps
gain | Microphone.gain
get | Camera.get(), Microphone.get()
getLocal | SharedObject.getLocal()
getRemote | SharedObject.getRemote()
getSize | SharedObject.getSize()
height | Camera.height, Video.height
index | Camera.index, Microphone.index
isConnected | NetConnection.isConnected
keyFrameInterval | Camera.keyFrameInterval
LocalConnection | LocalConnection class
loopback | Camera.loopback
liveDelay | NetStream.liveDelay
Microphone | Microphone class
motionLevel | Camera.motionLevel
motionTimeOut | Camera.motionTimeOut
MovieClip | MovieClip class
muted | Camera.muted, Microphone.muted
name | Camera.name, Microphone.name
names | Camera.names, Microphone.names
NetConnection | NetConnection class
NetStream | NetStream class
onActivity | Camera.onActivity, Microphone.onActivity
onStatus | Camera.onStatus, Microphone.onStatus, NetConnection.onStatus, NetStream.onStatus, SharedObject.onStatus
onSync | SharedObject.onSync
pause | NetStream.pause()
play | NetStream.play()
publish | NetStream.publish()
quality | Camera.quality
rate | Microphone.rate
receiveAudio | NetStream.receiveAudio()
receiveVideo | NetStream.receiveVideo()
seek | NetStream.seek()
send | NetStream.send(), SharedObject.send()
setBufferTime | NetStream.setBufferTime()
setFps | SharedObject.setFps()
setGain | Microphone.setGain()
setKeyFrameInterval | Camera.setKeyFrameInterval()
setLoopback | Camera.setLoopback()
setMode | Camera.setMode()
setMotionLevel | Camera.setMotionLevel()
setQuality | Camera.setQuality()
setRate | Microphone.setRate()
setSilenceLevel | Microphone.setSilenceLevel()
setUseEchoSuppression | Microphone.setUseEchoSuppression()
SharedObject | SharedObject class
showSettings | System.showSettings()
silenceLevel | Microphone.silenceLevel
silenceTimeout | Microphone.silenceTimeout
smoothing | Video.smoothing
System | System class
time | NetStream.time
uri | NetConnection.uri
useCodepage | System.useCodepage
useEchoSuppression | Microphone.useEchoSuppression
Video | Video class
width | Camera.width, Video.width


The Camera class

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

The Camera class lets you capture video from a video camera attached to the computer that is running Macromedia Flash Player. When used with Flash Communication Server, this class lets you transmit, display, and optionally record the video being captured. With these capabilities, you can develop communications applications such as video conferencing, instant messaging with video, and so on. Flash provides similar audio capabilities; for more information, see the Microphone class entry.

You can also use a Camera object without a server—for example, to monitor a video feed from a webcam attached to your local system.

To create or reference a Camera object, use Camera.get().

Method summary for the Camera class

Method | Description
Camera.get() | Returns a default or specified Camera object, or null if the camera is not available.
Camera.setKeyFrameInterval() | Specifies which video frames are transmitted in full instead of being interpolated by the video compression algorithm.
Camera.setLoopback() | Specifies whether to use a compressed video stream for a local view of what the camera is transmitting.
Camera.setMode() | Sets aspects of the camera capture mode, including height, width, and frames per second.
Camera.setMotionLevel() | Specifies how much motion is required to invoke Camera.onActivity(true) and how much time should elapse without motion before Camera.onActivity(false) is invoked.
Camera.setQuality() | Sets the maximum amount of bandwidth per second or the required picture quality of the current outgoing video feed.

Property summary for the Camera class

Property (read-only) | Description
Camera.activityLevel | The amount of motion the camera is detecting.
Camera.bandwidth | The maximum amount of bandwidth the current outgoing video feed can use, in bytes.
Camera.currentFps | The rate at which the camera is capturing data, in frames per second.
Camera.fps | The rate at which you would like the camera to capture data, in frames per second.
Camera.height | The current capture height, in pixels.
Camera.index | The index of the camera, as reflected in the array returned by Camera.names.
Camera.keyFrameInterval | A number that specifies which video frames are transmitted in full instead of being interpolated by the video compression algorithm.
Camera.loopback | A Boolean value that specifies whether a local view of what the camera is capturing is compressed or uncompressed.
Camera.motionLevel | The amount of motion required to invoke Camera.onActivity(true).
Camera.motionTimeOut | The number of milliseconds between the time the camera stops detecting motion and the time Camera.onActivity(false) is invoked.
Camera.muted | A Boolean value that specifies whether the user has allowed or denied access to the camera.
Camera.name | The name of the camera as specified by the camera hardware.
Camera.names | Class property; an array of strings containing the names of all available video capture devices, including video capture cards and cameras.
Camera.quality | A number that specifies the current level of picture quality based on the amount of compression being applied to each video frame.
Camera.width | The current capture width, in pixels.

Event handler summary for the Camera class

Method | Description
Camera.onActivity | Invoked when the camera starts or stops detecting motion.
Camera.onStatus | Invoked when the user allows or denies access to the camera.

Constructor for the Camera class

See Camera.get().


Camera.activityLevel

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.activityLevel

Description

Read-only property; a numeric value that specifies the amount of motion the camera is detecting. Values range from 0 (no motion is being detected) to 100 (a large amount of motion is being detected). The value of this property can help you determine if you need to pass a setting to Camera.setMotionLevel().

If the camera is available but is not yet being used because neither Video.attachVideo() nor NetStream.attachVideo() has been called, this property is set to -1.

If you are streaming only uncompressed local video—that is, you are not streaming the video within a NetStream object and you have not called Camera.setLoopback() (true)—this property is set only if you have assigned a function to the Camera.onActivity event handler. Otherwise, it is undefined.

See also

Camera.motionLevel, Camera.onActivity, Camera.setMotionLevel()


Camera.bandwidth

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.bandwidth

Description

Read-only property; an integer that specifies the maximum amount of bandwidth the current outgoing video feed can use, in bytes. A value of 0 means that Flash video can use as much bandwidth as needed to maintain the desired frame quality.

To set this property, use Camera.setQuality().

Example

The following example loads another SWF file if the camera's bandwidth is 32 kilobytes or greater.

if(active_cam.bandwidth >= 32768){
  loadMovie("splat.swf",_root.hiddenvar);
}

See also

Camera.setQuality()


Camera.currentFps

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.currentFps

Description

Read-only property; the rate at which the camera is capturing data, in frames per second. This property cannot be set; however, you can use Camera.setMode() to set a related property—Camera.fps—which specifies the maximum frame rate at which you would like the camera to capture data.

See also

Camera.fps, Camera.setMode()


Camera.fps

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.fps

Description

Read-only property; the maximum rate at which you want the camera to capture data, in frames per second. The maximum rate possible depends on the capabilities of the camera; that is, if the camera doesn't support the value you set here, this frame rate will not be achieved.

  • To set a desired value for this property, use Camera.setMode().
  • To determine the rate at which the camera is currently capturing data, use Camera.currentFps.

Example

The following example sets the fps rate of the active camera, active_cam.fps, to the value provided by the user's text box, this.config.txt_fps.

if (this.config.txt_fps != undefined) {
     active_cam.setMode(active_cam.width, active_cam.height,
      this.config.txt_fps, false);
}

Note: The setMode() method does not guarantee the requested fps setting; it sets the fps you requested or the fastest fps available.

See also

Camera.currentFps, Camera.setMode()


Camera.get()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

Camera.get([index])

Note: The correct syntax is Camera.get(). To assign the Camera object to a variable, use syntax like var active_cam:Camera = Camera.get().

Parameters

index An optional zero-based integer that specifies which camera to get, as determined from the array returned by Camera.names. To get the default camera (which is recommended for most applications), omit this parameter.

Returns

  • If index is not specified, this method returns a reference to the default camera or, if it is in use by another application, to the first available camera. (If there is more than one camera installed, the user may specify the default camera in the Flash Player Camera Settings panel.) If no cameras are available or installed, the method returns null.
  • If index is specified, this method returns a reference to the requested camera, or null if it is not available.

Description

Method; returns a reference to a Camera object for capturing video. To actually begin capturing the video, you must attach the Camera object either to a Video object (see Video.attachVideo()) or to a NetStream object (see NetStream.attachVideo()). (The NetStream object is available only with Flash Communication Server.)

Unlike objects that you create using the new constructor, multiple calls to Camera.get() reference the same camera. Thus, if your script contains the lines cam1 = Camera.get() and cam2 = Camera.get(), both cam1 and cam2 reference the same (default) camera.

In general,you shouldn't pass a value for index; simply use Camera.get() to return a reference to the default camera. By means of the Camera settings panel (discussed later in this section), the user can specify the default camera Flash should use. If you pass a value for index, you might be trying to reference a camera other than the one the user prefers. You might use index in rare cases—for example, if your application is capturing video from two cameras at the same time.

When a SWF file tries to access the camera returned by Camera.get()—for example, when you issue NetStream.attachVideo() or Video.attachVideo()—Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access to the camera. (Make sure your Stage size is at least 215 by 138 pixels; this is the minimum size Flash requires to display the dialog box.)

When the user responds to this dialog box, the Camera.onStatus event handler returns an information object that indicates the user's response. To determine whether the user has denied or allowed access to the camera without processing this event handler, use Camera.muted.

The user can also specify permanent privacy settings for a particular domain by right-clicking (Windows) or Control-clicking (Macintosh) while a SWF file is playing, choosing Settings, opening the Privacy panel, and selecting Remember.

You can't use ActionScript to set the Allow or Deny value for a user, but you can display the Privacy panel for the user by using System.showSettings(0). If the user selects Remember, Flash Player no longer displays the Privacy dialog box for SWF files from this domain.

If Camera.get returns null, either the camera is in use by another application, or there are no cameras installed on the system. To determine whether any cameras are installed, use Camera.names.length. To display the Flash Player Camera Settings panel, which lets the user choose the camera to be referenced by Camera.get(), use System.showSettings(3).

Scanning the hardware for cameras takes time. When Flash finds at least one camera, the hardware is not scanned again for the lifetime of the Flash Player instance. However, if Flash doesn't find any cameras, it will scan each time Camera.get is called. This is helpful if a user has forgotten to connect the camera; if your SWF file provides a Try Again button that calls Camera.get, Flash can find the camera without the user having to restart the SWF file.

Example

The following example captures and displays video locally within a Video object named my_video on the Stage.

var active_cam:Camera = Camera.get();
my_video.attachVideo(active_cam);

See also

Camera.index, Camera.muted, Camera.names, Camera.onStatus, Camera.setMode(), NetStream.attachVideo(), System.showSettings(), Video.attachVideo()


Camera.height

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.height

Description

Read-only property; the current capture height, in pixels. To set a value for this property, use Camera.setMode().

Example

The following line of code updates a text box in the user interface with the current height value.

my_txt._height = active_cam.height;

See also the example for Camera.setMode().

See also

Camera.setMode(), Camera.width


Camera.index

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.index

Description

Read-only property; a zero-based integer that specifies the index of the camera, as reflected in the array returned by Camera.names.

See also

Camera.get(), Camera.names


Camera.keyFrameInterval

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.keyFrameInterval

Description

Read-only property; a number that specifies which video frames are transmitted in full (called keyframes) instead of being interpolated by the video compression algorithm. The default value is 15 (every 15th frame is a keyframe).

See also

Camera.setKeyFrameInterval()


Camera.loopback

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.loopback

Description

Read-only property; a Boolean value that specifies whether a local view of what the camera is capturing is compressed and decompressed as it would be for live transmission using Flash Communication Server (true) or uncompressed (false). The default value is false.

To set this value, use Camera.setLoopback(). To set the amount of compression used when this property is true, use Camera.setQuality().

Example

See the example for Camera.setLoopback().

See also

Camera.setLoopback(), Camera.setQuality()


Camera.motionLevel

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.motionLevel

Description

Read-only property; a numeric value that specifies the amount of motion required to invoke Camera.onActivity(true). Acceptable values range from 0 to 100. The default value is 50.

Video can be displayed regardless of the value of the motionLevel property. For more information, see Camera.setMotionLevel().

See also

Camera.activityLevel, Camera.onActivity, Camera.onStatus, Camera.setMotionLevel()


Camera.motionTimeOut

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.motionTimeOut

Description

Read-only property; the number of milliseconds between the time the camera stops detecting motion and the time Camera.onActivity(false) is invoked. The default value is 2000 (2 seconds).

To set this value, use Camera.setMotionLevel().

Example

The following example sets the number of milliseconds between the time the camera stops detecting motion and the time Camera.onActivity(false) is invoked to 1000 milliseconds, or 1 second.

if(active_cam.motionTimeOut >= 1000){
  active_cam.setMotionLevel(active_cam.motionLevel, 1000);
}

See also

Camera.onActivity, Camera.setMotionLevel()


Camera.muted

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.muted

Description

Read-only property; a Boolean value that specifies whether the user has denied access to the camera (true) or allowed access (false) in the Flash Player Privacy Settings panel. When this value changes, Camera.onStatus is invoked. For more information, see Camera.get().

Example

In the following example, when the user clicks the button, Flash publishes and plays a live stream if the camera is not muted.

on (press) {
  // If the user mutes camera, display offline notice.
  // Else, publish and play live stream from camera.
  if(active_cam.muted) {
    _root.debugWindow+="Camera offline." + newline;
  }
  else {

    // Publish the camera data by calling
    // the root function pubLive().
    _root.pubLive();

    // Play what is being published by calling
    // the root function playLive().
    _root.playLive();
  }
}

See also

Camera.get(), Camera.onStatus


Camera.name

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.name

Description

Read-only property; a string that specifies the name of the current camera, as returned by the camera hardware.

Example

The following example displays the name of the default camera in the Output panel. In Windows, this name is the same as the device name listed in the Scanners and Cameras properties sheet.

var active_cam:Camera = Camera.get();
trace("The camera name is: " + active_cam.name);

See also

Camera.get(), Camera.names


Camera.names

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

Camera.names

Note: The correct syntax is Camera.names. To assign the return value to a variable, use syntax like var cam_array:Array = Camera.names. To determine the name of the current camera, use active_cam.name, where active_cam is the variable to which you assigned the results of Camera.get().

Description

Read-only class property; retrieves an array of strings reflecting the names of all available video capture devices (including video capture cards and cameras) without displaying the Flash Player Privacy Settings panel. This array behaves the same as any other ActionScript array, implicitly providing the zero-based index of each camera and the number of cameras on the system (by means of Camera.names.length). For more information, see the Array class entry in ActionScript Dictionary Help.

Calling the Camera.names property requires an extensive examination of the hardware, and it may take several seconds to build the array. In most cases, you can just use the default camera.

Example

The following example uses the default camera unless more than one camera is available, in which case the user can choose which camera to set as the default camera.

var cam_array:Array = Camera.names;
if (cam_array.length == 1){
  var active_cam:Camera = Camera.get();
}
else {
  System.showSettings(3);
  var active_cam:Camera = Camera.get();
}

See also

Camera.get(), Camera.index, Camera.names


Camera.onActivity

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.onActivity = function(activity) {
  // your statements here
}

Parameters

activity A Boolean value set to true when the camera starts detecting motion, false when it stops.

Returns

Nothing.

Description

Event handler; invoked when the camera starts or stops detecting motion. If you want to respond to this event handler, you must create a function to process its activity value.

To specify the amount of motion required to invoke Camera.onActivity(true) and the amount of time that must elapse without activity before invoking Camera.onActivity(false), use Camera.setMotionLevel().

Example

The following example displays true or false in the Output panel when the camera starts or stops detecting motion.

// Assumes a Video object named "my_video" is on the Stage
var active_cam:Camera = Camera.get();
my_video.attachVideo(active_cam);
active_cam.setMotionLevel(10, 500);
active_cam.onActivity = function(mode) {
  trace(mode);
}

See also

Camera.setMotionLevel()


Camera.onStatus

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

active_cam.onStatus = function(infoObject) {
  // your statements here
}

Parameters

infoObject A parameter defined according to the status message. For more information about this parameter, see Camera information objects.

Returns

Nothing.

Description

Event handler; invoked when one of the following events occurs:

  • The user allows access to the camera. The Camera.muted property is set to false, and this handler is invoked with an information object whose code property is Camera.Unmuted.
  • The user denies access to the camera. The Camera.muted property is set to true, and this handler is invoked with an information object whose code property is Camera.Muted.

When a SWF file tries to access the camera, Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access. To determine whether the user has denied or allowed access to the camera without processing this event handler, use the Camera.muted property.

Note: If the user chooses to permanently allow or deny access for all SWF files from a specified domain, this handler is not invoked for SWF files from that domain unless the user later changes the privacy setting. For more information, see Camera.get().

If you want to respond to this event handler, you must create a function to process the information object generated by the camera For more information, see Client-Side Information Objects.

Example

The following event handler displays a message whenever the user allows or denies access to the camera.

// Assumes a Video object named "my_video" is on the Stage
var active_cam:Camera = Camera.get();
my_video.attachVideo(active_cam);
active_cam.onStatus = function(infoMsg) {

  if(infoMsg.code == "Camera.Muted"){
    trace("User denies access to the camera");
  }
  else
    trace("User allows access to the camera");
}
// Change the Allow or Deny value to invoke the function
System.showSettings(0);

See also

Camera.get(), Camera.muted, System.showSettings()


Camera.quality

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.quality

Description

Read-only property; an integer specifying the required level of picture quality, as determined by the amount of compression being applied to each video frame. Acceptable quality values range from 1 (lowest quality, maximum compression) to 100 (highest quality, no compression). The default value is 0, which means that picture quality can vary as needed to avoid exceeding available bandwidth.

See also

Camera.setQuality()


Camera.setKeyFrameInterval()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.setKeyFrameInterval(keyframeInterval)

Parameters

keyframeInterval A numeric value that specifies which video frames are transmitted in full (called keyframes) instead of being interpolated by the video compression algorithm. A value of 1 means that every frame is a keyframe, a value of 3 means that every third frame is a keyframe, and so on. Acceptable values are 1 through 48. The default value is 15.

Returns

Nothing.

Description

Method; specifies which video frames are transmitted in full (called keyframes) instead of being interpolated by the video compression algorithm. This method is generally applicable only if you are transmitting video using Flash Communication Server.

The Flash video compression algorithm compresses video by transmitting only what has changed since the last frame of the video; these portions are considered to be interpolated frames. It may help to compare this concept with how tweening and keyframes interact within the Flash authoring environment: the frames between keyframes are created (interpolated) based on the contents of the previous frame. Similarly, frames of a video can be interpolated according to the contents of the previous frame. A keyframe, however, is a video frame that is complete; it is not interpolated from prior frames.

To determine how to set a value for keyframeInterval, consider both bandwidth use and video playback accessibility. For example, specifying a higher value for keyframeInterval (sending keyframes less frequently) reduces bandwidth use. However, this may increase the amount of time required to position the playhead at a particular point in the video; more prior video frames may have to be interpolated before the video can resume.

Conversely, specifying a lower value for keyframeInterval (sending keyframes more frequently) increases bandwidth use, because entire video frames are transmitted more often, but may decrease the amount of time required to seek a particular video frame within a recorded video.

See also

Camera.keyFrameInterval


Camera.setLoopback()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.setLoopback(compressLocalStream)

Parameters

compressLocalStream A Boolean value that specifies whether to use a compressed video stream (true) or an uncompressed stream (false) for a local view of what the camera is receiving. The default value is false.

Returns

Nothing.

Description

Method; specifies whether to use a compressed video stream for a local view of the camera. This method is generally applicable only if you are transmitting video using the Flash Communication Server; setting compressLocalStream to true lets you see more precisely how the video will appear to users when they view it in real time.

Although a compressed stream is useful for testing purposes, such as previewing video quality settings, it has a significant processing cost, because the local view is not simply compressed; it is compressed, edited for transmission as it would be over a live connection, and then decompressed for local viewing.

To set the amount of compression used when you set compressLocalStream to true, use Camera.setQuality().

Example

In the following example, if the user presses a loopback button, the loopback value is set to true.

on (press) {

  if (_root.active_cam.loopback==false) {
    _root.active_cam.setLoopback(true);
  } else {
    debugWindow+="You're already compressing the stream." + newline;
  }

See also

Camera.loopback, Camera.setQuality()


Camera.setMode()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.setMode(width, height, fps [, favorSize])

Parameters

width The requested capture width, in pixels. The default value is 160.

height The requested capture height, in pixels. The default value is 120.

fps The requested rate at which the camera should capture data, in frames per second. The default value is 15.

favorSize Optional: a Boolean value that specifies how to manipulate the width, height, and frame rate if the camera does not have a native mode that meets the specified requirements. The default value is true, which means that maintaining capture size is favored; using this parameter selects the mode that most closely matches width and height values, even if doing so adversely affects performance by reducing the frame rate. To maximize frame rate at the expense of camera height and width, pass false for the favorSize parameter.

Returns

Nothing.

Description

Method; sets the camera capture mode to the native mode that best meets the specified requirements. If the camera does not have a native mode that matches all the parameters you pass, Flash selects a capture mode that most closely synthesizes the requested mode. This manipulation may involve cropping the image and dropping frames.

By default, Flash drops frames as needed to maintain image size. To minimize the number of dropped frames, even if this means reducing the size of the image, pass false for the favorSize parameter.

When choosing a native mode, Flash tries to maintain the requested aspect ratio whenever possible. For example, if you issue the command active_cam.setMode(400, 400, 30), and the maximum width and height values available on the camera are 320 and 288, Flash sets both the width and height at 288; by setting these properties to the same value, Flash maintains the 1:1 aspect ratio you requested.

To determine the values assigned to these properties after Flash selects the mode that most closely matches your requested values, use Camera.width, Camera.height, and Camera.fps.

If you are using Flash Communication Server, you can also capture single frames or create time-lapsed photography. For more information, see NetStream.attachVideo().

Example

The following example sets the width, height, and fps based on the user's input if the user clicks the button. The optional parameter, favorSize is not included, because the default value, true, will provide the settings closest to the user's preference without sacrificing the picture quality, although the fps may then be sacrificed. The user interface is then updated with the new settings.

on (press) {
  // Sets width, height, and fps to user's input.
  _root.active_cam.setMode(txt_width, txt_height, txt_fps);

  // Update the user's text fields with the new settings.
  _root.txt_width = active_cam.width;
  _root.txt_height = active_cam.height;
  _root.txt_fps = active_cam.fps;
}

See also

Camera.currentFps, Camera.fps, Camera.height, Camera.width, NetStream.attachVideo()


Camera.setMotionLevel()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.setMotionLevel(sensitivity [, timeout])

Parameters

sensitivity A numeric value that specifies the amount of motion required to invoke Camera.onActivity(true). Acceptable values range from 0 to 100. The default value is 50.

timeout An optional numeric parameter that specifies how many milliseconds must elapse without activity before Flash considers activity to have stopped and invokes the Camera.onActivity(false) event handler. The default value is 2000 (2 seconds).

Returns

Nothing.

Description

Method; specifies how much motion is required to invoke Camera.onActivity(true). Optionally sets the number of milliseconds that must elapse without activity before Flash considers motion to have stopped and invokes Camera.onActivity(false).

Note: Video can be displayed regardless of the value of the sensitivity parameter. This parameter only determines when and under what circumstances Camera.onActivity is invoked—not whether video is actually being captured or displayed.

  • To prevent the camera from detecting motion at all, pass a value of 100 for sensitivity; Camera.onActivity is never invoked. (You would probably use this value only for testing purposes—for example, to temporarily disable any actions set to occur when Camera.onActivity is invoked.)
  • To determine the amount of motion the camera is currently detecting, use the Camera.activityLevel property.

Motion sensitivity values correspond directly to activity values. Complete lack of motion is an activity value of 0. Constant motion is an activity value of 100. Your activity value is less than your motion sensitivity value when you're not moving; when you are moving, activity values frequently exceed your motion sensitivity value.

This method is similar in purpose to Microphone.setSilenceLevel(); both methods are used to specify when the onActivity event handler should be invoked. However, these methods have a significantly different impact on publishing streams:

  • Microphone.setSilenceLevel() is designed to optimize bandwidth. When an audio stream is considered silent, no audio data is sent. Instead, a single message is sent, indicating that silence has started.
  • Camera.setMotionLevel() is designed to detect motion and does not affect bandwidth usage. Even if a video stream does not detect motion, video is still sent.

Example

The following example sends messages to the Output panel when video activity starts or stops. Change the motion sensitivity value of 30 to a higher or lower number to see how different values affect motion detection.

// Assumes a Video object named "my_video" is on the Stage
var active_cam:Camera = Camera.get();
x = 0;
function motion(mode) {
  trace(x + ": " + mode);
  x++;
}
active_cam.onActivity = function(mode) {
  motion(mode);
}
active_cam.setMotionLevel(30, 500);
my_video.attachVideo(active_cam);

See also

Camera.activityLevel, Camera.motionLevel, Camera.motionTimeOut, Camera.onActivity


Camera.setQuality()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.setQuality(bandwidth, frameQuality)

Parameters

bandwidth An integer that specifies the maximum amount of bandwidth that the current outgoing video feed can use, in bytes per second. To specify that Flash video can use as much bandwidth as needed to maintain the value of frameQuality, pass 0 for bandwidth. The default value is 16384.

frameQuality An integer that specifies the required level of picture quality, as determined by the amount of compression being applied to each video frame. Acceptable values range from 1 (lowest quality, maximum compression) to 100 (highest quality, no compression). To specify that picture quality can vary as needed to avoid exceeding bandwidth, pass 0 for frameQuality. The default value is 0.

Tip: Streams compressed with the lossless codec are larger than streams compressed with the default Sorenson codec.

Returns

Nothing.

Description

Method; sets the maximum amount of bandwidth per second or the required picture quality of the current outgoing video feed.

Use this method to specify which element of the outgoing video feed is more important to your application—bandwidth use or picture quality.

  • To indicate that bandwidth use takes precedence, pass a value for bandwidth and 0 for frameQuality. Flash will transmit video at the highest quality possible within the specified bandwidth. If necessary, Flash will reduce picture quality to avoid exceeding the specified bandwidth. In general, as motion increases, quality decreases.
  • To indicate that quality takes precedence, pass 0 for bandwidth and a numeric value for frameQuality. Flash will use as much bandwidth as required to maintain the specified quality. If necessary, Flash will reduce the frame rate to maintain picture quality. In general, as motion increases, bandwidth use also increases.
  • To specify that both bandwidth and quality are equally important, pass numeric values for both parameters. Flash will transmit video that achieves the specified quality and that doesn't exceed the specified bandwidth. If necessary, Flash will reduce the frame rate to maintain picture quality without exceeding the specified bandwidth.

Example

The following examples illustrate how to use this method to control bandwidth use and picture quality.

// Ensure that no more than 8192 (8K/second) is used to send video
active_cam.setQuality(8192,0);

// Ensure that no more than 8192 (8K/second) is used to send video
//   with a minimum quality of 50
active_cam.setQuality(8192,50);

// Ensure a minimum quality of 50, no matter how much bandwidth it takes
active_cam.setQuality(0,50);

See also

Camera.bandwidth, Camera.get(), Camera.quality


Camera.width

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_cam.width

Description

Read-only property; the current capture width, in pixels. To set a desired value for this property, use Camera.setMode().

Example

The following line of code updates a text box in the user interface with the current width value.

myTextField.text=active_cam.width;

See also the example for Camera.setMode().

See also

Camera.height, Camera.setMode()


The LocalConnection class

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

For information about this class, see the LocalConnection class entry in ActionScript Dictionary Help.


The Microphone class

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

The Microphone class lets you capture audio from a microphone attached to the computer that is running Flash Player.

When used with Flash Communication Server, this class lets you transmit, play, and optionally record the audio being captured. With these capabilities, you can develop communications applications such as instant messaging with audio, recording presentations so others can replay them at a later date, and so on. Flash provides similar video capabilities; for more information, see the Camera class entry.

You can also use a Microphone object without a server—for example, to transmit sound from your microphone through the speakers on your local system.

To create or reference a Microphone object, use the Microphone.get() method.

Method summary for the Microphone class

Method | Description
Microphone.get() | Returns a default or specified Microphone object, or null if the microphone is not available.
Microphone.setGain() | Specifies the amount by which the microphone should boost the signal.
Microphone.setRate() | Specifies the rate at which the microphone should capture sound, in kHz.
Microphone.setSilenceLevel() | Specifies the amount of sound required to activate the microphone.
Microphone.setUseEchoSuppression() | Specifies whether to use the echo suppression feature of the audio codec.

Property summary for the Microphone class

Property (read-only) | Description
Microphone.activityLevel | The amount of sound the microphone is detecting.
Microphone.gain | The amount by which the microphone boosts the signal before transmitting it.
Microphone.index | The index of the current microphone.
Microphone.muted | A Boolean value that specifies whether the user has allowed or denied access to the microphone.
Microphone.name | The name of the current sound capture device, as returned by the sound capture hardware.
Microphone.names | Class property: an array of strings reflecting the names of all available sound capture devices, including sound capture cards and microphones.
Microphone.rate | The sound capture rate, in kHz.
Microphone.silenceLevel | The amount of sound required to activate the microphone.
Microphone.silenceTimeout | The number of milliseconds between the time the microphone stops detecting sound and the time Microphone.onActivity (false) is called.
Microphone.useEchoSuppression | A Boolean value that specifies whether echo suppression is being used.

Event handler summary for the Microphone class

Method | Description
Microphone.onActivity | Invoked when the microphone starts or stops detecting sound.
Microphone.onStatus | Invoked when the user allows or denies access to the microphone.

Constructor for the Microphone class

See Microphone.get().


Microphone.activityLevel

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.activityLevel

Description

Read-only property; a numeric value that specifies the amount of sound the microphone is detecting. Values range from 0 (no sound is being detected) to 100 (very loud sound is being detected). The value of this property can help you determine a good value to pass to the Microphone.setSilenceLevel() method.

If the microphone is available but is not yet being used because neither MovieClip.attachAudio() nor NetStream.attachAudio() has been called, this property is set to -1.

Example

The following example sets the variable level to the activity level of the current microphone, my_mic.activityLevel.

var level:Number = my_mic.activityLevel;

See also

Microphone.setGain()


Microphone.gain

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.gain

Description

Read-only property; the amount by which the microphone boosts the signal. Valid values are 0 to 100. The default value is 50.

Example

The following example is attached to the nib of a slide bar. When this clip is loaded, Flash checks for the value active_mic.gain and provides a default value if this value is undefined. The _x position is then used to set the gain on the microphone to the user's preference.

onClipEvent (load) {
  if (_root.active_mic.gain == undefined) {
    _root.active_mic.setGain = 75;
  }

  this._x = _root.active_mic.gain;
  _root.txt_micgain = this._x;

  left = this._x;
  right = left+50;
  top = this._y;
  bottom = top;
}

on (press) {
  startDrag(this, false, left, top, right, bottom);
  this._xscale = 100;
  this._yscale = 100;
}

on (release, releaseOutside) {
  stopDrag();
  g = (this._x-50)*2;
  _root.active_mic.setGain(g);
  _root.txt_micgain = g;
  this._xscale = 100;
  this._yscale = 100;
}

See also

Microphone.setGain()


Microphone.get()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

Microphone.get([index])

Note: The correct syntax is Microphone.get(). To assign the Microphone object to a variable, use syntax like var active_mic:Microphone = Microphone.get().

Parameters

index An optional zero-based integer that specifies which microphone to get, as determined from the array returned by Microphone.names. To get the default microphone (which is recommended for most applications), omit this parameter.

Returns

  • If index is not specified, this method returns a reference to the default microphone or, if it is not available, to the first available microphone. If no microphones are available or installed, the method returns null.
  • If index is specified, this method returns a reference to the requested microphone, or null if it is not available.

Description

Method; returns a reference to a Microphone object for capturing audio. To actually begin capturing the audio, you must attach the Microphone object either to a MovieClip object (see MovieClip.attachAudio()) or to a NetStream object (see NetStream.attachAudio()). (The NetStream object is available only with Flash Communication Server.)

Unlike objects that you create using the new constructor, multiple calls to Microphone.get() reference the same microphone. Thus, if your script contains the lines mic1 = Microphone.get() and mic2 = Microphone.get(), both mic1 and mic2 reference the same (default) microphone.

In general, you shouldn't pass a value for index; simply use the Microphone.get() method to return a reference to the default microphone. By means of the Microphone settings panel (discussed later in this section), the user can specify the default microphone Flash should use. If you pass a value for index, you might be trying to reference a microphone other than the one the user prefers. You might use index in rare cases—for example, if your application is capturing audio from two microphones at the same time.

When a SWF file tries to access the microphone returned by the Microphone.get() method—for example, when you issue NetStream.attachAudio() or MovieClip.attachAudio()— Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access to the microphone. (Make sure your Stage size is at least 215 x 138 pixels; this is the minimum size Flash requires to display the dialog box.)

When the user responds to this dialog box, the Microphone.onStatus event handler returns an information object that indicates the user's response. To determine whether the user has denied or allowed access to the camera without processing this event handler, use Microphone.muted.

The user can also specify permanent privacy settings for a particular domain by right-clicking (Windows) or Control-clicking (Macintosh) while a SWF file is playing, choosing Settings, opening the Privacy panel, and selecting Remember.

You can't use ActionScript to set the Allow or Deny value for a user, but you can display the Privacy panel for the user by using System.showSettings(0). If the user selects Remember, Flash Player no longer displays the Privacy dialog box for SWF files from this domain.

If Microphone.get() returns null, either the microphone is in use by another application, or there are no microphones installed on the system. To determine whether any microphones are installed, use Microphones.names.length. To display the Flash Player Microphone Settings panel, which lets the user choose the microphone to be referenced by Microphone.get(), use System.showSettings(2).

Example

The following example lets the user specify the default microphone, then captures audio and plays it back locally. To avoid feedback, you may want to test this code while wearing headphones.

System.showSettings(2);
var active_mic:Microphone = Microphone.get();
_root.attachAudio(active_mic);

See also

Microphone.index, Microphone.muted, Microphone.names, Microphone.onStatus, MovieClip.attachAudio(), NetStream.attachAudio() , System.showSettings()


Microphone.index

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.index

Description

Read-only property; a zero-based integer that specifies the index of the microphone, as reflected in the array returned by Microphone.names.

See also

Microphone.get(), Microphone.names


Microphone.muted

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.muted

Description

Read-only property; a Boolean value that specifies whether the user has denied access to the microphone (true) or allowed access (false). When this value changes, Microphone.onStatus is invoked. For more information, see Microphone.get() .

Example

In the following example, when the user clicks the button, Flash publishes and plays a live stream if the microphone is not muted.

on (press) {
  // If the user mutes microphone, display offline notice.
  // Else, publish and play live stream from microphone.
  if(active_mic.muted) {
    _root.debugWindow+="Microphone offline." + newline;
  } else {

    // Publish the microphone data by calling
    // the root function pubLive().
    _root.pubLive();

    // Play what is being published by calling
    // the root function playLive().
    _root.playLive();
  }
}

See also

Microphone.get(), Microphone.onStatus


Microphone.name

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.name

Description

Read-only property; a string that specifies the name of the current sound capture device, as returned by the sound capture hardware.

Example

The following example displays the name of the default microphone in the Output panel.

var active_mic:Microphone = Microphone.get();
trace("The microphone name is: " + active_mic.name);

See also

Microphone.get(), Microphone.names


Microphone.names

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

Microphone.names

Note: The correct syntax is Microphone.names. To assign the return value to a variable, use syntax like var micNames_array:Array = Microphone.names. To determine the name of the current microphone, use active_mic.name, where active_mic is the variable to which you assigned the results of Microphone.get().

Description

Read-only class property; retrieves an array of strings reflecting the names of all available sound capture devices without displaying the Flash Player Privacy Settings panel. This array behaves the same as any other ActionScript array, implicitly providing the zero-based index of each sound capture device and the number of sound capture devices on the system (by means of Microphone.names.length). For more information, see the Array class entry in ActionScript Dictionary Help.

Calling Microphone.names requires an extensive examination of the hardware, and it may take several seconds to build the array. In most cases, you can just use the default microphone.

Example

The following code returns information on the array of audio devices.

var allMicNames_array:Array = Microphone.names;
trace("Microphone.names located these device(s):");
for(i=0; i < allMicNames_array.length; i++){
 trace("[" + i + "]: " + allMicNames_array[i]);
}

For example, the following information could be displayed.

Microphone.names located these device(s):
[0]: Crystal SoundFusion(tm)
[1]: USB Audio Device

See also

Array class entry in ActionScript Dictionary Help, Microphone.get() , Microphone.name


Microphone.onActivity

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.onActivity = function(activity) {
  // Your code here
}

Parameters

activity A Boolean value set to true when the microphone starts detecting sound, false when it stops.

Returns

Nothing.

Description

Event handler; invoked when the microphone starts or stops detecting sound. If you want to respond to this event handler, you must create a function to process its activity value.

To specify the amount of sound required to invoke Microphone.onActivity(true), and the amount of time that must elapse without sound before Microphone.onActivity(false) is invoked, use Microphone.setSilenceLevel().

Example

The following example displays true or false in the Output panel when the microphone starts or stops detecting sound.

var active_mic:Microphone = Microphone.get();
_root.attachAudio(active_mic);
active_mic.onActivity = function(mode){
  trace(mode);
}

See also

Microphone.setSilenceLevel()


Microphone.onStatus

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.onStatus = function(infoObject) {
  // Your code here
}

Parameters

infoObject A parameter defined according to the status message. For more information about this parameter, see Microphone information objects.

Returns

Nothing.

Description

Event handler; invoked when the user allows or denies access to the microphone. If you want to respond to this event handler, you must create a function to process the information object generated by the microphone. For more information, see Client-Side Information Objects.

When a SWF file tries to access the microphone, Flash Player displays a Privacy dialog box that lets the user choose whether to allow or deny access.

  • If the user allows access, the Microphone.muted property is set to false, and this event handler is invoked with an information object whose code property is Microphone.Unmuted.
  • If the user denies access, the Microphone.muted property is set to true, and this event handler is invoked with an information object whose code property is Microphone.Muted.

To determine whether the user has denied or allowed access to the microphone without processing this event handler, use Microphone.muted.

Note: If the user chooses to permanently allow or deny access for all SWF files from a specified domain, this method is not invoked for SWF files from that domain unless the user later changes the privacy setting. For more information, see Microphone.get().

Example

See the example for Camera.onStatus.

See also

Microphone.get(), Microphone.muted, System.showSettings()


Microphone.rate

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.rate

Description

Read-only property; the rate at which the microphone is capturing sound, in kHz. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz.

To set this value, use Microphone.setRate().

Example

The following example saves the current rate to the variable original.

var active_mic:Microphone = Microphone.get();
var original:Number = active_mic.rate;

See also

Microphone.setRate()


Microphone.setGain()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.setGain(gain)

Parameters

gain An integer that specifies the amount by which the microphone should boost the signal. Valid values are 0 to 100. The default value is 50; however, the user may change this value in the Flash Player Microphone Settings panel.

Returns

Nothing.

Description

Method; sets the microphone gain—that is, the amount by which the microphone should multiply the signal before transmitting it. A value of 0 tells Flash to multiply by 0; that is, the microphone transmits no sound.

You can think of this setting like a volume knob on a stereo: 0 is no volume and 50 is normal volume; numbers below 50 specify lower than normal volume, while numbers above 50 specify higher than normal volume.

Example

The following example ensures that the microphone gain setting is less than or equal to 55.

var active_mic:Microphone = Microphone.get();
if (active_mic.gain > 55){
  active_mic.setGain(55);
}

See also

Microphone.gain, Microphone.setUseEchoSuppression()


Microphone.setRate()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.setRate(kHz)

Parameters

kHz The rate at which the microphone should capture sound, in kHz. Acceptable values are 5, 8, 11, 22, and 44. The default value is 8 kHz if your sound capture device supports this value. Otherwise, the default value is the next available capture level above 8 kHz that your sound capture device supports, usually 11 kHz.

Returns

Nothing.

Description

Method; sets the rate, in kHz, at which the microphone should capture sound.

Example

The following example sets the microphone rate to the user's preference (which you have assigned to the userRate variable) if it is one of the following values: 5, 8, 11, 22, or 44. If it is not, the value is rounded to the nearest acceptable value that the sound capture device supports.

active_mic.setRate(userRate);

See also

Microphone.rate


Microphone.setSilenceLevel()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.setSilenceLevel(level [, timeout])

Parameters

level An integer that specifies the amount of sound required to activate the microphone and invoke Microphone.onActivity(true). Acceptable values range from 0 to 100. The default value is 10.

timeout An optional integer parameter that specifies how many milliseconds must elapse without activity before Flash considers sound to have stopped and invokes Microphone.onActivity(false). The default value is 2000 (2 seconds).

Returns

Nothing.

Description

Method; sets the minimum input level that should be considered sound and (optionally) the amount of silent time signifying that silence has actually begun.

  • To prevent the microphone from detecting sound at all, pass a value of 100 for level; Microphone.onActivity is never invoked.
  • To determine the amount of sound the microphone is currently detecting, use Microphone.activityLevel.

Activity detection is the ability to detect when audio levels suggest that a person is talking. When someone is not talking, bandwidth can be saved because there is no need to send the associated audio stream. This information can also be used for visual feedback so that users know they (or others) are silent.

Silence values correspond directly to activity values. Complete silence is an activity value of 0. Constant loud noise (as loud as can be registered based on the current gain setting) is an activity value of 100. After gain is appropriately adjusted, your activity value is less than your silence value when you're not talking; when you are talking, the activity value exceeds your silence value.

This method is similar in purpose to Camera.setMotionLevel(); both methods are used to specify when the onActivity event handler should be invoked. However, these methods have a significantly different impact on publishing streams:

  • Camera.setMotionLevel() is designed to detect motion and does not affect bandwidth usage. Even if a video stream does not detect motion, video is still sent.
  • Microphone.setSilenceLevel() is designed to optimize bandwidth. When an audio stream is considered silent, no audio data is sent. Instead, a single message is sent, indicating that silence has started.

Example

The following example changes the silence level to 75.

var active_mic:Microphone = Microphone.get();
trace(active_mic.silenceLevel);
active_mic.setSilenceLevel(75);
trace(active_mic.silenceLevel);

See also the example for Camera.setMotionLevel().

See also

Microphone.activityLevel, Microphone.onActivity, Microphone.setGain(), Microphone.silenceLevel, Microphone.silenceTimeout


Microphone.setUseEchoSuppression()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.setUseEchoSuppression(suppress)

Parameters

suppress A Boolean value indicating whether echo suppression should be used (true) or not (false).

Returns

Nothing.

Description

Method; specifies whether to use the echo suppression feature of the audio codec. The default value is false unless the user has selected Reduce Echo in the Flash Player Microphone Settings panel.

Echo suppression is an effort to reduce the effects of audio feedback, which is caused when sound going out the speaker is picked up by the microphone on the same computer. (This is different from echo cancellation, which completely removes the feedback.)

Generally, echo suppression is advisable when the sound being captured is played through speakers—instead of a headset—on the same computer. If your SWF file allows users to specify the sound output device, you may want to call Microphone.setUseEchoSuppression(true) if they indicate they are using speakers and will be using the microphone as well.

Users can also adjust these settings in the Flash Player Microphone Settings panel.

Example

The following example turns on echo suppression.

var active_mic:Microphone = Microphone.get();
active_mic.setUseEchoSuppression(true);

See also

Microphone.setGain(), Microphone.useEchoSuppression


Microphone.silenceLevel

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.silenceLevel

Description

Read-only property; an integer that specifies the amount of sound required to activate the microphone and invoke Microphone.onActivity(true). The default value is 10.

Example

See the example for Microphone.silenceTimeout.

See also

Microphone.gain, Microphone.onActivity , Microphone.setSilenceLevel()


Microphone.silenceTimeout

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.silenceTimeout

Description

Read-only property; a numeric value representing the number of milliseconds between the time the microphone stops detecting sound and the time Microphone.onActivity(false) is invoked. The default value is 2000 (2 seconds).

To set this value, use Microphone.setSilenceLevel().

Example

The following example sets the timeout to two times its current value.

var active_mic:Microphone = Microphone.get();
trace(active_mic.silenceTimeOut);
active_mic.setSilenceLevel(active_mic.silenceLevel,
  active_mic.silenceTimeOut * 2);
trace(active_mic.silenceTimeOut);

See also

Microphone.onActivity , Microphone.setSilenceLevel()


Microphone.useEchoSuppression

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

active_mic.useEchoSuppression

Description

Read-only property; a Boolean value of true if echo suppression is enabled, false otherwise. The default value is false unless the user has selected Reduce Echo in the Flash Player Microphone Settings panel.

Example

The following example checks for echo suppression and turns it on if it is off.

var active_mic:Microphone = Microphone.get();
active_mic.onActivity = function(active) {
  if (active == true) {
    if (active_mic.useEchoSuppression == false) {
      active_mic.setUseEchoSuppression(true);
    }
  }
}

See also

Microphone.setUseEchoSuppression()


The MovieClip class

This class is discussed in detail in ActionScript Dictionary Help. Only the method used by Flash Communication Server is discussed in this section.

Method summary for the MovieClip class

Method | Description
MovieClip.attachAudio() | Starts or stops playback of an audio source.


MovieClip.attachAudio()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

my_mc.attachAudio(source)

Parameters

source The object containing the audio to play. Valid values are a Microphone object, a NetStream object (requires Flash Communication Server), and false (stops playing the audio).

Note: In Flash Player 7 and later, source can also be a NetStream object playing an FLV file without the use of Flash Communication Server. .For more information, see the NetStream class entry in ActionScript Dictionary Help.

Returns

Nothing.

Description

Method; specifies the audio source to be either played locally (Microphone object) or streamed from the Flash Communication Server (NetStream object). To stop playing the audio source, pass false for source.

  • To play local audio, pass a Microphone object as source. This captures and plays local audio from the microphone hardware.
  • To play live or recorded audio streaming from the Flash Communication Server, pass a NetStream object as source. (The same NetStream object can contain both audio and video information. To play back video from a NetStream object, use the Video.attachVideo() method.)

You don't have to use this method to play back incoming streamed audio; audio sent through a stream is played through the subscriber's standard audio output device by default when the subscriber issues NetStream.play(). However, if you use this method to route streaming audio to a movie clip, you can then create a Sound object to control some aspects of the sound.

Example

The following code attaches a microphone to a movie clip.

my_mic = Microphone.get();
this.attachAudio(my_mic);

The following example shows how you can use a Sound object to control the sound associated with a stream being displayed in a Video object.

// Clip_mc is the instance name of the movie clip
// that contains the video object "my_video".
_root.Clip_mc.my_video.attachVideo(_root.my_ns);
_root.Clip_mc.attachAudio(_root.my_ns);
var my_sound:Sound = new Sound("_root.Clip_mc");
//To adjust the audio:
_root.my_sound.setVolume(100);

See also

Microphone class, NetStream class, NetStream.attachAudio(), Sound class in ActionScript Dictionary Help


The NetConnection class

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Note: In Flash Player 7 and later, you can use this class to open a connection and play FLV files without Flash Communication Server. .For more information, see the Netconnection class entry in ActionScript Dictionary Help.

The NetConnection class manages a bidirectional connection between Flash Player and a server, which lets you connect to Flash Remoting or to Flash Communication Server. Flash Communication Server enables you to share audio, video, and data using the Macromedia Real-Time Messaging Protocol (RTMP).

For information on using Flash with an application server, see Using Flash Remoting. For information on using Flash with Flash Communication Server, see the following entries in addition to NetConnection:

  • NetStream class—for any RTMP communication
  • Camera class—for capturing and transmitting video
  • Microphone class—for capturing and transmitting audio
  • SharedObject class—for sharing data
  • Video class—for displaying video

For information on creating a NetConnection object, see Constructor for the NetConnection class.

Method summary for the NetConnection class

Method | Description
NetConnection.call() | Invokes a command or method on the server.
NetConnection.close() | Closes the connection with the server.
NetConnection.connect() | Connects to an application on the Flash Communication Server.

Property summary for the NetConnection class

Property (read-only) | Description
NetConnection.isConnected | A Boolean value that indicates whether Flash Player is connected to the server (true) or not (false) through the specified connection.
NetConnection.uri | The target URI that was passed in with NetConnection.connect().

Event handler summary for the NetConnection class

Method | Description
NetConnection.onStatus | Invoked when a status change or error is posted for the NetConnection object.

Constructor for the NetConnection class

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

new NetConnection()

Parameters

None.

Returns

A NetConnection object.

Description

Constructor; creates an object that can be used to connect Flash Player to the Flash Communication Server or to an application server. After creating the NetConnection object, use NetConnection.connect() to make the actual connection.

For information on using Flash with an application server, see Using Flash Remoting.

Example

The following doConnect() function uses the NetConnection constructor to create a new connection and connect to the server.

function doConnect() {

  // Make a new connection object
  var my_nc:NetConnection = new NetConnection();

  // Get the name of the server from user input
  // and assign it to a variable named myURL
  var myURL_str:String = serverName;

  // Connect to the service
  my_nc.connect("rtmp://" + myURL_str + "/someApp/someInstance");
}

See also

NetConnection.connect()


NetConnection.call()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_nc.call(remoteMethod, resultObject | null [, p1,...,pN])

Parameters

remoteMethod A parameter in the form [/objectPath/]method; if you are calling a method on a NetConnection object, you can omit objectPath. For example, the parameter /someObj/doSomething means the server must call the someObj.doSomething method of the application passed to NetConnection.connect() in its targetURI parameter, passing the specified p1,...,pN parameters.

For security reasons, certain remoteMethod names are reserved at the application level; do not call these method names with the NetConnection.call method(). The reserved names are /onConnect, /onDisconnect, /onStatus, /onAppStop, and /onAppStart.

resultObject An object parameter that is needed only when the sender is expecting a result. The result object can be any user-defined object. For it to be of use, a handler named onResult must be called when the result arrives. If you don't need a result object, pass null.

p1,...pN Optional parameters to be passed to the specified method.

Returns

Nothing.

Description

Method; invokes a command or method on the server. You must create a server-side function to define this method. This method is also used when your application connects to an application server. For information on using Flash with an application server, see Using Flash Remoting.

Example

The following function checks for a message, sends it, then clears the local string.

function mySend(){
  if (length(msg) > 0) {
    my_nc.call("message", null, msg);
  }
  msg = "";
}


NetConnection.close()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_nc.close()

Parameters

None.

Returns

Nothing.

Description

Method; closes the connection with the server and invokes NetConnection.onStatus with a code property of NetConnection.Connect.Close. For more information, see NetConnection.onStatus.

This method disconnects all NetStream objects running over this connection; any queued data that has not been sent is discarded. (To terminate server streams without closing the connection, use NetStream.close().) If you want to reconnect, you must recreate the NetStream object (see Constructor for the NetStream class).

This method also disconnects all remote shared objects running over this connection. However, you don't need to recreate the shared object to reconnect. Instead, you can just call SharedObject.connect() to reestablish the connection to the shared object. Also, any data in the shared object that was queued when you issued NetConnection.close() will be sent after you reestablish a connection to the shared object.

Example

The following disconnect() function stops the published stream, then calls NetConnection.close() to delete the source connection. With no source stream to play, the destination stream automatically ends and is deleted.

function disconnect() {

  // Stops publishing the stream.
  srcStream_ns.close();

  // Deletes the source stream connection.
  my_nc.close();
}

See also

NetConnection.connect(), NetConnection.onStatus, NetStream.close(), SharedObject.connect()


NetConnection.connect()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_nc.connect(targetURI, [, p1 ... pN])

Parameters

targetURI The Uniform Resource Identifier (URI) of the application on the Flash Communication Server that runs when the connection is made. For targetURI, use the following general format (items in brackets are optional):

protocol:[//host][:port]/appname/[instanceName]

For protocol, specify either rtmp or rtmpt. If rtmp is specified, Flash Player will create a persistent socket connection with Flash Communication Server. If rtmpt is specified, Flash Player will create an HTTP "tunneling" connection to the server. For more information on RTMP and RTMPT, see the description section below.

You can omit the host parameter if the SWF file is served from the same host where Flash Communication Server is installed.

If the instanceName parameter is omitted, Flash Player connects to the application's default instance (_definst_).

By default, RTMP connections use port 1935, and RTMPT connections use port 80.

For example, the following URIs are formatted correctly:

  • rtmp://www.myCompany.com/myMainDirectory/groupChatApp/HelpDesk
  • rtmpt:/sharedWhiteboardApp/June2002
  • rtmp::1234/chatApp/room_name

p1 ... pN Optional parameters of any type to be passed to the application specified in targetURI. If the application is unable to process the parameters in the order in which they are received, NetConnection.onStatus is invoked with the code property set to NetConnection.Connect.Rejected.

Returns

A Boolean value of true if you passed in a valid URI, false otherwise. (To determine if the connection was successfully completed, use NetConnection.onStatus.)

Description

Method; connects to an application on the Flash Communication Server. This method can also be used to communicate with an application server. For information, see Using Flash Remoting.

In general, use the RTMP protocol, which opens a persistent connection between Flash Player and Flash Communication Server. If, however, clients are connecting from behind a firewall or through HTTP proxy servers that prohibit direct RTMP socket connections, use the RTMPT protocol, which transmits RTMP data over an HTTP connection. The RTMPT protocol explicitly requests an HTTP connection and enables a faster connection time for clients who can't connect through RTMP.

If Flash Player fails to connect to the server over an RTMP connection on the default port, it will automatically try to establish a connection using a predetermined sequence of ports and protocols. For example, if an application tries and fails to connect using my_nc.connect("rtmp:/myserver/myapp"), Flash Player will automatically try the following sequence of connections, until successful:

my_nc.connect("rtmp://myserver:443/myapp");
my_nc.connect("rtmp://myserver:80/myapp");
my_nc.connect("rtmpt://myserver:80/myapp");

This connection sequence can enable connections to succeed that otherwise would not. However, during this connection sequence users may wait several seconds for multiple connection attempts to time out.

Note: This automatic retry sequence will occur only if the initial connection specifies the RTMP protocol and uses the default port—for example, my_nc.connect("rtmp:/myserver/myapp").

If you want to use this connection for publishing or playing audio or video in real time, or to publish or play previously recorded audio or video streams, you must connect to the Flash Communication Server and then create a NetStream object within this NetConnection object. For more information, see the NetStream class entry.

If you want to use this connection for synchronizing data among multiple clients or between the client and a server, you must connect to the Flash Communication Server and then create a remote shared object within this NetConnection object. For more information, see the SharedObject class entry.

When you call this method, the NetConnection.onStatus event handler is invoked with an information object that specifies whether the connection succeeded or failed. For more information, see NetConnection.onStatus. If the connection is successful, NetConnection.isConnected is set to true.

Because of network and thread timing issues, it is better to place a NetConnection.onStatus handler in a script before a NetConnection.connect() method. Otherwise, the connection might complete before the script executes the onStatus handler initialization. Also, all security checks are made within the NetConnection.connect() method, and notifications will be lost if the onStatus handler is not yet set up.

If the specified connection is already open when you call this method, an implicit NetConnection.close() method is invoked, and then the connection is reopened.

During the connection process, any server responses to subsequent NetConnection.call(), NetStream.send(), or SharedObject.send() methods are queued until the server authenticates the connection and NetConnection.onStatus is invoked. The call or send methods are then processed in the order received. Any pending updates to remote shared objects are also queued until the connection is successful, at which point they are transmitted to the server.

Video and audio, however, are not queued during the connection process. Any video or audio that is streaming from the server is ignored until the connection is successfully completed. For example, confirm that the connection was successful before enabling a button that calls the NetStream.publish() method.

If your connection fails, make sure you have met all the requirements for connecting successfully:

  • You are specifying the correct protocol name for connecting to the server (rtmp, or rtmpt, for the Flash Communication Server).
  • You are connecting to a valid application on the correct server.
  • You have a subdirectory in the Flash Communication Server applications directory with the same name as the application specified in the connection URL.
  • The server is running.

To distinguish among different instances of a single application, pass a value for instanceName as part of targetURI. For example, you may want to give different groups of people access to the same application without having them interact with each other. To do so, you can open multiple chat rooms at the same time, as shown below.

my_nc.connect("rtmp://www.myserver.com/chatApp/peopleWhoSew")
my_nc.connect("rtmp://www.myserver.com/chatApp/peopleWhoKnit")

In another case, you may have an application named lectureSeries that records and plays back classroom lectures. To save individual lectures, pass a different value for instanceName each time you record a lecture, as shown below.

// Record Monday's lecture
my_nc.connect("rtmp://www.myserver.com/lectureSeries/Monday");
// Later ...
my_ns.connect(my_nc);
my_ns.publish("lecture", "record");

// Record Tuesday's lecture
my_nc.connect("rtmp://www.myserver.com/lectureSeries/Tuesday");
// Later ...
my_ns.connect(my_nc);
my_ns.publish("lecture", "record");
// and so on

// Play back one of the lectures
my_nc.connect("rtmp://www.myserver.com/lectureSeries/Monday");
// Later ...
my_ns.connect(my_nc);
my_ns.play("lecture")

You can also nest instance names, as shown below.

my_nc.connect("rtmp://www.myserver.com/chatApp/peopleWhoSew/Monday")
my_nc.connect("rtmp://www.myserver.com/chatApp/peopleWhoSew/Tuesday")

For information on where recorded streams are stored on the server, see NetStream.publish().

Understanding file naming and domains used with this method If an HTML page containing a SWF file is accessed differently (with regards to domain names) from the way the SWF file itself accesses the Flash Communication Server, then the connection will not be successful. This is a security feature of Flash Player. But in some cases, this may be inconvenient.

For example, if a web page containing a SWF file is served on an intranet from, say, http://deptserver.mycorp.com, it can also be accessed simply by http://deptserver. If the page is accessed via, say, http://deptServer/tcpage.htm, but the SWF file specifies deptServer.mycorp.com in targetURI, then the SWF file will not make a successful connection to the server. Similarly, if the web page and SWF file are accessed as http://deptserver.mycorp.com/tcpage.htm, but the SWF file specifies rtmp://deptserver in targetURI, it will not connect.

There are a few things you can do to prevent the security policies from inconveniencing you or your users. The first, and easiest, is to use a target URI that doesn't specify a server name. (This is applicable only if the Flash Communication Server and web server are running from the same IP address.) To do so, leave off the second slash in the targetURI parameter. For example, the following commands will make Flash Player attempt to connect to the same host and domain as the web server the SWF file was served from.

my_nc = new NetConnection();
my_nc.connect("rtmp:/myApp");

Second, there is a bit of JavaScript you can use in your HTML page to avoid the security problem. Assuming the SWF file uses a fully qualified domain name URL to access the Flash Communication Server, this JavaScript redirects the web page to an explicitly named full URL, like this:

<SCRIPT language="javascript">
//if the URL didn't have the domain on it
if (document.URL.indexOf("mycorp.com") == -1) {
    //redirect to a version that does
    document.URL="http://deptServer.mycorp.com/tcpage.htm";
}
</script>

Finally, if you own a domain name, have access to the DNS records of that domain name, and have a static IP address for your Flash Communication Server, you can create address ("A") records to point a host name to that IP address. For instance, flashcom.mycorp.com could map to the machine running the Flash Communication Server and having an IP address provided by your IT department or ISP. Your web pages can continue to be hosted by whatever means you are currently using. ("CNAME" records are recommended if you need to forward traffic to a server that has a DNS-accessible host name but may or may not have a static IP address.)

Example

The following example connects over the RTMP protocol to the default instance of the funAndGames application located on the real host of the macromedia server using the default port.

my_nc = new NetConnection();
my_nc.connect("rtmp://real.macromedia.com/funAndGames");

The following example connects over the RTMPT protocol to the room_01 application instance of the chat application using the default port. In this example, the Flash SWF file is served from the same host and domain as Flash Communication Server, so the host parameter is omitted.

my_nc = new NetConnection();
my_nc.connect("rtmpt:/chat/room_01");

See also

NetConnection.close(), NetConnection.onStatus


NetConnection.isConnected

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_nc.isConnected

Description

Read-only property; a Boolean value indicating whether Flash Player is connected to the server (true) or not (false) through the specified connection. Whenever a connection is made or closed, this property is set.

Example

The following example is attached to a toggle push button. When the user clicks the button, if the user is connected to the server, the connection is closed. If the user is not connected, a connection is established.

on (release) {
  if (_root.my_nc.isConnected == true)
    _root.my_nc.close();
  else
    _root.my_nc.connect(_root.myURI);
}

See also

NetConnection.close(), NetConnection.connect(), NetConnection.onStatus


NetConnection.onStatus

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_nc.onStatus = function(infoObject) {
  // Your code here
}

Parameters

infoObject A parameter defined according to the status message. For more information about this parameter, see NetConnection information objects.

Returns

Nothing.

Description

Event handler; invoked when a status change or error is posted for the NetConnection object. If you want to respond to this event handler, you must create a function to process the information object sent by the server. For more information, see Client-Side Information Objects.

Example

The following example writes data about the connection to a log file.

reconnection_nc.onStatus = function(info){
  _root.log += "Recording stream status.\n";
  _root.log += "Event: " + info.code + "\n";
  _root.log += "Type: " + info.level + "\n";
  _root.log += "Message:" + info.description + "\n";
}

See also

NetConnection.call(), NetConnection.close(), NetConnection.connect()


NetConnection.uri

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_nc.uri

Description

Read-only property; a string representing the target URI that was passed in with NetConnection.connect(). If NetConnection.connect() hasn't yet been called for my_nc, this property is undefined.

See also

NetConnection.connect()


The NetStream class

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Note: In Flash Player 7 and later, you can use this method to play FLV files without Flash Communication Server. .For more information, see the NetStream class entry in ActionScript Dictionary Help.

The NetStream class opens a one-way streaming connection between Flash Player and Flash Communication Server through a connection made available by a NetConnection object. A NetStream object is like a channel inside a NetConnection object; this channel can either publish audio and/or video data, using NetStream.publish(), or subscribe to a published stream and receive data, using NetStream.play(). You can publish or play live (real-time) data and play previously recorded data.

You can also use NetStream objects to send text messages to all subscribed clients (see NetStream.send()).

The following steps summarize the sequence of actions required for publishing real-time audio and video using Flash Communication Server and the Real-Time Messaging Protocol (RTMP):

  1. Use new NetConnection to create a NetConnection object.
  2. Use NetConnection.connect("rtmp://serverName/appName/appInstanceName") to connect the application instance to the Flash Communication Server.
  3. Use new NetStream(connection) to create a data stream over the connection.
  4. Use NetStream.attachAudio(audioSource) to capture and send audio over the stream, and NetStream.attachVideo(videoSource) to capture and send video over the stream.
  5. Use NetStream.publish(publishName) to give this stream a unique name and send data over the stream to the Flash Communication Server, so others can receive it. You can also record the data as you publish it, so that users can play it back later.

    SWF files that subscribe to this stream will use the name specified here; that is, they will call the same NetConnection.connect() method as the publisher, and then call a NetStream.play(publishName) method. They will also have to call Video.attachVideo() to display the video.

Multiple streams can be open simultaneously over one connection, but each stream either publishes or plays. To publish and play over a single connection, open two streams over the connection, as shown in the following example. This example publishes audio and video data in real time on one stream and plays it back on another stream on the same client, through the same connection.

// These lines begin broadcasting
var my_nc:NetConnection = new NetConnection(); // create connection object
my_nc.connect("rtmp://mySvr.myDomain.com/App"); // connect to server
publish_ns = new NetStream(my_nc);   // open stream within connection
publish_ns.attachAudio(Microphone.get());   // capture audio
publish_ns.attachVideo(Camera.get());       // capture video
publish_ns.publish("todays_news");          // begin broadcasting

// These lines open a stream to play the video portion of the broadcast
// inside a Video object named my_video.
// The audio is played through the standard output device--you don't
// need to issue a separate command to hear the audio.
var play_ns:NetStream = new NetStream(my_nc);
my_video.attachVideo(play_ns); // specify where to display video
play_ns.play("todays_news"); // play uses the same name as publish, above

In the previous example, note that both the publisher and subscriber call an attachVideo method. The publisher calls NetStream.attachVideo() to connect a video feed to a stream. The subscriber calls Video.attachVideo() to connect a video feed to a Video object on the Stage; the incoming video is displayed inside this object.

Note also that although the publisher calls an attachAudio method, the subscriber does not. This is because audio sent through a stream is played through the subscriber's standard audio output device by default; the subscriber doesn't have to attach the incoming audio to an object on the Stage. However, you can use MovieClip.attachAudio() to route audio from a NetStream object to a movie clip. If you do this, you can then create a Sound object to control the volume of the sound. For more information, see MovieClip.attachAudio().

Method summary for the NetStream class

Method | Description
NetStream.attachAudio() | Publisher method; specifies whether audio should be sent over the stream.
NetStream.attachVideo() | Publisher method; starts transmitting video or a snapshot from the specified source.
NetStream.close() | Stops publishing or playing all data on the stream and makes the stream available for another use.
NetStream.pause() | Subscriber method; pauses or resumes playback of a stream.
NetStream.play() | Subscriber method; feeds streaming audio, video, and text messages being published on the Flash Communication Server, or a recorded file stored on the server, to the client.
NetStream.publish() | Publisher method; sends streaming audio, video, and text messages from the client to the Flash Communication Server, optionally recording the stream during transmission.
NetStream.receiveAudio() | Subscriber method; specifies whether incoming audio plays on the stream.
NetStream.receiveVideo() | Subscriber method; specifies whether incoming video will play on the stream, or specifies the frame rate of the video.
NetStream.seek() | Subscriber method; seeks to a position in the recorded stream currently playing.
NetStream.send() | Publisher method; broadcasts a message to all subscribing clients.
NetStream.setBufferTime() | Method; for a publishing stream, this number indicates how long the outgoing buffer can grow before Flash starts dropping frames. For a subscribing stream, this number indicates how long to buffer incoming data before starting to display the stream.

Property summary for the NetStream class

Property (read-only) | Description
NetStream.bufferLength | The number of seconds of data currently in the buffer.
NetStream.bufferTime | The number of seconds assigned to the buffer by NetStream.setBufferTime().
NetStream.currentFps | The number of frames per second being sent or received on the publishing or subscribing stream.
NetStream.liveDelay | The number of seconds of data in a subscribing stream's buffer in live mode.
NetStream.time | The number of seconds a stream has been playing or publishing.

Event handler summary for the NetStream class

Method | Description
NetStream.onStatus | Invoked every time a status change or error is posted for the NetStream object.

Constructor for the NetStream class

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

new NetStream(myRTMPConnection)

Parameters

myRTMPConnection A NetConnection object that is using the Real-Time Messaging Protocol (RTMP) to communicate with the Flash Communication Server.

Returns

A NetStream object.

Description

Constructor; creates a stream that can be used for publishing (sending) or playing (receiving) data through the specified server connection.

You can't publish and play data over the same stream at the same time. For example, if you are publishing on a stream and then call NetStream.play(), an implicit NetStream.close() method is called; the publishing stream then becomes a subscribing stream.

However, you can create multiple streams that run simultaneously over the same connection: one stream publishes and another stream plays.

Example

The following example shows how a publishing client and a subscribing client can connect to the Flash Communication Server and then open an application stream for sending (publishing) or receiving (playing) data over this connection.

// Publishing client contains this code.
my_nc = new NetConnection();         // create NetConnection object
my_nc.connect("rtmp://myRTMPServer.myDomain.com/app"); // connect to server

my_ns = new NetStream(my_nc);     // open app stream within my_nc
my_ns.publish("myWeddingVideo");       // publish data over this stream

// Subscribing client contains this code.
// Note that the connection and stream names are the same as those
// used by the publishing client. This is neither required nor prohibited,
// because the scripts are running on different machines.
// However, the parameters used with connect() and play() below
// must be the same as those used with connect() and publish() above.
my_nc = new NetConnection();
my_nc.connect("rtmp://myRTMPServer.myDomain.com/app");

my_ns = new NetStream(my_nc);
my_ns.play("myWeddingVideo");

For more examples, see the NetStream class entry and Video.attachVideo().

See also

NetConnection class, NetStream.attachAudio(), NetStream.attachVideo(), NetStream.play(), NetStream.publish(), Video.attachVideo()


NetStream.attachAudio()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.attachAudio(source)

Parameters

source The source of the audio to be transmitted. Valid values are a Microphone object and null.

Returns

Nothing.

Description

Method; specifies whether audio should be sent over the stream (from a Microphone object passed as source) or not (null passed as source). This method is available only to the publisher of the specified stream.

You can call this method before or after you call the NetStream.publish() method and actually begin transmitting. Subscribers who want to hear the audio must call a NetStream.play() method.

Subscribers can also attach their incoming audio to a movie clip and then create a Sound object to control some aspects of the sound. For more information, see MovieClip.attachAudio().

Example

The following code attaches a microphone to a network stream.

my_ns.attachAudio(active_mic);

See also

Microphone class, MovieClip.attachAudio(), NetStream.attachVideo(), NetStream.publish(), NetStream.receiveAudio()


NetStream.attachVideo()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.attachVideo(source | null [, snapShotMilliseconds])

Parameters

source The source of the video transmission. Valid values are a Camera object (which starts capturing video) and null. If you pass null, Flash stops capturing video, and any additional parameters you send are ignored.

snapShotMilliseconds An optional integer that specifies whether the video stream is continuous, a single frame, or a series of single frames used to create time-lapse photography.

  • If this parameter is omitted, Flash captures all video until you issue my_ns.attachVideo(null).
  • If you pass 0, Flash captures only a single video frame. Use this value to transmit "snapshots" within a preexisting stream.

    Note: Flash interprets invalid, negative, or nonnumeric arguments as 0.

  • If you pass a positive number, Flash captures a single video frame and then appends a pause of length snapShotMilliseconds as a "trailer" on the snapshot. Use this value to create time-lapse photography effects (see "Description," below).

Returns

Nothing.

Description

Method; starts capturing video from the specified source, or stops capturing if source is null. This method is available only to the publisher of the specified stream.

After attaching the video source, you must call NetStream.publish() to actually begin transmitting. Subscribers who want to display the video must call the NetStream.play() and Video.attachVideo() methods to display the video on the Stage.

You can use snapShotMilliseconds to send a single snapshot (by providing a value of 0) or a series of snapshots—in effect, time-lapse footage—by providing a positive number that adds a trailer of the specified number of milliseconds to the video feed. The trailer extends the length of time the video message is displayed. By repeatedly calling attachVideo with a positive value for snapShotMilliseconds, the snapshot/trailer/snapshot/trailer... sequence creates time-lapse footage. For example, you could capture one frame per day and append it to a video file. When a subscriber plays back the file, each frame remains onscreen for the specified number of milliseconds and then the next frame is displayed.

The snapShotMilliseconds parameter serves a different purpose from the fps parameter you can set with Camera.setMode(). When you specify snapShotMilliseconds, you are controlling how much time elapses during playback between recorded frames. When you specify fps using Camera.setMode(), you are controlling how much time elapses during recording and playback between recorded frames.

For example, suppose you want to take a snapshot every 5 minutes for a total of 100 snapshots. You can do this in two different ways:

  • You can issue a NetStream.attachVideo(source, 500) command 100 times, once every 5 minutes. This takes 500 minutes to record, but the resulting file will play back in 50 seconds (100 frames with 500 milliseconds between frames).
  • You can issue a Camera.setMode() command with an fps value of 1/300 (one per 300 seconds, or one every 5 minutes), and then issue a NetStream.attachVideo(source) command, letting the camera capture continuously for 500 minutes. The resulting file will play back in 500 minutes—the same length of time that it took to record—with each frame being displayed for 5 minutes.

Both techniques capture the same 500 frames, and both approaches are useful; which approach to use depends primarily on your playback requirements. For example, in the second case, you could be recording audio the entire time. Also, both files would be approximately the same size.

Example

The following function publishes a stream on a NetConnection named my_nc containing the camera output from active_cam.

function pubLive() {

  // Create a new source stream.
  var source_ns:NetStream = new NetStream(my_nc);

  // Attach the camera activity to the source stream. This
  // call causes a warning message to show which service is
  // requesting access. It also gives the user the option of
  // not sending the camera activity to the server.
  source_ns.attachVideo(active_cam);

  // Get the stream name from the user input.
  var mySubj:String = subject;

  // Assuming the user named the stream 'webCamStream',
  // publish the live camera activity as 'webCamStream'.
  source_ns.publish(mySubj, "live");
}

See also the example for MovieClip.attachAudio().

See also

Camera class, Camera.setMode(), NetStream.publish(), NetStream.receiveVideo(), Video.attachVideo()


NetStream.bufferLength

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.bufferLength

Description

Read-only property; the number of seconds of data currently in the buffer. You can use this property in conjunction with NetStream.bufferTime to estimate how close the buffer is to being full—for example, to display feedback to a user who is waiting for data to be loaded into the buffer.

See also

NetStream.bufferTime


NetStream.bufferTime

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.bufferTime

Description

Read-only property; the number of seconds assigned to the buffer by NetStream.setBufferTime(). The default value is 9. To determine the number of seconds currently in the buffer, use NetStream.bufferLength.

See also

NetStream.bufferLength, NetStream.setBufferTime()


NetStream.close()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.close()

Parameters

None.

Returns

Nothing.

Description

Method; stops publishing or playing all data on the stream, sets the NetStream.time property to 0, and makes the stream available for another use. This method is invoked implicitly whenever you call NetStream.play() from a publishing stream, or NetStream.publish() from a subscribing stream.

  • If this method is called from a publishing stream, all pending NetStream.play() calls on the stream are cleared on the server; subscribers no longer receive anything that was being published on the stream.
  • If this method is called from a subscribing stream, publishing continues and other subscribing streams may still be playing, but the subscriber can now use the stream for another purpose.
  • To stop play on a subscribing stream without closing the stream or changing the stream type, use my_ns.play(false).

Example

The following onDisconnect() function closes a stream.

function onDisconnect() {

  // Stops publishing the stream.
  srcStream_ns.close();

  // Deletes the source stream connection. With no source
  // to play, the destination stream also ends and can be
  // deleted.
  my_nc.close();
}

See also

NetStream.pause(), NetStream.play(), NetStream.publish(), NetStream.time


NetStream.currentFps

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.currentFps

Description

Read-only property; the number of frames per second being sent or received on the specified publishing or subscribing stream.


NetStream.liveDelay

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.liveDelay

Description

Read-only property; the number of seconds of data in the specified subscribing stream's buffer in live (unbuffered) mode. This property indicates the current network transmission delay (lag time).

Example

The following example displays a string (inside a text field named connectionQuality_str) indicating the connection quality over the NetStream object named my_ns, according to the value of the liveDelay property.

if (my_ns.liveDelay < .5) {
  connectionQuality_str.text = "Good";
} else if (my_ns.liveDelay < 1) {
  connectionQuality_str.text = "Slow";
} else {
  connectionQuality_str.text = "Network congested";
}


NetStream.onStatus

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.onStatus = function(infoObject) {
  // Your code here
}

Parameters

infoObject A parameter defined according to the status or error message. For more information about this parameter, see NetStream information objects.

Returns

Nothing.

Description

Event handler; invoked every time a status change or error is posted for the NetStream object. If you want to respond to this event handler, you must create a function to process the information object sent by the server. For more information, see Client-Side Information Objects.


NetStream.pause()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.pause( [ pauseResume ] )

Parameters

pauseResume Optional: a Boolean value specifying whether to pause play (true) or resume play (false). If you omit this parameter, NetStream.pause() acts as a toggle: the first time it is called on a specified stream, it pauses play, and the next time it is called, it resumes play.

Returns

Nothing.

Description

Method; pauses or resumes playback of a stream. This method is available only to clients subscribed to the specified stream, not to the stream's publisher.

The first time you call this method on a given playlist (without sending a parameter), it pauses the playlist; the next time, it resumes play. You might want to attach this method to a button that the user presses to pause or resume playback.

Example

The following examples illustrate some uses of this method.

my_ns.pause(); // pauses play first time issued
my_ns.pause(); // resumes play
my_ns.pause(false); // no effect, play continues
my_ns.pause(); // pauses play

In the following example, suppose you have a playlist of three recorded streams.

var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://localhost/appName/appInstance");

// Create a NetStream for playing back in a Video object named my_video
var my_ns:NetStream = new NetStream(my_nc);
my_video.attachVideo(my_ns);

// To play record1
my_ns.play("record1", 0, -1, false);

// To play record2
my_ns.play("record2", 0, -1, false);

// To play record3
my_ns.play("record3", 0, -1, false);

// You click a button to pause while record2 is playing
my_ns.pause();

// Later, you want to resume the play
my_ns.pause();

// Later, you want to start a new playlist

// To play record4
my_ns.play("record4", 0, -1, true);

// To play record5
my_ns.play("record5", 0, -1, false);

// To play record6
my_ns.play("record6", 0, -1, false);

See also

NetStream.close() , NetStream.play()


NetStream.play()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.play(whatToPlay | false [,start [, length [, flushPlaylists]]])

Parameters

whatToPlay An identifying name for live data published by NetStream.publish(), a recorded file name for playback, or false. If you pass false, the stream stops playing and any additional parameters you send are ignored.

To play back FLV files, the default Flash file format for recorded streams, specify the name of the stream without a file extension (for example, "bolero"). To play back MP3 files that you've stored on the server or the ID3 tags of MP3 files, you must precede the stream name with mp3: or id3:, for example, "mp3:bolero" or "id3:bolero". For more information on playing MP3 files, see Developing Communication Applications Help.

start An optional numeric parameter that specifies the start time, in seconds. This parameter can also be used to indicate whether the stream is live or recorded.

  • The default value for start is -2, which means that Flash first tries to play the live stream specified in whatToPlay. If a live stream of that name is not found, Flash plays the recorded stream specified in whatToPlay. If neither a live nor a recorded stream is found, Flash opens a live stream named whatToPlay even though no one is publishing on it; when someone does begin publishing on that stream, Flash begins playing it.
  • If you pass -1 for start, Flash plays only the live stream specified in whatToPlay. If no live stream is found, Flash waits for it indefinitely if length is set to -1; if length is set to a different value, Flash waits for length seconds before it begins playing the next item in the playlist.
  • If you pass 0 or a positive number for start, Flash plays only a recorded stream named whatToPlay, beginning start seconds from the beginning of the stream. If no recorded stream is found, Flash begins playing the next item in the playlist immediately.
  • If you pass a negative number other than -1 or -2 for start, Flash interprets the value as if it were -2.

length An optional numeric parameter that specifies the duration of the playback, in seconds.

  • The default value for length is -1, which means that Flash plays a live stream until it is no longer available or plays a recorded stream until it ends.
  • If you pass 0 for length, Flash plays the single frame that is start seconds from the beginning of a recorded stream (assuming start is equal to or greater than 0).
  • If you pass a positive number for length, Flash plays a live stream for length seconds after it becomes available, or plays a recorded stream for length seconds. (If a stream ends before length seconds, playback ends when the stream ends.)
  • If you pass a negative number other than -1 for length, Flash interprets the value as if it were -1.

flushPlaylists An optional Boolean value or number that specifies whether to flush any previous playlist. If flushPlaylists is false (0), whatToPlay is added (queued) in the current playlist; that is, whatToPlay plays only after previous streams finish playing. You can use this technique to create a dynamic playlist. If flushPlaylists is true (1), any previous play calls are cleared and whatToPlay is played immediately. By default, the value is true.

You can also specify a value of 2 or 3 for the flushPlaylists parameter, which is useful when playing recorded stream files that contain message data. These values are analogous to passing false (0) and true (1), respectively: a value of 2 maintains a playlist, and a value of 3 resets the playlist. However, the difference is that specifying 2 or 3 for flushPlaylists causes Flash Communication Server to return all messages in the recorded stream file at once, rather than at the intervals which the messages were originally recorded (the default behavior).

This is especially useful for accessing log files recorded by Flash Communication Server. For more information on Flash Communication Server logging, see TechNote 16464.

Description

Method; feeds streaming audio, video, and text messages being published on the Flash Communication Server, or a recorded file stored on the server, to the client. This method is available only to clients subscribed to the specified stream, not to the stream's publisher.

To view video data, you must call Video.attachVideo(); audio being streamed with the video will be played automatically. If audio-only data is being streamed, you can use MovieClip.attachAudio() to route streaming audio to a movie clip and then create a Sound object to control some aspects of the audio.

You can use the optional parameters of this method to control various aspects of playback behavior. The following table shows a few ways in which these values interact.

start | length | Flash Player behavior
(Default) | (Default) | Plays the live stream until it is no longer available. If a live stream of the specified name is not found, Flash Player plays a recorded stream until it ends.
-2 | 19 | Plays a live stream for up to 19 seconds after it becomes available. If a live stream of the specified name is not found, Flash Player plays a recorded stream for 19 seconds.
15 | 19 | Plays a recorded stream for 19 seconds, beginning 15 seconds from the beginning of the stream.
15 | (Default) | Plays a recorded stream, beginning 15 seconds from the beginning of the stream, until the stream ends.
-1 | (Default) | Plays a live stream until it is no longer available.

This method can invoke NetStream.onStatus with a number of different information objects. For example, if the specified stream isn't found, NetStream.onStatus is called with a code property of NetStream.Play.StreamNotFound. For more information, see NetStream.onStatus.

If you want to create a dynamic playlist that switches among different live or recorded streams, call play more than once and pass false for flushPlaylists each time. Conversely, if you want to play the specified stream immediately, clearing any other streams that are queued for play, pass true for flushPlaylists.

Example

The following examples show some ways to use this method to play back live or recorded streams.

Example 1:

var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://localhost/appName/appInstance");

var my_ns:NetStream = new NetStream(my_nc);
my_video.attachVideo(my_ns);

// To play a live stream named "stephen" being published elsewhere
// using the default values -- start time is -2, length is -1,
// and flushPlaylists is true -- don't pass any optional parameters.
my_ns.play("stephen");

// To immediately play a recorded stream named record1
// starting at the beginning, for up to 100 seconds.
my_ns.play("record1", 0, 100, true);

Example 2:

// To play and switch between live and recorded streams:
// Suppose we have two live streams, live1 and live2,
// and three recorded streams, record1, record2, and record3.
// The play order is record1, live1, record2, live2, and record3.
var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://localhost/appName/appInstance");

// Create a NetStream for playing
var my_ns:NetStream = new NetStream(my_nc);
my_video.attachVideo(my_ns);

// Play record1
my_ns.play("record1", 0, -1, false);

// Switch from record1 to live1.
// live1 will start to play after record1 is done
my_ns.play("live1", -1, 5, false);

// Switch from live1 to record2.
// record2 will start to play after live1 plays for 5 seconds.
my_ns.play("record2", 0, -1, false);

// Interrupt the current play and play a segment in record1 again
// (we can implement a seek by this)
my_ns.play("record1", 1, 5, true);

In the following example, data messages in the recorded stream file log.flv are returned at the intervals at which they were originally recorded.

var my_ns:NetStream = new NetStream(my_nc);
my_ns.play("log", 0, -1);

In the following example, data messages in the recorded stream file log.flv are returned all at once, rather than at the intervals at which they were originally recorded.

var my_ns:NetStream = new NetStream(my_nc);
my_ns.play("log", 0, -1, 2);

See also

MovieClip.attachAudio(), NetStream.close(), NetStream.pause(), NetStream.publish()


NetStream.publish()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.publish(whatToPublish | false [, howToPublish ] )

Parameters

whatToPublish A string that identifies the stream. If you pass false, the publish operation stops. Subscribers to this stream must pass this same name when they call NetStream.play(). You don't need to include a file extension for the stream name.

howToPublish An optional string that specifies how to publish the stream. Valid values are "record", "append", and "live". The default value is "live".

  • If you pass "record" for howToPublish, Flash publishes and records live data, saving the recorded data to a new file named whatToPublish.flv. The file is stored on the server in a subdirectory within the directory containing the server application. If the file already exists, it is overwritten. For more information on where recorded streams are stored, see "Description," below.
  • If you pass "append" for howToPublish, Flash publishes and records live data, appending the recorded data to a file named whatToPublish.flv, stored on the server in a subdirectory within the directory containing the server application. If no file named whatToPublish.flv is found, it is created.
  • If you omit this parameter or pass "live", Flash publishes live data without recording it. If whatToPublish.flv exists, it will be deleted.

Returns

Nothing.

Description

Method; sends streaming audio, video, and text messages from the client to the Flash Communication Server, optionally recording the stream during transmission. This method is available only to the publisher of the specified stream.

You don't use this command when you want to let a subscriber play a stream that has already been published and recorded. For example, assume you have recorded a stream named "allAboutMe." To enable someone to play it back, you need only open a stream for the subscriber to use:

var publish_ns:NetStream = new NetStream(my_nc);
var subscribe_ns:NetStream = new NetStream(my_nc);
subscribe_ns.play("allAboutMe");

When you record a stream, Flash creates an FLV file and stores it in a subdirectory of the Flash Communication Server applications directory on the server. Each stream is stored in a directory whose name is the same as the instanceName value passed to NetConnection.connect(). Flash creates these directories automatically; you don't have to create one for each instance name. For example:

// Connect to a specific instance of an app that is stored in
// a directory named "lectureSeries" in your applications directory
// a file named "lecture.flv" is stored in a subdirectory named
// "...\yourAppsFolder\lectureSeries\streams\Monday"

var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://server.domain.com/lectureSeries/Monday");
var my_ns:NetStream = new NetStream(my_nc);
my_ns.publish("lecture", "record");

// Connect to a different instance of the same app
// but issue an identical publish command
// a file named "lecture.flv" is stored in a subdirectory named
// "...\yourAppsFolder\lectureSeries\streams\Tuesday"
var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://server.domain.com/lectureSeries/Tuesday");
var my_ns:NetStream = new NetStream(my_nc);
my_ns.publish("lecture", "record");

If you don't pass a value for instanceName, whatToPublish.flv is stored in a subdirectory named "...\yourAppsFolder\appName\streams\_definst_" (for "default instance"). For more information on using instance names, see NetConnection.connect(). For information on playing back FLV files, see NetStream.play().

This method can invoke NetStream.onStatus with a number of different information objects. For example, if someone is already publishing on a stream with the specified name, NetStream.onStatus is called with a code property of "NetStream.Publish.BadName". For more information, see NetStream.onStatus.

Example

The following example shows how to publish and record a video, and then play it back.

var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://myServer.myDomain.com/appName/appInstance");
var src_ns:NetStream = new NetStream(my_nc);
src_ns.publish("stephen", "record");
src_ns.attachVideo(Camera.get());

// To stop publishing and recording
src_ns.publish(false);

// To play the recorded stream
src_ns.play("stephen");

See also

NetConnection.connect(), NetStream.play(), Video.attachVideo()


NetStream.receiveAudio()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.receiveAudio(receive)

Parameters

receive A Boolean value that specifies whether incoming audio plays on the specified stream (true) or not (false). The default value is true.

Returns

Nothing.

Description

Method; specifies whether incoming audio plays on the specified stream. This method is available only to clients subscribed to the specified stream, not to the stream's publisher.

You can call this method before or after you call the NetStream.play() method and actually begin receiving the stream. For example, you can attach these methods to a button the user clicks to mute and unmute the incoming audio stream.

If the specified stream contains only audio data, then passing a value of false to this method stops NetStream.time from further incrementing.

See also

NetStream.receiveVideo(), NetStream.time


NetStream.receiveVideo()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.receiveVideo(receive | FPS)

Parameters

receive A Boolean value that specifies whether incoming video plays on the specified stream (true) or not (false). The default value is true.

FPS A number that specifies the frame rate per second of the incoming video. The default value is the frame rate of the SWF file.

Returns

Nothing.

Description

Method; specifies whether incoming video will play on the specified stream, or specifies the frame rate of the video. This method is available only to clients subscribed to the specified stream, not to the stream's publisher.

You can call this method before or after you call the NetStream.play() method and actually begin receiving the stream. For example, you can attach these methods to a button the user presses to show or hide the incoming video stream.

To stop receiving video, pass 0 for FPS. (This has the same effect as passing false.) To determine the current frame rate, use NetStream.currentFps.

If you call NetStream.receiveVideo with a frame rate after calling NetStream.receiveVideo(false), an implicit call to NetStream.receiveVideo(true) is issued.

If the specified stream contains only video data, then passing a value of false to this method stops NetStream.time from further incrementing.

Example

The following example opens a stream and specifies that the video play at a specified rate.

var my_ns:NetStream = new NetStream(my_nc);
my_ns.receiveVideo(false);   // don't display video being published
// Later....
my_ns.receiveVideo(12);      // display video at 12 FPS

See also

NetStream.currentFps, NetStream.receiveAudio(), NetStream.time


NetStream.seek()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

myRecordedStream_ns.seek(numberOfSeconds)

Parameters

numberOfSeconds The number of seconds to move forward or backward in a recorded stream or playlist.

  • To return to the beginning of the stream or playlist, pass 0 for numberOfSeconds.
  • To seek forward from the beginning of the stream or playlist, pass the number of seconds you want to advance. For example, to position the playhead at 15 seconds from the beginning, use myRecordedStream_ns.seek(15).
  • To seek relative to the current position, pass myRecordedStream_ns.time + n or myRecordedStream_ns.time - n to seek n seconds forward or backward, respectively, from the current position. For example, to rewind 20 seconds from the current position, use myRecordedStream_ns.seek(my_ns.time - 20).

Returns

Nothing.

Description

Method; seeks the specified number of seconds into the recorded stream that is currently playing, either from the beginning of the stream or from the current position. This method is available only to clients subscribed to the specified stream, not to the stream's publisher.

If you require an accurate return value from seeking, you may need to change the Application.xml file's "Enhanced seeking" flag at the server.

"Enhanced seeking" is a Boolean flag in the Application.xml file. By default, this flag is set to false. When a seek occurs, the server seeks to the closest video keyframe possible and starts from that keyframe. For example, if you want to seek to time 15, and there are keyframes only at time 11 and time 17, seeking actually starts from time 17 instead of time 15. This is an approximate seeking method that works well with compressed streams.

If the flag is set to true, some compression is invoked on the server. Using the example above, if the flag is set to true, then the server creates a keyframe—based on the preexisting keyframe at time 11—for each keyframe from 11 through 15. Even though a keyframe does not exist at the seek time, the server generates a keyframe. This, of course, involves some processing time on the server.

See also

NetStream.play(), NetStream.time


NetStream.send()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.send(handlerName [,p1, ...,pN])

Parameters

handlerName A string that identifies the message; also the name of the ActionScript handler to receive the message. The handler name can be only one level deep (that is, it can't be of the form parent/child) and is relative to the stream object.

Note: Do not use a reserved term for a handler name. For example, my_ns.send("close") will fail.

p1, ...,pN Optional parameters that can be of any type. They are serialized and sent over the connection, and the receiving handler receives them in the same order. If a parameter is a circular object (for example, a linked list that is circular), the serializer handles the references correctly.

Returns

Nothing.

Description

Method; broadcasts a message on the specified stream to all subscribing clients. This method is available only to the publisher of the specified stream.

To process and respond to the message, create a handler in the format my_ns.HandlerName.

Flash Player does not serialize methods or their data, object prototype variables, or non-enumerable variables. Also, for movie clips, Flash Player serializes the path but none of the data.

The sending client has the following script:

var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://myServer.myDomain.com/appName/appInstance");
var my_ns:NetStream = new NetStream(my_nc);
my_ns.publish("slav", "live");
my_ns.send("Fun", "this is a test");  //Fun is the handler name

The receiving client's script looks something like this:

var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://myServer.myDomain.com/appName");
my_ns = new NetStream(my_nc);
my_ns.play("slav", -1, -1);

my_ns.Fun = function(str) { //Fun is the handler name
    trace (str);
}


NetStream.setBufferTime()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.setBufferTime(numberOfSeconds)

Parameters

numberOfSeconds The number of seconds to be buffered before Flash stops sending data (on a publishing stream) or begins displaying data (on a subscribing stream). The default value is 9.

Description

Method; behavior depends on whether this method is called on a publishing or a subscribing stream.

  • For a publishing stream, this method specifies how long the outgoing buffer can grow before Flash starts dropping frames. On a high-speed connection, buffer time shouldn't be a concern; data will be sent almost as quickly as Flash can buffer it. On a slow connection, however, there might be a significant difference between how fast Flash buffers the data and how fast it can be sent to the client.

    For example, suppose you set numberOfSeconds to 30, but after 30 seconds, only 5 seconds of data have been sent over the connection. Flash may stop sending data to the buffer until more data has been sent to the client. The client will receive the initial 30 seconds that were buffered but might lose some intervening frames before the next set of buffered data is displayed.

  • For a subscribing stream, this method specifies how long to buffer incoming data before starting to display the stream. For example, if you want to make sure that the first 15 seconds of the stream play without interruption, set numberOfSeconds to 15; Flash will begin playing the stream only after 15 seconds of data have been buffered.

    When a recorded stream is played, if numberOfSeconds is zero, Flash sets it to a small value (approximately 10 milliseconds). If live streams are later played (for example, from a playlist), this buffer time persists—that is, numberOfSeconds remains non-zero for the stream.

See also

NetStream.bufferTime


NetStream.time

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

my_ns.time

Description

Read-only property; for a subscriber stream, the number of seconds the stream has been playing; for a publishing stream, the number of seconds the stream has been publishing. This number is accurate to the thousandths decimal place; multiply by 1000 to get the number of milliseconds the stream has been playing.

When you are publishing a stream, this property stops incrementing when you stop sending data over the stream by calling NetStream.attachVideo(false) or NetStream.attachAudio(false). When you resume publishing by calling NetStream.attachVideo(active_cam) or NetStream.attachAudio(active_mic), the time property continues incrementing from where it left off plus the time that elapsed while no data was sent. When you stop publishing a stream by calling Netstream.publish(false), the time property stops incrementing and is reset to 0 when you resume publishing the stream.

For a subscribing stream, if the server stops sending data but the stream remains open, this value stops incrementing. When the server begins sending data again, the value of this property continues incrementing from where it left off plus the time that elapsed while no data was sent. The value of this property continues to increment when the stream switches from one playlist element to another. This property is set to 0 when NetStream.play is called with flushPlaylists set to true, or when NetStream.close is called.

Example

The following example shows how, while you are publishing a stream, NetStream.time continues to increment even while no data is being sent over a stream.

my_ns.attachVideo(active_cam);
my_ns.publish("SomeData", "live");
//After 10 seconds, my_ns.time = 10

// You then stop sending data over the stream
my_ns.attachVideo(false);

// Later you start sending data over the same stream
my_ns.attachVideo(active_cam);
// After 10 seconds, my_ns.time = 20

The following example shows how NetStream.time is reset to 0 when you stop publishing a stream for a while and then start publishing the same stream.

my_ns.attachVideo(active_cam);
my_ns.publish("SomeData", "live");
//After 10 seconds, my_ns.time = 10

//You then stop publishing the stream
my_ns.publish(false);

//10 seconds later, you publish on the same stream
my_ns.publish("SomeData", "live");
//my_ns.time resets to 0

The following example shows how, while you are subscribing to a stream, NetStream.time continues to increment even while no data is being sent over the stream.

publish_ns.attachVideo(active_cam);
publish_ns.publish("SomeData", "live");
play_ns.play("SomeData");
//After 10 seconds, play_ns.time = 10

//You then stop sending data for a while
publish_ns.attachVideo(false);

//10 seconds later, you resume sending data over the publishing stream
publish_ns.attachVideo(active_cam);
//play_ns.time continues with 20

The following example shows how, when subscribing to a stream, you can control whether NetStream.time is reset to 0 between items in a playlist by setting the NetStream.play method's flushPlaylists parameter to true or false.

//my_ns.time starts from 0
my_ns.play("live1", -1, 5, true);

//5 secounds later, my_ns switches from "live1" to "live2"
my_ns.play("live2", -1, -1, false);
//my_ns.time continues from 5

//Later you reset the playlist
my_ns.play("live3", -1, 5, true);
//my_ns.time resets to 0 again

See also

NetStream.close(), NetStream.play(), NetStream.publish()


The SharedObject class

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Shared objects are quite powerful: they offer real-time data sharing between multiple client SWF files and objects that are persistent on the local or remote location. You can think of local shared objects as "cookies" and remote shared objects as real-time data transfer devices. Common ways to use shared objects are summarized below.

  • Maintaining local persistence

    This is the simplest way to use a shared object, and does not require Flash Communication Server. For example, you can call SharedObject.getLocal() to create a shared object, such as a calculator with memory, in Flash Player. Because the shared object is locally persistent, Flash saves its data attributes on the user's machine when the application ends. The next time the application runs, the calculator contains the values it had when the application ended. Alternatively, if you set the shared object's properties to null before the application ends, the calculator opens without any prior values the next time the application runs.

  • Storing and sharing data on a server

    A shared object can store data on the Flash Communication Server for other clients to retrieve. For example, you can open a remote shared object, such as a phone list, that is persistent on the server. Whenever a client makes any changes to the shared object, the revised data is available to all clients that are currently connected to the object or who later connect to it. If the object is also persistent locally and a client changes the data while not connected to the server, the changes are copied to the remote shared object the next time the client connects to the object.

  • Sharing data in real time

    A shared object can share data among multiple clients in real time. For example, you can open a remote shared object that stores real-time data, such as a list of users connected to a chat room, that is visible to all clients connected to the object. When a user enters or leaves the chat room, the object is updated and all clients that are connected to the object see the revised list of chat room users.

The following examples show a few ways shared objects are called within ActionScript programs. Note that in order to create a remote shared object, you must first connect to Flash Communication Server with the RTMP protocol.

// Create a local shared object
var local_so:SharedObject = SharedObject.getLocal("foo");

// Create a remote shared object that is not persistent on the server
var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://server.domain.com/chat/room3";
var remote_so:SharedObject = SharedObject.getRemote("users", my_nc.uri);
remote_so.connect(my_nc);

// Create a remote shared object that is persistent on the server
// but not on the client
var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://server.domain.com/chat/room3";
var remote_so:SharedObject = SharedObject.getRemote("users", my_nc.uri, true);
remote_so.connect(my_nc);

// Create a remote shared object that is persistent on the server
// and on the client
var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://server.domain.com/chat/room3";
var remote_so:SharedObject = SharedObject.getRemote("users", my_nc.uri, "/chat");
remote_so.connect(my_nc);

Designing remote shared objects

When designing remote shared objects, develop a model for how the data will be managed. Take into account issues of data design and management, conflict resolution, and storage (persistence) requirements, both locally and on the server. These issues are discussed briefly in this section.

When using a locally persistent remote shared object, make sure your Stage size is at least 215 by 138 pixels. Flash Player needs at least this much space to display the Settings panels.

Data design and management

Data associated with shared objects is stored in attributes of the object's data properties; each set of attributes constitutes one slot. For example, the following lines assign values to three slots of a shared object:

my_so.data.userID = "myLogonName";
my_so.data.currentStatus = "in a meeting";
my_so.data.lastLogon = "February 27, 2002";

Each time a client changes an attribute, all the attributes for that slot are sent to the server and then propagated to all clients attached to the object. Thus, the more information a slot contains, the more network traffic is generated when any attribute in that slot is changed.

For example, consider a shared object with the following attributes occupying a single slot:

my_so.data.year.month.dayOfMonth = someValue;

If a client changes the value of the year, month, or dayOfMonth attribute, the entire slot is updated, even though only one data item was changed.

Compare this data structure to a shared object with the same attributes, but with a flat design that occupies three slots instead of one:

my_so.data.year = someValue;
my_so.data.month = someValue;
my_so.data.dayOfMonth = someValue;

In this case, because each slot contains only one piece of information, less bandwidth is required to update all connected clients when a single data attribute is changed.

You can use this information when designing your remote shared objects. For example, if an object is designed to be updated frequently by multiple clients in real time, minimizing the amount of data per slot can improve performance. This design can also help minimize data collisions (multiple clients trying to change a single slot at the same time).

Conflict resolution

If more than one client (or a server application) can change the data in a single slot of your shared object at the same time, you must implement a conflict resolution strategy. Here are some examples:

Use different slots The simplest strategy is to use a different slot for each player or server that might change data in the object. For example, in a shared object that keeps track of users in a chat room, provide one slot per user and have users modify only their own slots.

Assign an owner A more sophisticated strategy is to define a single client as the owner of a property in a shared object for a limited period of time. You might write server code to create a "lock" object, where a client can request ownership of a slot. If the server reports that the request was successful, the client knows that it will be the only client changing the data in the shared object.

Notify the client When the server rejects a client-requested change to a property of the shared object, the SharedObject.onSync event handler notifies the client that the change was rejected. Thus, an application can provide a user interface to let a user resolve the conflict. This technique works best if data is changed infrequently, as in a shared address book. If a synchronization conflict occurs, the user can decide whether to accept or reject the change.

Accept some changes and reject others Some applications can accept changes on a "first come, first served" basis. This works best when users can resolve conflicts by reapplying a change if someone else's change preceded theirs.

Local disk space considerations

You can choose to make remote shared objects persistent on the client, the server, or both. (Local shared objects are always persistent on the client, up to available memory and disk space.)

By default, Flash can save locally persistent remote shared objects up to 100K in size. When you try to save a larger object, Flash Player displays a Local Storage dialog box, which lets the user allow or deny local storage for the domain that is requesting access. (Make sure your Stage size is at least 215 by 138 pixels; this is the minimum size Flash requires to display the dialog box.)

If the user selects Allow, the object is saved and SharedObject.onStatus is invoked with a code property of SharedObject.Flush.Success; if the user selects Deny, the object is not saved and SharedObject.onStatus is invoked with a code property of SharedObject.Flush.Failed.

The user can also specify permanent local storage settings for a particular domain by right-clicking (Windows) or Control-clicking (Macintosh) while a SWF file is playing, choosing Settings, and then opening the Local Storage panel.

You can't use ActionScript to specify local storage settings for a user, but you can display the Local Storage panel for the user by using System.showSettings(1).

The following list summarizes how the user's disk space choices interact with remote shared objects from a specified domain that request local persistence.

  • If the user selects Never, objects are never saved locally, and all SharedObject.flush() commands issued for the object return false.
  • If the user selects Unlimited (moves the slider all the way to the right), objects are saved locally up to available disk space.
  • If the user selects None (moves the slider all the way to the left), all SharedObject.flush() commands issued for the object return "pending" and cause Flash to ask the user if additional disk space can be allotted to make room for the object, as explained above.
  • If the user selects 10 KB, 100 KB, 1 MB, or 10 MB, objects are saved locally and SharedObject.flush() returns true if the object fits within the specified amount of space. If more space is needed, SharedObject.flush() returns "pending", and Flash asks the user if additional disk space can be allotted to make room for the object, as explained above.

Additionally, if the user selects a value that is less than the amount of disk space currently being used for locally persistent data, Flash warns the user that any shared objects that have already been saved locally will be deleted.

Note: There is no size limit in Flash Player that runs from the authoring environment; the limit applies only to the stand-alone player.

Method summary for the SharedObject class

Method | Description
SharedObject.clear() | Purges data from a shared object.
SharedObject.close() | Closes the connection between a remote shared object and the Flash Communication Server.
SharedObject.connect() | Connects to a remote shared object on the Flash Communication Server.
SharedObject.flush() | Immediately writes a locally persistent shared object to a local file.
SharedObject.getLocal() | Returns a reference to a locally persistent shared object that is available only to the current client.
SharedObject.getRemote() | Returns a reference to a shared object that is available to multiple clients by means of the Flash Communication Server.
SharedObject.getSize() | Gets the current size of the shared object, in bytes.
SharedObject.send() | Broadcasts a message to all clients connected to the remote shared object, including the client that sent the message.
SharedObject.setFps() | Specifies the number of times per second that a client's changes to a shared object are sent to the server.

Property summary for the SharedObject class

Property (read-only) | Description
SharedObject.data | The collection of attributes assigned to the data property of the object; these attributes can be shared and/or stored.

Event handler summary for the SharedObject class

Method | Description
SharedObject.onStatus | Invoked every time an error, warning, or informational note is posted for a shared object.
SharedObject.onSync | Initially invoked when the client and server shared object are synchronized after a successful call to SharedObject.connect(), and later invoked whenever any client changes the attributes of the data property of the remote shared object.

Constructor for the SharedObject class

For information on creating shared objects that do not require Flash Communication Server, see SharedObject.getLocal(). For all other shared objects, see SharedObject.getRemote().


SharedObject.clear()

Availability

  • Flash Player 7.
  • Flash Communication Server MX (not required).

Usage

my_so.clear()

Parameters

None.

Returns

Nothing.

Description

Method; for local shared objects, purges all of the data and deletes the shared object from the disk. The reference to my_so is still active, but my_so data properties are deleted.

For remote shared objects, this method disconnects the object and purges all of the data; if the shared object is locally persistent, the method also deletes the shared object from the disk. The reference to my_so is still active, but my_so data properties are deleted.

Example

The following example shows the effect of using this method.

var my_so:SharedObject = SharedObject.getLocal("example");
my_so.data.name = "Barbara";
trace(my_so.data.name);    // Barbara
my_so.clear();
trace(my_so.data.name);  // undefined


SharedObject.close()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

myRemote_so.close()

Parameters

None.

Returns

Nothing.

Description

Method; closes the connection between a remote shared object and the Flash Communication Server.

If a remote shared object is locally persistent, the user can make changes to the local copy of the object after this method is called. Any changes made to the local object are sent to the server the next time the user connects to the remote shared object.

See also

SharedObject.clear() , SharedObject.connect(), SharedObject.flush()


SharedObject.connect()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

myRemote_so.connect(myRTMPConnection)

Parameters

myRTMPConnection A NetConnection object that is using the Real-Time Messaging Protocol (RTMP) to communicate with the Flash Communication Server.

Returns

A Boolean value of true if the connection was successfully completed, false otherwise.

Description

Method; connects to a remote shared object on the Flash Communication Server through the specified connection. Use this method after issuing SharedObject.getRemote(). After a successful connection, the SharedObject.onSync event handler is invoked.

Before attempting to work with a remote shared object, you should first check for a return value of true, indicating a successful connection, and then wait until you receive a result from the function you have assigned to SharedObject.onSync. If you fail to do so, any changes you make to the object locally—before SharedObject.onSync is invoked—may be lost.

Note: SharedObject.onSync is not invoked if this call returns false.

See also

NetConnection class, SharedObject.getRemote(), SharedObject.onSync


SharedObject.data

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

myLocalOrRemote_so.data

Description

Read-only property; the collection of attributes assigned to the data property of the object; these attributes can be shared and/or stored. Each attribute can be an object of any of the basic ActionScript or JavaScript types—Array, Number, Boolean, and so on. For example, the following lines assign values to various aspects of a shared object:

itemsArray = new Array(101,346,483);
currentUserIsAdmin = true;
currentUserName = "Ramona";
my_so.data.itemNumbers = itemsArray;
my_so.data.adminPrivileges = currentUserIsAdmin;
my_so.data.userName = currentUserName;

All attributes of a shared object's data property are available to all clients connected to the shared object, and all of them are saved if the object is persistent. Attributes are volatile; if one client changes the value of an attribute, all clients now see the new value.

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

If you assign null or undefined to the attribute of a remote shared object, Flash deletes the attribute, and SharedObject.onSync is invoked with a code property of "delete". To delete attributes for local shared objects, use code like delete my_so.data.attributeName; setting an attribute to null or undefined for a local shared object does not delete the attribute.

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

my_so.favoriteColor = "blue";
my_so.favoriteNightClub = "The Bluenote Tavern";
my_so.favoriteSong = "My World is Blue";

Example

The following example sets the current stream to the user's selection.

my_ns = _root.my_so.data.msgList[selected].streamName;

See also

SharedObject.clear() , SharedObject.onSync


SharedObject.flush()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

myLocalOrRemote_so.flush( [ minimumDiskSpace ] )

Parameters

minimumDiskSpace An optional integer specifying the number of bytes that must be allotted for this object. The default value is 0.

Returns

A Boolean value of true or false, or a string value of "pending".

  • If the user has permitted local information storage for objects from this domain, and the amount of space allotted is sufficient to store the object, this method returns true. (If you have passed a value for minimumDiskSpace, the amount of space allotted must be at least equal to that value for true to be returned).
  • If the user has permitted local information storage for objects from this domain, but the amount of space allotted is not sufficient to store the object, this method returns "pending".
  • If the user has permanently denied local information storage for objects from this domain, or if Flash is unable to save the object for any reason, this method returns false.

Description

Method; immediately writes a locally persistent shared object to a local file. If you don't use this method, Flash writes the shared object to a file when the shared object session ends—that is, when the SWF file is closed, when the shared object is garbage-collected because it no longer has any references to it, or when you call SharedObject.close().

If this method returns "pending", the Flash Player displays a dialog box asking the user to increase the amount of disk space available to objects from this domain. To allow space for the shared object to "grow" when it is saved in the future, thus avoiding return values of "pending", pass a value for minimumDiskSpace. When Flash tries to write the file, it looks for the number of bytes passed to minimumDiskSpace, instead of looking for just enough space to save the shared object at its current size.

For example, if you expect a shared object to grow to a maximum size of 500 bytes, even though it may start out much smaller, pass 500 for minimumDiskSpace. If Flash asks the user to allot disk space for the shared object, it will ask for 500 bytes. After the user allots the requested amount of space, Flash won't have to ask for more space on future attempts to flush the object (as long as its size doesn't exceed 500 bytes).

After the user responds to the dialog box, this method is called again and returns either true or false; also, SharedObject.onStatus is invoked with a code property of SharedObject.Flush.Success or SharedObject.Flush.Failed.

For more information, see Local disk space considerations.

Example

The following function gets a shared object, my_so, and fills writable properties with user-provided settings. Finally, flush() is called to save the settings and allot a minimum of 1000 bytes of disk space.

this.SyncSettingsCore = function(soname, override, settings){
  var my_so:SharedObject = SharedObject.getLocal(soname, "http://www.mydomain.com/app/sys");

  // settings list index
  var i;

  // For each specified value in settings:
  // If override is true, set the persistent setting to the provided value.
  // If override is false, fetch the persistent setting, unless there
  // isn't one, in which case, set it to the provided value.
  for (i in settings) {
    if (override || (my_so.data[i] == null)) {
      my_so.data[i]= settings[i];
    } else {
      settings[i]= my_so.data[i];
    }
  }
  my_so.flush(1000);
}

For a remote shared object, calling SharedObject.flush() in the client-side ActionScript file flushes the object only on the client, not the server. The following example shows how a server-side script can flush a remote shared object on the server.

// This is a SERVER-SIDE script, not ActionScript
// Get the shared object when the application is loaded.
application.onAppStart = function(){
  application.my_so = SharedObject.get("SharedObjName", true);
}

// When a user disconnects, flush the shared object.
application.onDisconnect = function(client){
  application.my_so.flush();
}

// You can also set a timer to periodically flush the shared object
// onto the hard disk on the server
application.onAppStart = function(){
  application.my_so = SharedObject.get("SharedObjName", true);
  setInterval(function() { application.my_so.flush(); }, 60000);
}

See also

SharedObject.close()


SharedObject.getLocal()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

SharedObject.getLocal(objectName [, localPath])

Note: The correct syntax is SharedObject.getLocal(). To assign the object to a variable, use syntax like var myLocal_so:SharedObject = SharedObject.getLocal(objectName).

Parameters

objectName The name of the object. The name can include forward slashes (/); for example, work/addresses is a legal name. Spaces are not allowed in a shared object name, nor are the following characters:

~ % & \ ; :  " ' , < > ? #

localPath An optional string parameter that specifies the full or partial path to the SWF file that created the shared object, and that determines where the shared object will be stored locally. The default value is the full path. For more information on using this parameter, see SharedObject.getRemote().

Returns

A reference to a shared object that is persistent locally and is available only to the current client. If Flash can't create or find the shared object (for example, if localPath was specified but no such directory exists), this method returns null.

Description

Method; returns a reference to a locally persistent shared object that is available only to the current client. To create a shared object that is available to multiple clients by means of the Flash Communication Server, use SharedObject.getRemote().

Note: If the user has chosen to never allow local storage for this domain, the object will not be saved locally, even if a value for localPath is specified. For more information, see Local disk space considerations.

Because local shared objects are available only to a single client, the SharedObject.onSync handler is not called when the object is changed, and there is no need to implement conflict-resolution techniques.

To avoid name collisions, Flash looks at the location of the SWF file that is creating the shared object. For example, if a SWF file at www.myCompany.com/apps/stockwatcher.swf creates a shared object named portfolio, that shared object will not conflict with another object named portfolio that was created by a SWF file at www.yourCompany.com/photoshoot.swf, because the SWF files originate from two different directories.

Example

The following example saves the last frame a user entered to a local shared object recentFrame.

// Get the kookie
var myLocal_so:SharedObject = SharedObject.getLocal("recentFrame");

// Get the user of the kookie and go to the frame number saved for this user.
if (myLocal_so.data.user != undefined) {
  this.user = myLocal_so.data.user;
  this.gotoAndStop(myLocal_so.data.frame);
}

The following code block is placed on each SWF frame.

// On each frame, call the rememberme function to save the frame number.
function rememberme() {
  myLocal_so.data.frame=this._currentFrame;
  myLocal_so.data.user="John";
}
rememberme();

See also

SharedObject.close(), SharedObject.flush(), SharedObject.getRemote()


SharedObject.getRemote()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

SharedObject.getRemote(objectName, URI [, persistence])

Note: The correct syntax is SharedObject.getRemote(). To assign the object to a variable, use syntax like var myRemote_so:SharedObject = SharedObject.getRemote(objectName, URI).

Parameters

objectName The name of the object. The name can include forward slashes (/); for example, work/addresses is a legal name. Spaces are not allowed in a shared object name, nor are the following characters: ~ % & \ ; : " ' , < > ? #

URI The URI of the server on which the shared object will be stored. This URI must be identical to the URI of the NetConnection object to which the shared object will be connected. For more information and an example, see the SharedObject class entry.

persistence An optional value that specifies whether the attributes of the shared object's data property are persistent locally, remotely, or both, and that may specify where the shared object will be stored locally. Acceptable values are as follows:

  • null (default) or false specifies that the shared object is not persistent on the client or server. (These values have the same effect as omitting the persistence parameter.)
  • true specifies that the shared object is persistent only on the server.
  • A full or partial local path to the shared object indicates that the shared object is persistent on the client and the server; on the client, it is stored in the specified path. On the server, it is stored in a subdirectory within the Flash Communication Server applications directory. For more information, see "Description," below.

Note: If the user has chosen to never allow local storage for this domain, the object will not be saved locally, even if a local path is specified for persistence. For more information, see Local disk space considerations.

Returns

A reference to an object that can be shared across multiple clients. If Flash can't create or find the shared object (for example, if a local path was specified for persistence but no such directory exists), this method returns null.

Description

Method; returns a reference to an object that can be shared across multiple clients by means of the Flash Communication Server. To create a shared object that is available only to the current client, use SharedObject.getLocal().

After issuing this command, use SharedObject.connect() to connect the object to the Flash Communication Server, as shown below.

var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://somedomain.com/applicationName");

var myRemote_so = SharedObject.getRemote("mo", my_nc.uri, false);
myRemote_so.connect(my_nc);

To confirm that the local and remote copies of the shared object are in sync, use the SharedObject.onSync event handler.

All clients that want to share this object must pass the same values for objectName and URI.

Understanding persistence for remote shared objects By default, the shared object is not persistent on the client or server; that is, when all clients close their connections to the shared object, it is deleted. To create a shared object that is saved locally or on the server, pass a value for persistence.

Once a value has been passed for the local persistence of a remote shared object, it is valid for the life of the object. In other words, once you have gotten a remote shared object which is not locally persistent, you cannot get the same shared object with local persistence while the shared object is active.

For example, the second line of code in the following example does not get a locally persistent remote shared object.

// Get a remote shared object (remote01_so) that is persistent
// on the server but not on the client
var remote01_so:SharedObject = SharedObject.getRemote("someObject", my_nc.uri, true);

// Get a remote shared object (remote02_so) with the same name and path
// as remote01_so, but with local persistence.
// remote02_so will just point to the same object as remote01_so,
// and an onStatus message will be invoked for remote2_so
// with the "code" value of the information object
// set to "SharedObject.BadPersistence".
var remote02_so:SharedObject = SharedObject.getRemote("someObject", my_nc.uri, "somePath");

Also, remote shared objects that are not persistent on the server are created in a different namespace from remote shared objects that are persistent on the server. Therefore, if the following line of code is added to the above example, no SharedObject.BadPersistence error will result because remote03_so does not point to the same object as remote01_so.

var remote03_so:SharedObject = SharedObject.getRemote("someObject", my_nc.uri, false);

Understanding naming conventions for remote shared objects To avoid name collisions, Flash looks at the location of the SWF file that is creating the shared object. For example, if a SWF file at www.myCompany.com/apps/stockwatcher.swf creates a shared object named portfolio, that shared object will not conflict with another object named portfolio that was created by a SWF file at www.yourCompany.com/photoshoot.swf, because the SWF files originate from two different directories.

To further avoid name collisions, Flash Player appends the application name and instance name to the end of the path of the shared object directory. Unless two SWF files are located in the same directory, use a shared object with the same name, and are connected to the same application with the same instance name, there will not be a name collision related to persistent shared objects on either local or remote locations.

However, if two different SWF files located in the same directory create objects with identical names and the same location for persistence, the names will conflict, and one object can overwrite the other without warning. Implemented properly, however, this feature lets SWF files in the same directory read each other's shared objects.

Similarly, you can use persistence to let SWF files in different directories in the same domain read and write each other's shared objects. For example, if the full path to the SWF file is www.macromedia.com/a/b/c/d/foo.swf, persistence can be any of the following:

  • "/"
  • "/a/"
  • "/a/b/"
  • "/a/b/c/"
  • "/a/b/c/d/"
  • "/a/b/c/d/foo.swf/"

By specifying a partial path for persistence, you can let several SWF files from the same domain access the same shared objects. For example, if you specify "/a/b/" for the SWF file named above and also for a SWF file whose full path is www.macromedia.com/a/b/foo2.swf, each SWF file can read shared objects created by the other SWF file. When specifying persistence, do not include a domain name.

To specify that the path for persistence should be the same as the SWF file, without having to explicitly specify its value, you can use MovieClip._url:

var myRemote_so:SharedObject = (name, uri, _root._url);

Example

The following example illustrates the sequence of steps required to create a nonpersistent remote shared object.

// open connection to server
var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://myServer.myCompany.com/someApp");
//
// the URI for the shared object must be the same as
// the URI of the NetConnection it's using
var myRemote_so:SharedObject = SharedObject.getRemote("myObject", my_nc.uri);
my_so.connect(my_nc);

See also

NetConnection class, SharedObject class, SharedObject.connect(), SharedObject.getLocal(), SharedObject.onSync


SharedObject.getSize()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

myLocalOrRemote_so.getSize()

Parameters

None.

Returns

A numeric value specifying the size of the shared object, in bytes.

Description

Method; gets the current size of the shared object, in bytes.

Flash calculates the size of a shared object by stepping through each of its data properties; the more data properties the object has, the longer it takes to estimate its size. For this reason, estimating object size can have significant processing cost. Therefore, you may want to avoid using this method unless you have a specific need for it.

Example

The following example gets the size of the shared object my_so.

var soSize:Number = this.my_so.getSize();


SharedObject.onStatus

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

myLocalOrRemote_so.onStatus = function(infoObject) {
  // Your code here
}

Parameters

infoObject A parameter defined according to the status message. For more information about this parameter, see SharedObject information objects.

Returns

Nothing.

Description

Event handler; invoked every time an error, warning, or informational note is posted for a shared object. If you want to respond to this event handler, you must create a function to process the information object generated by the shared object. For more information, see Client-Side Information Objects.

See also

SharedObject.getLocal(), SharedObject.getRemote(), SharedObject.onSync


SharedObject.onSync

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

myRemote_so.onSync = function(objArray){
  // Your code here
}

Parameters

objArray An array of objects; each object contains properties that describe the changed members of a remote shared object. (For more information, see "Description," below.)

Returns

Nothing.

Description

Event handler; initially invoked when the client and server shared object are synchronized after a successful call to SharedObject.connect(), and later invoked whenever any client changes the attributes of the data property of the remote shared object. You must create a function to override this handler and process the information object sent by this event handler. The properties of each object are code, name, and oldValue.

When you initially connect to a remote shared object that is persistent locally and/or on the server, all the properties of this object are set to empty strings. Otherwise, Flash sets code to "clear", "success", "reject", "change", or "delete" as explained below.

  • A value of "clear" means either that you have successfully connected to a remote shared object that is not persistent on the server or the client, or that all the properties of the object have been deleted—for example, when the client and server copies of the object are so far out of sync that Flash resynchronizes the client object with the server object. In the latter case, SharedObject.onSync is invoked again, this time with the value of code set to "change".
  • A value of "success" means the client changed the shared object.
  • A value of "reject" means the client tried unsuccessfully to change the object; instead, another client changed the object.
  • A value of "change" means another client changed the object or the server resynchronized the object.
  • A value of "delete" means the attribute was deleted.

The name property contains the name of the property that has been changed.

The oldValue property contains the former value of the changed property. This parameter is null unless code has a value of "reject" or "change".

To minimize network traffic, this method is not called when a client "changes" a property to the same value it currently has. That is, if a property is set to the same value multiple times in a row, this method is invoked the first time the property is set, but not during subsequent settings, as shown in the following example:

my_so.data.x = 15;
// The following line invokes onSync
my_so.data.x = 20;
// The following line doesn't invoke onSync,
// even if issued by a different client
my_so.data.x = 20;

Example

// Create or get a remote shared object named 'position';
// my_nc is the NetConnection created earlier in code;
// false means do not make this a persistent shared object.
var myRemote_so:SharedObject = SharedObject.getRemote("position", my_nc.uri, false);

// Update ball position when another participant moves the ball;
// sharedBall_mc is a movie clip on the Stage.
myRemote_so.onSync = function(list) {
    sharedBall_mc._x= myRemote_so.data.x;
    sharedBall_mc._y= myRemote_so.data.y;
}

// You must always call connect() in order to successfully
// connect to the shared object and share data.
myRemote_so.connect(my_nc);

See also

SharedObject.data


SharedObject.send()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

myRemote_so.send(handlerName [,p1, ...,pN])

Parameters

handlerName A string that identifies the message; also the name of the ActionScript handler to receive the message. The handler name can be only one level deep (that is, it can't be of the form parent/child) and is relative to the shared object.

Note: Do not use a reserved term for a handler name. For example, myRemote_so.send("close") will fail.

p1, ...,pN Optional parameters that can be of any type. They are serialized and sent over the connection, and the receiving handler receives them in the same order. If a parameter is a circular object (for example, a linked list that is circular), the serializer handles the references correctly.

Returns

Nothing.

Description

Method; broadcasts a message to all clients connected to myRemote_so, including the client that sent the message. To process and respond to the message, create a function named handlerName attached to the shared object.

Example

The following example shows how to use send to display a message in the Output panel.

// Create a remote shared object called myRemote_so
// Place an Input Text text box named inputMsgTxt on the Stage
// Attach this code to a button labeled "Send Message"
on (release) {
  _root.myRemote_so.send("testMsg",inputMsgTxt);
}
// Attach this code to the frame containing the button
_root.myRemote_so.testMsg = function(recvStr){
  trace(recvStr);
}
// Type data in the text box and press the button to see the results


SharedObject.setFps()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

myRemote_so.setFps(updatesPerSecond)

Parameters

updatesPerSecond A number that specifies how often a client's changes to a remote shared object are sent to the server. The default value is the frame rate of the SWF file.

  • To send changes immediately and then stop sending changes, pass 0 for updatesPerSecond.
  • To reset updatesPerSecond to its default value, pass a value less than 0.

Returns

A Boolean value of true if the update was accepted, false otherwise.

Description

Method; specifies the number of times per second that a client's changes to a shared object are sent to the server.

Use this method when you want to control the amount of traffic between the client and the server. For example, if the connection between the client and server is relatively slow, you may want to set updatesPerSecond to a relatively low value. Conversely, if the client is connected to a multiuser game in which timing is important, you may want to set updatesPerSecond to a relatively high value.

If you want to manually control when updates are sent, issue this command with updatesPerSecond set to 0 when you want to send changes to the server. For example, if you want to let the user push a button that sends updates to the server, attach myRemoteSharedObject.setFps(0) to the button.

Regardless of the value you pass for updatesPerSecond, changes are not sent to the server until SharedObject.onSync has returned a value for the previous update. That is, if the response time from the server is slow, updates may be sent to the server less frequently than the value specified in updatesPerSecond.

See also

SharedObject.onSync


The System class

This is a top-level class that contains the capabilities object, the security object, and other methods, properties, and event handlers. This document discusses the System.showSettings() method and the System.useCodepage property, which are relevant to communication applications. .For more information, see the System class entry in ActionScript Dictionary Help.


System.showSettings()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

System.showSettings([panel])

Parameters

panel An optional number that specifies which Flash Player Settings panel to display, as illustrated in the following table.

Value passed for panel | Settings panel displayed
None (parameter is omitted) | Whichever panel was open the last time the user closed the Player Settings panel
0 | Privacy
1 | Local storage
2 | Microphone
3 | Camera

Returns

Nothing.

Description

Method; displays the specified Flash Player Settings panel, which lets users do any of the following:

  • Allow or deny access to their camera and microphone
  • Specify settings for local disk space available for shared objects
  • Select a default camera and microphone
  • Specify microphone gain and echo suppression settings

For example, if your application requires the use of a camera, you can inform users that they must select Allow in the Privacy Settings panel, and then issue a System.showSettings(0) command. (Make sure your Stage size is at least 215 by 138 pixels; this is the minimum size Flash requires to display the panel.)

See also

Camera.get(), Microphone.get()


System.useCodepage

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

System.useCodepage

Description

Flash Communication Server sends text in UTF-8 format. If you set System.useCodepage = true in your ActionScript code, your communication application might not work properly. A value of true causes Macromedia Flash Player to handle text based on the end user's code page, as in early versions of the player. Flash Player, however, will still send UTF-8 encoded text to Flash Communication Server, and all text received from the server will be UTF-8 encoded as well. Setting System.useCodepage = true in a Macromedia Flash Communication Server application will likely result in unexpected behavior and is strongly discouraged. For example, text might not be sent and received properly from the server. For more information on System.useCodepage, see the Macromedia Flash Support Center.


The Video class

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Note: In Flash Player 7 and later, Flash video (FLV) files can be played without the use of Flash Communication Server. .For more information, see the Video class entry in ActionScript Dictionary Help.

The Video class lets you display live or recorded streaming video on the Stage without embedding it in your SWF file. The video may be a live video stream being captured with the Camera.get() command, or a live or recorded video stream or MP3 audio stream being displayed through the use of a NetStream.play() command (requires Flash Communication Server).

A Video object can be used like a movie clip. As with other objects you place on the stage, you can control various properties of Video objects. For example, you can move the Video object around on the stage by using its _x and _y properties; you can change its size using its _height and _width properties, and so on.

To display the video stream, first place a Video object on the Stage. Then use Video.attachVideo() to attach the video stream to the Video object.

To place a Video object on the Stage:

  1. If the Library panel isn't visible, select Window > Library to display it.
  2. Add an embedded Video object to the library by clicking the Options menu on the right side of the Library panel title bar and selecting New Video.
  3. Drag the Video object to the Stage and use the Property inspector to give it a unique instance name, such as my_video. (Do not name it Video.)

    Note: You can also embed recorded streams (FLV files) using the File > Import or File > Import to Library command. For more information on embedding video files, see Using Flash.

Method summary for the Video class

Method | Description
Video.attachVideo() | Specifies a stream to be displayed within the boundaries of the Video object on the Stage.
Video.clear() | Clears the image currently displayed in the Video object.

Property summary for the Video class

Property | Description
Video.deblocking | Specifies the behavior for the deblocking filter that the video compressor applies as needed when streaming the video.
Video.height | Read-only; the height in pixels of the video stream.
Video.smoothing | Specifies whether the video should be smoothed (interpolated) when it is scaled.
Video.width | Read-only; the width in pixels of the video stream.


Video.attachVideo()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

my_video.attachVideo(source)

Parameters

source A NetStream or Camera object that is playing video or MP3 audio data or capturing video data, respectively. To drop the connection to the Video object, pass null for source.

Returns

Nothing.

Description

Method; specifies a video stream (source) to be displayed within the boundaries of the Video object on the Stage. The video stream is either a NetStream object being displayed by means of the NetStream.play() command (requires Flash Communication Server), a Camera object, or null. If source is null, video is no longer played within the Video object.

If you want to control the audio, you can use MovieClip.attachAudio() to route the audio to a movie clip; you can then create a Sound object to control some aspects of the audio. For more information, see MovieClip.attachAudio().

Example

The following example plays live video locally, without the need for Flash Communication Server.

var active_cam:Camera = Camera.get();
my_video.attachVideo(active_cam); // my_video is a Video object on the Stage

The following example shows how to publish and record a video, and then play it back.

// This script publishes and records video
// The recorded file will be named "allAboutMe.flv"
var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://localhost/allAboutMe/mySpeech");
var publish_ns:NetStream = new NetStream(my_nc);
publish_ns.publish("allAboutMe", "record");
publish_ns.attachVideo(Camera.get());

// This script plays the recorded file.
// Note that no publishing stream is required to play a recorded file.
var my_nc:NetConnection = new NetConnection();
my_nc.connect("rtmp://localhost/allAboutMe/mySpeech");
var subscribe_ns:NetStream = new NetStream(my_nc);
subscribe_ns.play("allAboutMe");
my_video.attachVideo(subscribe_ns);  // my_video is a Video object on the Stage

See also

Camera class, NetStream.play(), NetStream.publish()


Video.clear()

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

my_video.clear()

Parameters

None.

Returns

Nothing.

Description

Method; clears the image currently displayed in the Video object. This is useful when, for example, the connection breaks and you want to display standby information without having to hide the Video object.

See also

Video.attachVideo()


Video.deblocking

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

my_video.deblocking

Description

Property; a number that specifies the behavior for the deblocking filter that the video compressor applies as needed when streaming the video. The following are acceptable values:

  • 0 (the default): Let the video compressor apply the deblocking filter as needed.
  • 1: Never use the deblocking filter.
  • 2: Always use the deblocking filter.

The deblocking filter has an effect on overall playback performance, and it is usually not necessary for high-bandwidth video. If your system is not powerful enough, you might experience difficulties playing back video with this filter enabled.


Video.height

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

my_video.height

Description

Read-only property; an integer specifying the height of the video stream, in pixels. This value is the same as the Camera.height property of the Camera object that is capturing (or previously captured) the video stream. You may want to use this property, for example, to ensure that the user is seeing the video at the same size at which it was captured, regardless of the actual size of the Video object on the Stage.

Example

Usage 1: The following example sets the height and width values of the Video object to match the values of an FLV file. You should call this code after NetStream.onStatus is invoked with a code property of NetStream.Buffer.Full. If you call it when the code property is NetStream.Play.Start, the height and width values will be 0, because the Video object doesn't yet have the height and width of the loaded FLV file.

// Clip is the instance name of the movie clip
// that contains the video object "my_video".
_root.Clip._width = _root.Clip.my_video.width;
_root.Clip._height = _root.Clip.my_video.height;

Usage 2: The following example lets the user press a button to set the height and width of a video stream being displayed in the Flash Player to be the same as the height and width at which the video stream was captured.

// First attach the stream to the Video object
my_video.attachVideo(videoSource);
// Then attach code like the following to a button
on (release) {
  _root.my_video._width = _root.my_video.width
  _root.my_video._height = _root.my_video.height
}

See also

Video.width


Video.smoothing

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

my_video.smoothing

Description

Property; a Boolean value that specifies whether the video should be smoothed (interpolated) when it is scaled. For smoothing to work, Flash Player must be in high-quality mode. The default value is false (no smoothing).


Video.width

Availability

  • Flash Player 6.
  • Flash Communication Server MX (not required).

Usage

my_video.width

Description

Read-only property; an integer specifying the width of the video stream, in pixels. This value is the same as the Camera.width property of the Camera object that is capturing (or previously captured) the video stream. You may want to use this property, for example, to ensure that the user is seeing the video at the same size at which it was captured, regardless of the actual size of the Video object on the Stage.

Example

See the examples for Video.height.


Client-side information objects overview

The Camera, Microphone, LocalConnection, NetConnection, NetStream, and SharedObject objects provide an onStatus event handler that uses an information object for providing information, status, or error messages. To respond to this event handler, you must create a function to process the information object, and you must know the format and contents of the information object returned.

In addition to the specific onStatus methods provided for the objects listed above, Macromedia Flash also provides a "super" function called System.onStatus. If onStatus is invoked for a particular object with a level property of "error" and there is no function assigned to respond to it, Flash processes a function assigned to System.onStatus if it exists.

The following example illustrates how you can create generic and specific functions to process information objects sent by the onStatus method.

// Create generic function
System.onStatus = function(genericError)
{
  // Your script would do something more meaningful here
  trace("An error has occurred. Please try again.");
};

// Create connection functions
// If the connection attempt returns a different information object
// from those listed below, with a level property of "error",
// System.onStatus will be invoked

nConn.onStatus = function(infoObject)
{
  if (infoObject.code == "NetConnection.Connect.Success")
  {
    trace("Successful connection.");
  }
  if (infoObject.code == "NetConnection.Connect.Failed")
  {
    trace("Connection failed.");
  }
};

//   Attempt to open connection
nConn = new NetConnection();
nConn.connect("rtmp://myServer.myDomain.com/myRTMPapp");

The following tables show the default properties of each information object and the circumstances under which onStatus is invoked with each information object. When referring to the tables, note the following:

  • By default, every information object has a code property containing a string that describes the result of the onStatus method, and a level property containing a string that is either "status", "warning", or "error". Some information objects have additional default properties, which provide more information about the reason onStatus was invoked. These properties are noted as footnotes in the tables.
  • For NetStream, NetConnection, and remote shared objects, which are available only with Macromedia Flash Communication Server MX 1.5, the properties of the information objects are determined by the methods available in server applications and should be documented by the developers of your server-side application. The properties listed here are the ones available by default; that is, these are the properties available if your server-side application doesn't specify other information object properties. For information on using Flash with an application server, see Using Flash Remoting.
  • For objects that do not require Flash Communication Server (Camera, Microphone, LocalConnection, and local shared objects), the properties listed here are the only ones available to onStatus, and no server-side application is required.


Camera information objects

The following events notify you when the user has changed access to a camera—by muting it, resizing it, or shutting it down.

Code property | Level property | Meaning
Camera.Muted | Status | The user denied access to a camera.
Camera.Unmuted | Status | The user allowed access to a camera.


LocalConnection information objects

The following events notify you when an attempt to send to a receiving LocalConnection object has succeeded or failed.

Code property | Level property | Meaning
None | Status | Flash successfully sent a command to a receiving LocalConnection object.
None | Error | Flash was unable to send to a receiving LocalConnection object.


Microphone information objects

The following events notify you when the user denies or allows access to a microphone. To determine whether access to a microphone is currently denied or allowed, use the Microphone.muted property.

Code property | Level property | Meaning
Microphone.Muted | Status | The user denied access to a microphone.
Microphone.Unmuted | Status | The user allowed access to a microphone.


NetConnection information objects

The following events notify you when certain NetConnection activities occur.

Code property | Level property | Meaning
NetConnection.Call.Failed | Error | The NetConnection.call method was not able to invoke the server-side method or command.*
NetConnection.Connect.AppShutdown | Error | The application has been shut down (for example, if the application is out of memory resources and must be shut down to prevent the server from crashing) or the server has been shut down.
NetConnection.Connect.Closed | Status | The connection was successfully closed.
NetConnection.Connect.Failed | Error | The connection attempt failed; for example, the server is not running.
NetConnection.Connect.InvalidApp | Error | The application name specified during the connection attempt was not found on the server.
NetConnection.Connect.Rejected | Error | The client does not have permission to connect to the application, or the application expected different parameters from those that were passed, or the application specifically rejected the client.**
NetConnection.Connect.Success | Status | The connection attempt succeeded.

*This information object also has a description property, which is a string that provides a more specific reason for the failure.

**This information object also has an application property, which contains the value returned by the application.rejectConnection server-side method.


NetStream information objects

The following events notify you when certain NetStream activities occur.

Code property | Level property | Meaning
NetStream.Buffer.Empty | Status | Data is not being received quickly enough to fill the buffer. Data flow will be interrupted until the buffer refills, at which time a NetStream.Buffer.Full message will be sent and the stream will begin playing again.
NetStream.Buffer.Full | Status | The buffer is full and the stream will begin playing.
NetStream.Failed | Error | An error has occurred for a reason other than those listed elsewhere in this table, such as the subscriber trying to use the seek command to move to a particular location in the recorded stream, but with invalid parameters.*
NetStream.Pause.Notify | Status | The subscriber has paused playback.
NetStream.Play.Failed | Error | An error has occurred in playback for a reason other than those listed elsewhere in this table, such as the subscriber not having read access.*
NetStream.Play.PublishNotify | Status | Publishing has begun; this message is sent to all subscribers.
NetStream.Play.Reset | Status | The playlist has reset (pending play commands have been flushed).
NetStream.Play.Start | Status | Playback has started.**
NetStream.Play.Stop | Status | Playback has stopped.
NetStream.Play.StreamNotFound | Error | The client tried to play a live or recorded stream that does not exist.
NetStream.Play.UnpublishNotify | Status | Publishing has stopped; this message is sent to all subscribers.
NetStream.Publish.BadName | Error | The client tried to publish a stream that is already being published by someone else.
NetStream.Publish.Idle | Status | The publisher of the stream has been idling for too long.
NetStream.Publish.Start | Status | Publishing has started.
NetStream.Record.Failed | Error | An error has occurred in recording for a reason other than those listed elsewhere in this table; for example, the disk is full.*
NetStream.Record.NoAccess | Error | The client tried to record a stream that is still playing, or the client tried to record (overwrite) a stream that already exists on the server with read-only status.
NetStream.Record.Start | Status | Recording has started.
NetStream.Record.Stop | Status | Recording has stopped.
NetStream.Seek.Failed | Error | The subscriber tried to use the seek command to move to a particular location in the recorded stream, but failed.
NetStream.Seek.Notify | Status | The subscriber has used the seek command to move to a particular location in the recorded stream.
NetStream.Unpause.Notify | Status | The subscriber has resumed playback.
NetStream.Unpublish.Success | Status | Publishing has stopped.

*This information object also has a description property, which is a string that provides a more specific reason for the failure.

**This information object also has a details property, which is a string that provides the name of the stream currently playing on the NetStream. If you are streaming a playlist that contains multiple streams, this information object will be sent each time you begin playing a different stream in the playlist.


SharedObject information objects

The following events notify you when certain SharedObject activities occur.

Code property | Level property | Meaning
SharedObject.BadPersistence | Error | The persistence parameter passed to SharedObject.getRemote() is different from the one used when the shared object was created.
SharedObject.Flush.Failed | Error | A SharedObject.flush() command that returned "pending" has failed (the user did not allot additional disk space for the shared object when Flash Player displayed the Local Storage Settings dialog box).
SharedObject.Flush.Success | Status | A SharedObject.flush() command that returned "pending" has been successfully completed (the user allotted additional disk space for the shared object).
SharedObject.UriMismatch | Error | The URI parameter passed to SharedObject.connect() is different from the one passed to SharedObject.getRemote() when the shared object was created.

Previous


Overview of Server-Side Communication ActionScript

Server-Side Communication ActionScript is a scripting language on the server that lets you develop efficient and flexible client-server Macromedia Flash Communication Server MX 1.5 applications. For example, you can use server-side ActionScript to control login procedures, control events in connected Macromedia Flash applications, determine what users see in their Flash applications, and communicate with other servers. You can also use server-side scripting to allow and disallow users access to various server-side application resources and to allow users to update and share information.

Server-side ActionScript is based on the ECMA-262 specification (ECMAScript 1.5) derived from JavaScript and lets you access the core JavaScript server object model. (For more information, see the Netscape DevEdge website.) Server-side ActionScript provides global methods and classes and exposes a rich object model for developing communication applications. You can also create your own classes, properties, and methods. This dictionary provides detailed information about the classes and their properties, methods, and events.

Client-Side Communication ActionScript is based on the ECMA-262 specification, but there are some differences in its implementation. Server-side ActionScript, however, does not deviate from the ECMA-262 specification. For information about the relationship between server-side ActionScript and client-side ActionScript, see Developing Communication Applications.


Using server-side ActionScript

To use server-side ActionScript with a Flash Communication Server application, you write the code, copy the script into the appropriate server directory, and run the SWF file that connects to the server. To understand Flash Communication Server applications, see Developing Communication Applications.

Create the server-side ActionScript file and name it main.asc. All ActionScript code that is embedded in the script file and not inside a function body executes once when the application is loaded but before the application.onAppStart event handler is called.

Note: You can also name your server-side script file app_name, where app_name is the name of your application's directory, and save it with a file extension of .asc or .js. Also, any double-byte characters (including characters of all Asian languages) in the server-side ActionScript file must be UTF-8-encoded. For more information on server-side script files, see Developing Communication Applications.

To install and test the server-side ActionScript file, do the following:

  1. Locate the Macromedia Flash Communication Server MX /applications directory.

    The default location of the /applications directory is under the Macromedia Flash Communication Server MX product installation directory.

    Note: If you did not accept the default installation settings and you aren't sure where the application directory is located, the location is specified in the <AppsDir> tag of the Vhost.xml file, which is located at \Flash Communication Server MX\conf\_defaultRoot_\_defaultVhost_\. For information about configuring a different application directory, see Managing Flash Communication Server. While your SWF and HTML files should be published under a web server directory, your server-side ASC files, your audio/video FLV files, and your ActionScript FLA source files should not be accessible to a user browsing your website.

  2. Your server-side script file must be named main.asc, main.js, registered_app_name.asc, or registered_app_name.js.
  3. Create a subdirectory in the /applications directory called appName, where appName is a name you choose as the filename of your Flash Communication Server application. You must pass this name as a parameter to the NetConnection.connect method in the client-side ActionScript.
  4. Place the main.asc file in the appName directory or in a subdirectory called scripts in the appName directory.
  5. Open the Flash application (the SWF file) in a browser or in the stand-alone Flash Player.

    The SWF file must contain ActionScript code that passes appName to the connect method of the NetConnection class, as shown in the following example:

    nc = new NetConnection();
nc.connect("rtmp://flashcomsvr.mydomain.com/myFlashComAppName");

    Note: You can use the Communication App inspector or the Administration Console to check if the application loaded successfully.


Overview of naming conventions

When you write server-side ActionScript code, there are certain naming conventions that you must use to name your applications, methods, properties, and variables. These rules let you logically identify objects so your code executes properly.


Naming applications

Flash Communication Server application names must follow the Uniform Resource Identifier (URI) RFC 2396 convention . This convention supports a hierarchical naming system where a forward slash (/) separates the elements in the hierarchy. The first element specifies the application name. The element following the application name specifies the application instance name. Each instance of the application has its own script environment.


Specifying instances

By specifying a unique application instance name after an application name, you can run multiple instances of a single application. For example, rtmp:/support/session215 specifies a customer support application named "support" and refers to a specific session of that application named "session215". All users who connect to the same instance name can communicate with each other by referencing the same streams or shared objects.


Using JavaScript syntax

You must follow all syntax rules of JavaScript. For example, JavaScript is case-sensitive and does not allow punctuation other than underscores (_) and dollar signs ($) in names. You can use numbers in names, but names cannot begin with a number.


Avoiding reserved commands

Flash Communication Server has reserved commands that you cannot use in a script. These commands are either methods that belong to the client-side NetConnection class or methods that belong to the server-side Client class. This means that if you have a NetConnection object on the client (player), you cannot make the following call:

nc.call( "reservedCmd", ... );

In this call, "reservedCmd" is any of the following commands: closeStream, connect, createStream, deleteStream, onStatus, pause, play, publish, receiveAudio, receiveVideo, or seek. It also cannot be any of the server-side Client class methods: getBandwidthLimit, setBandwidthLimit, getStats, and ping.


Contents of the dictionary

All dictionary entries are listed alphabetically. However, methods, properties, and event handlers that are associated with an object are listed along with the object's name—for example, the name property of the Application class is listed as Application.name. The following table helps you locate these elements.

ActionScript element | See entry
acceptConnection | Application.acceptConnection()
addHeader | NetConnection.addHeader()
agent | Client.agent
Application | Application class
bufferTime | Stream.bufferTime
call | Client.call(), NetConnection.call()
clear | SharedObject.clear(), Stream.clear()
clearInterval | clearInterval()
clearSharedObject | Application.clearSharedObjects()
clearStreams | Application.clearStreams()
Client | Client class
clients | Application.clients
close | NetConnection.close(), SharedObject.close()
"commandName" | Client."commandName"
connect | NetConnection.connect()
disconnect | Application.disconnect()
flush | SharedObject.flush()
get | SharedObject.get(), Stream.get()
getBandwidthLimit | Client.getBandwidthLimit()
getProperty | SharedObject.getProperty()
getPropertyNames | SharedObject.getPropertyNames()
handlerName | SharedObject.handlerName
hostName | Application.hostname
ip | Client.ip
isConnected | NetConnection.isConnected
length | Stream.length()
load | load()
lock | SharedObject.lock()
name | Application.name, SharedObject.name, Stream.name
NetConnection | NetConnection class
onAppStart | Application.onAppStart
onAppStop | Application.onAppStop
onConnect | Application.onConnect
onConnectAccept | Application.onConnectAccept
onConnectReject | Application.onConnectReject
onDisconnect | Application.onDisconnect
onStatus | Application.onStatus, NetConnection.onStatus, SharedObject.onStatus, Stream.onStatus
onSync | SharedObject.onSync
play | Stream.play()
purge | SharedObject.purge()
readAccess | Client.readAccess
record | Stream.record()
referrer | Client.referrer
registerClass | Application.registerClass()
registerProxy | Application.registerProxy()
rejectConnection | Application.rejectConnection()
__resolve | Client.__resolve
resyncDepth | SharedObject.resyncDepth
send | SharedObject.send(), Stream.send()
setBandwidthLimit | Client.setBandwidthLimit()
setBufferTime | Stream.setBufferTime()
setInterval | setInterval()
setProperty | SharedObject.setProperty()
SharedObject | SharedObject class
size | SharedObject.size()
server | Application.server
Stream | Stream class
trace | trace()
unlock | SharedObject.unlock()
uri | NetConnection.uri
version | SharedObject.version
writeAccess | Client.writeAccess


The Application class

The Application class contains information about a Flash Communication Server application instance that lasts until the application instance is unloaded. A Flash Communication Server application is a collection of stream objects, shared objects, and clients (connected users). Each application has a unique name, and you can use the naming scheme described in Using naming conventions to create multiple instances of an application.

The Application class lets you accept and reject client connection attempts, register and unregister classes and proxies, and create functions that are invoked when an application starts or stops or when a client connects or disconnects.

Besides the built-in properties of the Application class, you can create other properties of any legal ActionScript type, including references to other ActionScript objects. For example, the following lines of code create a new property of type array and a new property of type number:

application.myarray = new Array();
application.num_requests = 1;

Method summary for the Application class

Method | Description
Application.acceptConnection() | Accepts a connection to an application from a client.
Application.clearSharedObjects() | Clears all shared objects associated with the current instance.
Application.clearStreams() | Clears all stream objects associated with the current instance.
Application.disconnect() | Disconnects a client from the server.
Application.getStats() | Returns network statistics for the application instance.
Application.registerClass() | Registers or unregisters a constructor that is called during object deserialization.
Application.registerProxy() | Registers a NetConnection or Client object to fulfill a method request.
Application.rejectConnection() | Rejects a connection to an application.

Property summary for the Application class

Property (read-only) | Description
Application.clients | An object containing a list of all clients currently connected to the application.
Application.hostname | The hostname of the server for default virtual hosts, and virtual hostname for non-default virtual hosts.
Application.name | The name of an application instance.
Application.server | The platform and version of the server.

Event handler summary for the Application class

Event handler | Description
Application.onAppStart | Invoked when the application is loaded by the server.
Application.onAppStop | Invoked when the application is unloaded by the server.
Application.onConnect | Invoked when a client connects to the application.
Application.onConnectAccept | Invoked when a client successfully connects to the application; for use with communication components only.
Application.onConnectReject | Invoked when a client fails to connect to the application; for use with communication components only.
Application.onDisconnect | Invoked when a client disconnects from the application.
Application.onStatus | Invoked when a script generates an error.


Application.acceptConnection()

Availability

Flash Communication Server MX.

Usage

application.acceptConnection(clientObj)

Parameters

clientObj A client to accept.

Returns

Nothing.

Description

Method; accepts the connection call from a client to the server. The application.onConnect event handler is invoked on the server side to notify a script when NetConnection.connect is called from the client side. You can use the application.acceptConnection method inside an application.onConnect event handler to accept a connection from a client. You can use the application.acceptConnection method outside an application.onConnect event handler to accept a client connection that had been placed in a pending state (for example, to verify a user name and password).

When you use components and your code includes an explicit call to application.acceptConnection or application.rejectConnection, the last line (in order of execution) of the onConnect method should be either application.acceptConnection or application.rejectConnection. Also, any logic that follows the explicit acceptConnection or rejectConnection statement must be placed in application.onConnectAccept and application.onConnectReject statements, or it will be ignored. This requirement exists only when you use components.

Example

The following example uses the application.acceptConnection method to accept the connection from client1:

application.onConnect = function (client1){
  // insert code here
  application.acceptConnection(client1);
  client1.call("welcome");
};

Note: The example above shows code from an application that does not use components.

See also

Application.onConnect, Application.rejectConnection()


Application.clearSharedObjects()

Availability

Flash Communication Server MX.

Usage

application.clearSharedObjects(soPath);

Parameters

soPath A string that indicates the URI of a shared object.

Returns

A Boolean value of true if the shared object at the specified path was deleted; otherwise, false. If using wildcard characters to delete multiple stream files, the method will return true only if all the shared objects matching the wildcard pattern were successfully deleted; otherwise, it will return false.

Description

Method; removes persistent shared objects (FSO files) specified by the soPath parameter and clears all properties from active shared objects (both persistent and nonpersistent). You can use the SharedObject object to create shared objects in a Flash Communication Server application instance. The Flash Communication Server stores persistent shared objects for each application. You can use application.clearSharedObjects to handle one shared object at a time, so you must specify the name of the shared object. You can also use application.clearStreams to remove all the recorded streams based on a stream path.

The soPath parameter specifies the name of a shared object, which can include a slash (/) as a delimiter between directories in the path. The last element in the path can contain wildcard patterns (for example, a question mark [?] and an asterisk [*]) or a shared object name. The application.clearSharedObjects method traverses the shared object hierarchy along the specified path and clears all the shared objects. Specifying a slash clears all the shared objects associated with an application instance.

The following are possible values for the soPath parameter:

  • / clears all local and persistent shared objects associated with the instance.
  • /foo/bar clears the shared object /foo/bar; if bar is a directory name, no shared objects are deleted.
  • /foo/bar/* clears all shared objects stored under the instance directory /foo/bar. The bar directory is also deleted if no persistent shared objects are in use within this name space.
  • /foo/bar/XX?? clears all shared objects that begin with XX, followed by any two characters. If a directory name matches this specification, all the shared objects within this directory are cleared.

If you call the clearSharedObjects method and the specified path matches a shared object that is currently active, all its properties are deleted, and a "clear" event is sent to all subscribers of the shared object. If it is a persistent shared object, the persistent store is also cleared.

Example

The following example clears all the shared objects for an instance:

function onApplicationStop(){
  application.clearSharedObjects("/");
}


Application.clearStreams()

Availability

Flash Communication Server MX.

Usage

application.clearStreams(streamPath);

Parameters

streamPath A string that indicates the URI of a stream.

Returns

A Boolean value of true if the stream at the specified path was deleted; otherwise, false. If using wildcard characters to clear multiple stream files, the method returns true only if all the streams matching the wildcard pattern were successfully deleted; otherwise it returns false.

Description

Method; clears recorded streams (FLV) files and MP3 files associated with the application instance. You can use this method to clear a single stream, all streams associated with the application instance, just those streams in a specific subdirectory of the application instance, or just those streams whose names match a specified wildcard pattern.

The streamPath parameter specifies the location and name of a stream, relative to the application's instance directory. You can include a slash (/) as a delimiter between directories in the path. The last element in the path can contain wildcard patterns (for example, a question mark [?] and an asterisk [*]) or a stream name. The application.clearStreams method traverses the stream hierarchy along the specified path and clears all the recorded streams that match the given wildcard pattern. Specifying a slash clears all the streams associated with an application instance.

To clear MP3 files associated with the application instance, precede the path to the stream with mp3: (for example, mp3:/streamPath). By default, application.clearStreams method clears only recorded FLV streams. You can also explicitly clear only FLV streams by placing flv: before the stream path (for example, flv:/streamPath). See Examples section below for examples of clearing FLV and MP3 files.

The following are examples of some possible values for the streamPath parameter:

  • / or flv:/ clears all recorded (FLV) streams associated with the instance.
  • /report clears the stream file report01.flv from the application instance directory.
  • /presentations/intro clears the recorded stream file intro.flv from the application instance's /presentations subdirectory; if intro is a directory name, no streams are deleted.
  • /presentations/* clears all recorded stream files stored from the application instance's /presentations subdirectory. The /presentation subdirectory is also deleted if no streams are in use within this name space.
  • mp3:/ clears all MP3 files associated with the instance.
  • mp3:/mozart/requiem clears the MP3 file named requiem.mp3 from the application instance's /mozart subdirectory.
  • mp3:/mozart/* clears all MP3 file from the application instance's /mozart subdirectory.
  • /presentations/report?? clears all recorded (FLV) streams that begin with report, followed by any two characters. If there are directories within the given directory listing, the directories are cleared of any streams that match report??.

If an application.clearStreams method is invoked on a stream that is currently recording, the recorded file is set to length 0 (cleared), and the internal cached data is also cleared.

Note: You can also use the Server Management ActionScript API removeApp method to delete all the resources for a single instance.

Examples

The following example clears all recorded streams:

function onApplicationStop(){
  application.clearStreams("/");
}

The following example clears all MP3 files from the application instance's /disco subdirectory:

function onApplicationStop(){
  application.clearStreams("mp3:/disco/*");
}


Application.clients

Availability

Flash Communication Server MX.

Usage

application.clients

Description

Property (read-only); an object containing all the Flash clients or other Flash Communication Servers currently connected to the application. The object is a custom object like an array, but with only one property, length. Each element in the object is a reference to a Client object instance, and you can use the length property to determine the number of users connected to the application. You can use the array access operator ([]) with the application.clients property to access elements in the object.

The object used for the clients property is not an array, but it acts the same except for one difference: you can't use the following syntax to iterate through the object:

for(var i in application.clients) {
  // insert code here
}

Instead, use the following code to loop through each element in a clients object:

for (var i = 0; i < application.clients.length; i++) {
  // insert code here
}

Example

This example uses a for loop to iterate through each member of the application.clients array and calls the method serverUpdate on each client:

for (i = 0; i < application.clients.length; i++){
  application.clients[i].call("serverUpdate");
}


Application.disconnect()

Availability

Flash Communication Server MX.

Usage

application.disconnect(clientObj)

Parameters

clientObj The client to disconnect. The object must be a Client object from the application.clients array.

Returns

A Boolean value of true if the disconnect was successful; otherwise, false.

Description

Method; causes the server to terminate a client connection to the application. When this method is called, NetConnection.onStatus is invoked on the client side with a status message of NetConnection.Connection.Closed. The application.onDisconnect method is also invoked.

Example

This example calls the application.disconnect method to disconnect all users of an application instance:

function disconnectAll(){
  for (i=0; i < application.clients.length; i++){
    application.disconnect(application.clients[i]);
  }
}


Application.getStats()

Availability

Flash Communication Server MX.

Usage

application.getStats()

Returns

An ActionScript object with various properties for each statistic returned.

Description

Method; returns statistics for the application instance including the total number of bytes sent and received, the number of RTMP messages sent and received, the number of dropped messages, the number of clients connected to the application instance, and the number of clients who have disconnected from the application instance.

Example

The following traces example uses Application.getStats to output the application instance's statistics to the Output panel:

stats = application.getStats();
trace("Total bytes received: " + stats.bytes_in);
trace("Total bytes sent : " + stats.bytes_out);
trace("RTMP messages received : " + stats.msg_in);
trace("RTMP messages sent : " + stats.msg_out);
trace("RTMP messages dropped : " + stats.msg_dropped);
trace("Total clients connected : " + stats.total_connects);
trace("Total clients disconnected : " + stats.total_disconnects);


Application.hostname

Availability

  • Flash Player 6
  • Flash Communication Server MX 1.5

Usage

application.hostname

Description

Property (read-only); contains the hostname of the server for default virtual hosts and the virtual hostname for non-default virtual hosts.

Example

The following example traces the name of the host running the current application to the Output panel.

trace( application.hostname )


Application.name

Availability

Flash Communication Server MX.

Usage

application.name

Description

Property (read-only); contains the name of the Flash Communication Server application instance.

Example

The following example checks the name property against a specific string before it executes some code:

if (application.name == "videomail/work"){
  // insert code here
}


Application.onAppStart

Availability

Flash Communication Server MX.

Usage

application.onAppStart = function (){
  // insert code here
};

Parameters

None.

Returns

Nothing.

Description

Event handler; invoked when the server first loads the application instance. You use this handler to initialize an application state. You can use application.onAppStart and application.onAppStop to initialize and clean up global variables in an application because each of these events is invoked only once during the lifetime of an application instance.

Example

The following example defines an anonymous function for the application.onAppStart event handler that sends a trace message:

application.onAppStart = function () {
  trace ("onAppStart called");
};


Application.onAppStop

Availability

Flash Communication Server MX.

Usage

application.onAppStop = function (info){
  // insert code here
};

Parameters

info An information object that explains why the application stopped running. See Server-Side Information Objects.

Returns

The value returned by the function you define, if any, or null. To refuse to unload the application, return false. To unload the application, return true or any non-false value.

Description

Event handler; invoked when the application is about to be unloaded by the server. You can define a function that executes when the event handler is invoked. If the function returns true, the application unloads. If the function returns false, the application doesn't unload. If you don't define a function for this event handler, or if the return value is not a Boolean value, the application is unloaded when the event is invoked.

The Flash Communication Server application passes an information object to the application.onAppStop event. You can use server-side ActionScript to look at this information object to decide what to do in the function you define. You could also define the application.onAppStop event to notify users before shutdown.

If you use the Administration Console or the Server Management ActionScript API to unload a Flash Communication Server application, application.onAppStop is not invoked. Therefore you cannot use the application.onAppStop event, for example, to tell users that the application is exiting.

Example

This example defines a function to perform the shutdown operations on the application. The function is then assigned to the event handler so that it executes when the handler is invoked.

function onMyApplicationEnd(info){
  // Do all the application-specific shutdown logic...
  // insert code here
}

application.onAppStop = onMyApplicationEnd;


Application.onConnect

Availability

Flash Communication Server MX.

Usage

application.onConnect = function (clientObj [, p1, ..., pN]){
  // insert code here to call methods that do authentication
  // returning null puts client in a pending state
  return null;
};
(usage 2)
application.onConnect = function (clientObj [, p1, ..., pN]){
  // insert code here to call methods that do authentication
  // accepts the connection
  application.acceptConnection(clientObj);
};
(usage 3)
application.onConnect = function (clientObj [, p1, ..., pN])
{
  // insert code here to call methods that do authentication
  // accepts the connection by returning true
  return true;
};

Parameters

clientObj The client connecting to the application.

p1 ..., pN Optional parameters passed to the application.onConnect method. These parameters are passed from the client-side NetConnection.connect method when a client connects to the application.

Returns

The value you provide. If you return a Boolean value of true, the server accepts the connection; if the value is false, the server rejects the connection. If you return null or no return value, the server puts the client in a pending state and the client can't receive or send messages. If the client is put in a pending state, you must call application.acceptConnection or application.rejectConnection at a later time to accept or reject the connection. For example, you can perform external authentication by making a NetConnection call in your application.onConnect event handler to an application server, and having the reply handler call application.acceptConnection or application.rejectConnection, depending on the information received by the reply handler.

You can also call application.acceptConnection or application.rejectConnection inside the application.onConnect event handler. If you do, any value returned by the function is ignored.

Note: Returning 1 or 0 is not the same as returning true or false. The values 1 and 0 are treated the same as any other integers and do not accept or reject a connection.

How to use application.onConnect to accept, reject, or put a client in a pending state

Description

Event handler; invoked on the server side when NetConnection.connect is called from the client side and a client attempts to connect to an application instance. You can define a function for the application.onConnect event handler. If you don't define a function, connections are accepted by default. If the server accepts the new connection, the application.clients object is updated.

You can use the application.onConnect event in server-side scripts to perform authentication. All the information required for authentication should be sent to the server by the client as parameters (p1 ..., pN) that you define. In addition to authentication, the script can set the access rights to all server-side objects that this client can modify by setting the Client.readAccess and Client.writeAccess properties.

If there are several simultaneous connection requests for an application, the server serializes the requests so there is only one application.onConnect handler executing at a time. It is a good idea to write code for the application.onConnect function that executes quickly to prevent a long connection time for clients.

Note: If you are using the Component framework (that is, you are loading the components.asc file in your server-side script file) you must use the Application.onConnectAccept method to accept client connections. For more information see Application.onConnectAccept.

Example

This example verifies that the user has sent the password "XXXX". If the password is sent, the user's access rights are modified and the user can complete the connection. In this case, the user can create or write to streams and shared objects in the user's own directory and can read or view any shared object or stream in this application instance.

// This code should be placed in the global scope

application.onConnect = function (newClient, userName, password){
  // Do all the application-specific connect logic
  if (password == "XXXX"){
    newClient.writeAccess = "/" + userName;
    this.acceptConnection(newClient);
  } else {
    var err = new Object();
    err.message = "Invalid password";
    this.rejectConnection(newClient, err);
  }
};

If the password is incorrect, the user is rejected and an information object with a message property set to "Invalid password" is returned to the client side. The object is assigned to infoObject.application. To access the message property, use the following code on the client side:

ClientCom.onStatus = function (info){
  trace(info.application.message);
  // it will print "Invalid password"
  // in the Output panel on the client side
};

See also

Application.acceptConnection(), Application.onConnectAccept, Application.onConnectReject, Application.rejectConnection()


Application.onConnectAccept

Availability

Flash Communication Server MX (with communication components only)

Usage

application.onConnectAccept = function (clientObj [,p1, ..., pN]){
  //insert code here to indicate result of an accepted connection
};

Parameters

clientObj The client connecting to the application.

p1...pN Optional parameters passed to the application.onConnectAccept method. These parameters are passed from the client-side NetConnection.connect method when a client connects to the application.

Returns

Nothing.

Description

Event handler; invoked only when the communication components are used (that is, when the components.asc script is loaded into your server-side application script). application.onConnectAccept is invoked on the server side when NetConnection.connect is called from the client side and a client successfully connects to an application instance.

When you use components, your last line (in order of execution) of the onConnect method should be either application.acceptConnection or application.rejectConnection. Any logic that follows the explicit acceptConnection or rejectConnection statement needs to go into application.onConnectAccept and application.onConnectReject statements, or it will be ignored. This requirement exists only when you use components.

Example

The first example is the client-side code you would use for an application:

nc = new NetConnection();

//try either username
nc.connect("rtmp:/test","jlopes");
//nc.connect("rtmp:/test","hacker");

nc.onStatus = function(info) {trace(info.code);}

nc.doSomething = function(){
  trace("doSomething called!");
}

The second example is server-side code you would include in your application's main.asc file:

//When using components, always load components.asc
load( "components.asc" );

application.onConnect = function(client, username){
  trace("onConnect called");
   gFrameworkFC.getClientGlobals(client).username = username;
  if (username == "hacker") {
    application.rejectConnection(client);
  }
  else {
    application.acceptConnection(client);
  }
}

//Code is in onConnectAccept and onConnectReject statements, because components are used
application.onConnectAccept = function(client, username){
  trace("Connection accepted for "+username);
  client.call("doSomething",null);
}

application.onConnectReject = function(client, username){
  trace("Connection rejected for "+username);
}

See also

Application.acceptConnection(), Application.onConnect, Application.onConnectReject, Application.rejectConnection()


Application.onConnectReject

Availability

Flash Communication Server MX (with communication components only)

Usage

application.onConnectReject = function (clientObj [,p1, ..., pN]){
  //insert code here to indicate result of a rejected connection
};

Parameters

clientObj The client connecting to the application.

p1...pN Optional parameters passed to the application.onConnectReject method. These parameters are passed from the client-side NetConnection.connect method when a client connects to the application.

Returns

Nothing.

Description

Event handler; invoked only when the communication components are used (that is, only when you include a call to load the components.asc script in your server-side application script). application.onConnectReject is invoked on the server side when NetConnection.connect is called from the client side and a client fails to connect to an application instance.

When you use components, the last line (in order of execution) of the onConnect method should be either application.acceptConnection or application.rejectConnection. Any logic that follows the explicit acceptConnection or rejectConnection statement needs to go into application.onConnectAccept and application.onConnectReject statements.

Example

The first example is the client-side code you would use for an application:

nc = new NetConnection();

//try either username
nc.connect("rtmp:/test","jlopes");
//nc.connect("rtmp:/test","hacker");

nc.onStatus = function(info) {trace(info.code);}

nc.doSomething = function(){
  trace("doSomething called!");
}

The second example is the server-side code you would include in your main.asc file:

//When using components, always load components.asc
load( "components.asc" );

application.onConnect = function(client, username){
  trace("onConnect called");
   gFrameworkFC.getClientGlobals(client).username = username;
  if (username == "hacker") {
    application.rejectConnection(client);
  }
  else {
    application.acceptConnection(client);
  }
}

application.onConnectAccept = function(client, username){
  trace("Connection accepted for "+username);
  client.call("doSomething",null);
}

application.onConnectReject = function(client, username){
  trace("Connection rejected for "+username);
}

See also

Application.acceptConnection(), Application.onConnect, Application.onConnectAccept, Application.rejectConnection()


Application.onDisconnect

Availability

Flash Communication Server MX.

Usage

application.onDisconnect = function (clientObj){
  // insert code here
};

Parameters

clientObj A client disconnecting from the application.

Returns

The server ignores any return value.

Description

Event handler; invoked when a client disconnects from the application. You can use this event handler to flush any client state information or to notify other users of this event. This event handler is optional.

Example

This example uses an anonymous function and assigns it to the application.onDisconnect event handler:

// This code should be placed in the global scope.
application.onDisconnect = function (client){
  // Do all the client-specific disconnect logic...
  // insert code here
  trace("user disconnected");
};


Application.onStatus

Availability

Flash Communication Server MX.

Usage

application.onStatus = function (infoObject){
  // insert code here
};

Parameters

infoObject An object that contains the error level, code, and sometimes a description. See Server-Side Information Objects.

Returns

Any value that the callback function returns.

Description

Event handler; invoked when the server encounters an error while processing a message that was targeted at this application instance. The application.onStatus event handler is the root for any Stream.onStatus or NetConnection.onStatus messages that don't find handlers. Also, there are a few status calls that come only to application.onStatus. This event handler can be used for debugging messages that generate errors.

Example

The following example defines a function that sends a trace statement whenever the application.onStatus method is invoked. You can also define a function that gives users specific feedback about the type of error that occurred.

appInstance.onStatus = function(infoObject){
  trace("An application error occurred");
};


Application.registerClass()

Availability

Flash Communication Server MX.

Usage

application.registerClass(className, constructor)

Parameters

className The name of an ActionScript class.

constructor A constructor function used to create an object of a specific class type during object deserialization. The name of the constructor function must be the same as className. During object serialization, the name of the constructor function is serialized as the object's type. To unregister the class, pass the value null as the constructor parameter. Serialization is the process of turning an object into something you can send to another computer over the network.

Returns

Nothing.

Description

Method; registers a constructor function that is used when deserializing an object of a certain class type. If the constructor for a class is not registered, you cannot call the deserialized object's methods. This method is also used to unregister the constructor for a class. This is an advanced use of the server and is necessary only when sending ActionScript objects between a client and a server.

The client and the server communicate over a network connection. Therefore, if you use typed objects, each side must have the prototype of the same objects they both use. In other words, both the client-side and server-side ActionScript must define and declare the types of data they share so that there is a clear, reciprocal relationship between an object, method, or property on the client and the corresponding element on the server. You can use application.registerClass to register the object's class type on the server side so that you can use the methods defined in the class.

Constructor functions should be used to initialize properties and methods; they should not be used for executing server code. Constructor functions are called automatically when messages are received from the client and need to be "safe" in case they are executed by a malicious client. You shouldn't define procedures that could result in negative situations such as filling up the hard disk or consuming the processor.

The constructor function is called before the object's properties are set. A class can define an onInitialize method, which is called after the object has been initialized with all its properties. You can use this method to process data after an object is deserialized.

If you register a class that has its prototype set to another class, you must set the prototype constructor back to the original class after setting the prototype. The second example below illustrates this point.

Note: Client-side classes must be defined as function function_name(){}, as shown in the following examples. If not defined in the correct way, application.registerClass will not properly identify the class when an instance of it is passed from the client to the server, and an error will be returned.

Example

This example defines a Color constructor function with properties and methods. After the application connects, the registerClass method is called to register a class for the objects of type Color. When a typed object is sent from the client to the server, this class is called to create the server-side object. After the application stops, the registerClass method is called again and passes the value null to unregister the class.

function Color(){
  this.red = 255;
  this.green = 0;
  this.blue = 0;
}
Color.prototype.getRed = function(){
  return this.red;
}
Color.prototype.getGreen = function(){
  return this.green;
}
Color.prototype.getBlue = function(){
  return this.blue;
}
Color.prototype.setRed = function(value){
  this.red = value;
}
Color.prototype.setGreen = function(value){
  this.green = value;
}
Color.prototype.setBlue = function(value){
  this.blue = value;
}
application.onAppStart = function(){
  application.registerClass("Color", Color);
};
application.onAppStop = function(){
  application.registerClass("Color", null);
};

The following example shows how to use the application.registerClass method with the prototype property:

function A(){}
function B(){}

B.prototype = new A();
B.prototype.constructor = B; // set constructor back to that of B
// insert code here
application.registerClass("B", B);


Application.registerProxy()

Availability

Flash Communication Server MX.

Usage

application.registerProxy(methodName, proxyConnection [, proxyMethodName])

Parameters

methodName The name of a method. All requests to execute methodName for this application instance are forwarded to the proxyConnection object.

proxyConnection A Client or NetConnection object. All requests to execute the remote method specified by methodName are sent to the Client or NetConnection object that is specified in the proxyConnection parameter. Any result that is returned is sent back to the originator of the call. To unregister, or remove, the proxy, provide a value of null for this parameter.

proxyMethodName An optional parameter. The server calls this method on the object specified by the proxyConnection parameter if proxyMethodName is different from the method specified by the methodName parameter.

Returns

A value that is sent back to the client that made the call.

Description

Method; maps a method call to another function. You can use this method to communicate between different application instances that can be on the same Flash Communication Server (or different Flash Communication Servers). Clients can execute server-side methods of any application instances to which they are connected. Server-side scripts can use this method to register methods to be proxied to other application instances on the same server or a different server. You can remove or unregister the proxy by calling this method and passing null for the proxyConnection parameter, which results in the same behavior as never registering the method at all.

Example

In the following example, the application.registerProxy method is called in a function in the application.onAppStart event handler and executes when the application starts. Inside the function block, a new NetConnection object called myProxy is created and connected. The application.registerProxy method is then called to assign the method getXyz to the myProxy object.

application.onAppStart = function(){
  var myProxy = new NetConnection();myProxy.connect("rtmp://xyz.com/myApp");
  application.registerProxy("getXyz", myProxy);
};


Application.rejectConnection()

Availability

Flash Communication Server MX.

Usage

application.rejectConnection(clientObj, errObj)

Parameters

clientObj A client to reject.

errObj An object of any type that is sent to the client, explaining the reason for rejection. The errObj object is available in client-side scripts as the application property of the information object that is passed to the application.onStatus call when the connection is rejected. For more information, see the appendix, "Client-Side Information Objects," in the Client-Side Communication ActionScript Dictionary.

Returns

Nothing.

Description

Method; rejects the connection call from a client to the server. The application.onConnect event handler notifies a script when a new client is connecting. In the function assigned to application.onConnect, you can either accept or reject the connection. You can also define a function for application.onConnect that calls an application server for authentication. In that case, an application could call application.rejectConnection from the application server's response callback to disconnect the client from the server.

When you use components and your code includes an explicit call to application.acceptConnection or application.rejectConnection, the last line (in order of execution) of the onConnect method should be either application.acceptConnection or application.rejectConnection. Also, any logic that follows the explicit acceptConnection or rejectConnection statement must be placed in application.onConnectAccept and application.onConnectReject statements, or it will be ignored. This requirement exists only when you use components.

Example

In the following example, the client specified by client1 is rejected and provided with the error message contained in err.message. The message "Too many connections" appears on the server side.

function onConnect(client1){
  // insert code here
  var err = new Object();err.message = "Too many connections";
  application.rejectConnection(client1, err);
}

The following code should appear on the client side:

clientConn.onStatus = function (info){
  if (info.code == "NetConnection.Connect.Rejected"){
    trace(info.application.message);
    // this sends the message
    // "Too many connections" to the Output panel
    // on the client side
  }
};

See also

Application.onConnect, Application.acceptConnection()


Application.server

Availability

Flash Communication Server MX.

Usage

application.server

Description

Property (read-only); contains the platform and the server-version information.

Example

The following example checks the server property against a string before executing the code inside the if statement:

if (application.server == "Flash Communication Server-Windows/1.0"){
  // insert code here
}


clearInterval()

Availability

Flash Communication Server MX.

Usage

clearInterval(intervalID)

Parameters

intervalID A unique ID returned by a previous call to the setInterval() method.

Returns

Nothing.

Description

Method (global); cancels a time-out that was set with a call to the setInterval() method.

Example

The following example creates a function named callback and passes it to the setInterval() method, which is called every 1000 milliseconds and sends the message "interval called" to the Output panel. The setInterval() method returns a unique identifier that is assigned to the variable intervalID. The identifier allows you to cancel a specific setInterval() call. In the last line of code, the intervalID variable is passed to the clearInterval() method to cancel the setInterval() call:

function callback(){trace("interval called");
}
var intervalID;
intervalID = setInterval(callback, 1000);
// sometime later
clearInterval(intervalID);


The Client class

The Client class lets you handle each user, or client, connection to a Flash Communication Server application instance. The server automatically creates a Client object when a user connects to an application; the object is destroyed when the user disconnects from the application. Users have unique Client objects for each application to which they are connected. Thousands of Client objects can be active at the same time.

You can use the properties of the Client class to determine the version, platform, and IP address of each client. You can also set individual read and write permissions to various application resources such as Stream objects and shared objects. Use the methods of the Client class to set bandwidth limits and call methods in client-side scripts.

When you call NetConnection.call from a client-side ActionScript script, the method that executes in the server-side script must be a method of the Client class. In your server-side script, you must define any method that you want to call from the client-side script. You can also call any methods you define in the server-side script directly from the Client class instance in the server-side script.

If all instances of the Client class (each client in an application) require the same methods or properties, you can add those methods and properties to the class itself instead of adding them to each instance of a class. This process is called extending a class. You can extend any server-side or client-side ActionScript class. To extend a class, instead of defining methods inside the constructor function of the class or assigning them to individual instances of the class, you assign methods to the prototype property of the constructor function of the class. When you assign methods and properties to the prototype property, the methods are automatically available to all instances of the class.

Extending a class lets you define the methods of a class separately, which makes them easier to read in a script. And more importantly, it is more efficient to add methods to prototype, otherwise the methods are reinterpreted each time an instance is created.

The following code shows how to assign methods and properties to an instance of a class. During application.onConnect, a client instance clientObj is passed to the server-side script as a parameter. You can then assign a property and method to the client instance:

application.onConnect = function(clientObj){
  clientObj.birthday = myBDay;
  clientObj.calculateDaysUntilBirthday = function(){
    // insert code here
  }
};

The above example works, but must be executed every time a client connects. If you want the same methods and properties to be available to all clients in the application.clients array without defining them every time, you must assign them to the prototype property of the Client class. There are two steps to extending a built-in class using the prototype method. You can write the steps in any order in your script. The following example extends the built-in Client class, so the first step is to write the function that you will assign to the prototype property:

// first step: write the functions

function Client_getWritePermission(){
// "writeAccess" property is already built-in to the client class
return this.writeAccess;
}

function Client_createUniqueID(){
  var ipStr = this.ip;
// "ip" property is already built-in to the client class
  var uniqueID = "re123mn"
// you would need to write code in the above line
// that creates a unique ID for each client instance
  return uniqueID;
}

// second step: assign prototype methods to the functions

Client.prototype.getWritePermission = Client_getWritePermission;
Client.prototype.createUniqueID = Client_createUniqueID;

// a good naming convention is to start all class method
// names with the name of the class, followed by an underscore

You can also add properties to prototype, as shown in the following example:

Client.prototype.company = "Macromedia";

The methods are available to any instance, so within application.onConnect, which is passed a clientObj argument, you can write the following code:

application.onConnect = function(clientObj){
  var clientID = clientObj.createUniqueID();
  var clientWritePerm = clientObj.getWritePermission();
};

Method summary for the Client class

Method | Description
Client.call() | Executes a method on the Flash client asynchronously and returns the value from the Flash client to the server.
Client.getBandwidthLimit() | Returns the maximum bandwidth the client or the server can attempt to use for this connection.
Client.getStats() | Returns statistics for the client.
Client.ping() | Sends a "ping" message to the client. If the client responds, the method returns true; otherwise it returns false.
Client.__resolve | Provides values for undefined properties.
Client.setBandwidthLimit() | Sets the maximum bandwidth for the connection.

Property summary for the Client class

Property | Description
Client.agent | The version and platform of the Flash client.
Client.ip | The IP address of the Flash client.
Client.protocol | The protocol used by the client to connect to the server.
Client.readAccess | A list of access levels to which the client has read access.
Client.referrer | The URL of the SWF file or server where this connection originated.
Client.writeAccess | A list of access levels to which the client has write access.

Event handler summary for the Client class

Event handler | Description
Client."commandName" | Invoked when NetConnection.call(commandName) is called in a client-side script.


Client.agent

Availability

Flash Communication Server MX.

Usage

Client.agent

Description

Property (read-only); contains the version and platform information of the Flash client.

Example

The following example checks the agent property against the string "WIN" and executes different code depending on whether they match. This code is written inside an onConnect function.

function onConnect(newClient, name){
  if (newClient.agent.indexOf("WIN") > -1){
    trace ("Window user");
  }  else {
    trace ("non Window user.agent is" + newClient.agent);
  }
}


Client.call()

Availability

Flash Communication Server MX.

Usage

Client.call(methodName, [resultObj, [p1, ..., pN]])

Parameters

methodName A method specified in the form [objectPath/]method. For example, the command someObj/doSomething tells the client to invoke the NetConnection.someObj.doSomething method on the client.

resultObj An optional parameter that is required when the sender expects a return value from the client. If parameters are passed but no return value is desired, pass the value null. The result object can be any object you define and, in order to be useful, should have two methods that are invoked when the result arrives: onResult and onStatus. The resultObj.onResult event is triggered if the invocation of the remote method is successful; otherwise, the resultObj.onStatus event is triggered.

p1, ..., pN Optional parameters that can be of any ActionScript type, including a reference to another ActionScript object. These parameters are passed to the methodName parameter when the method executes on the Flash client. If you use these optional parameters, you must pass in some value for resultObject; if you do not want a return value, pass null.

Returns

A Boolean value of true if a call to methodName was successful on the client; otherwise, false.

Description

Method; executes a method on the originating Flash client or on another server. The remote method may optionally return data, which is returned as a result to the resultObj parameter, if it is provided. The remote object is typically a Flash client connected to the server, but it can also be another server. Whether the remote agent is a Flash client or another server, the method is called on the remote agent's NetConnection object.

Example

The following example shows a client-side script that defines a function called random, which generates a random number:

nc = new NetConnection();
nc.connect ("rtmp://someserver/someApp/someInst");
nc.random = function(){
  return (Math.random());
};

The following server-side script uses the Client.call method inside the application.onConnect handler to call the random method that was defined on the client side. The server-side script also defines a function called randHander, which is used in the Client.call method as the resultObj parameter.

application.onConnect = function(clientObj){
  trace("we are connected");
  application.acceptConnection(clientObj);
  clientObj.call("random", new randHandler());
};
randHandler = function(){
  this.onResult = function(res){
    trace("random num: " + res);
  }
  this.onStatus = function(info){
    trace("failed and got:" + info.code);
  }
};


Client."commandName"

Availability

Flash Communication Server MX.

Usage

function onMyClientCommand([p1, ..., pN])
{
  // insert code here
  return val;
}

Parameters

p1, ..., pN Optional parameters passed to the command message handler if the message contains parameters you defined. These parameters are the ActionScript objects passed to the NetConnection.call() method.

Returns

Any ActionScript object you define. This object is serialized and sent to the client as a response to the command only if the command message supplied a response handler.

Description

Event handler; invoked when a Flash client or another server calls the NetConnection.call method. A command name parameter is passed to NetConnection.call on the client side, which causes Flash Communication Server to search the Client object instance on the server side for a method that matches the command name parameter. If the parameter is found, the method is invoked and the return value is sent back to the client.

Example

This example creates a method called sum as a property of the Client object newClient on the server side:

newClient.sum = function sum(op1, op2){
  return op1 + op2;
};

The sum method can then be called from NetConnection.call on the Flash client side, as shown in the following example:

nc = new NetConnection();
nc.connect("rtmp://myServer/myApp");
nc.call("sum", new result(), 20, 50);
function result(){
  this.onResult = function (retVal){
    output += "sum is " + retVal;
  };
  this.onStatus = function(errorVal){
    output += errorVal.code + " error occurred";
  };
}

The sum method can also be called on the server side, as shown here:

newClient.sum();

The following example creates two functions that you can call from either a client-side or server-side script:

application.onConnect = function(clientObj) {
  // Add a callable function called "foo"; foo returns the number 8
  clientObj.foo = function() {return 8;};
  // Add a remote function that is not defined in the onConnect call
  clientObj.bar = application.barFunction;
};
// The bar function adds the two values it is given
application.barFunction = function(v1,v2) {
  return (v1 + v2);
};

You can call either of the two functions that were defined in the previous examples (foo and bar) by using the following code in a client-side script:

c = new NetConnection();
c.call("foo");
c.call("bar", null, 1, 1);

You can call either of the two functions that were defined in the previous examples (foo and bar) by using the following code in a server-side script:

c = new NetConnection();
c.onStatus = function(info) {
  if(info.code == "NetConnection.Connect.Success") {
    c.call("foo");
    c.call("bar", null, 2, 2);
  }
};


Client.getBandwidthLimit()

Availability

Flash Communication Server MX.

Usage

Client.getBandwidthLimit(iDirection)

Parameters

iDirection An integer specifying the connection direction: 0 indicates a client-to-server direction, 1 indicates a server-to-client direction.

Returns

An integer indicating bytes per second.

Description

Method; returns the maximum bandwidth that the client or the server can use for this connection. Use the iDirection parameter to get the value for each direction of the connection. The value returned indicates bytes per second and can be changed with Client.setBandwidthLimit(). The default value for a connection is set for each application in the Application.xml file.

Example

The following example uses Client.getBandwidthLimit() with the iDirection parameter to set two variables, clientToServer and serverToClient:

application.onConnect = function(newClient){
  var clientToServer= newClient.getBandwidthLimit(0);var serverToClient= newClient.getBandwidthLimit(1);
};


Client.getStats()

Availability

Flash Communication Server MX.

Usage

Client.getStats()

Returns

An object with various properties for each statistic returned.

Description

Method; returns statistics for the client including the total number of bytes sent and received, the number of RTMP messages sent and received, the number of dropped RTMP messages, and how long it takes the client takes to respond to a ping message.

Example

The following example uses Client.getStats() to output a new client's statisitics to the Output panel:

application.onConnect( newClient ){
  stats = newClient.getStats();
  trace("Total bytes received : " + stats.bytes_in);
  trace("Total bytes sent : " + stats.bytes_out);
  trace("RTMP messages received : " + stats.msg_in);
  trace("RTMP messages sent: " + stats.msg_out);
  trace("RTMP messages dropped : " + stats.msg_dropped);
  trace("Ping roundtrip time: " + stats.ping_rtt);
}

See also

Client.ping()


Client.ip

Availability

Flash Communication Server MX.

Usage

Client.ip

Description

Property (read-only); contains the IP address of the Flash client.

Example

The following example uses the Client.ip property to verify whether a new client has a specific IP address. The result determines which block of code runs.

application.onConnect = function(newClient, name){
  if (newClient.ip == "127.0.0.1"){
    // insert code here
  } else {
    // insert code here
  }
};


Client.protocol

Availability

Flash Communication Server MX

Usage

Client.protocol

Description

Property (read-only); contains a string that indicates the protocol used by the client to connect to the server. This string can have one of the following values:

  • rtmp (Real Time Message Protocol over persistent socket connection)
  • rtmpt (RTMP tunneled through HTTP protocol)

For more information about the HTTP tunneling feature in Flash Communication Server MX, see the NetConnection.connect() entry in the Client-Side Communication ActionScript Dictionary.

Example

The following checks the connection protocol used by a client upon connection to the application.

application.onConnect(clientObj) {
  if(clientObj.protocol == "rtmp") {
    trace("Client connected over a persistent connection");
  } else if(clientOjb.protocol == "rtmpt") {
    trace("Client connected over an HTTP tunneling connection");
  }
}


Client.ping()

Availability

Flash Communication Server MX.

Usage

Client.ping()

Description

Method; sends a "ping" message to the client and waits for a response. If the client responds, the method returns true, otherwise returns false. Use this method to determine whether or not the client connection is still alive and active.

Example

The following onConnect function pings the connecting client and traces the results of the method to the Output panel:

application.onConnect( newClient ) {
  if ( newClient.ping() ){
    trace("ping successful");
  }
  else {
    trace("ping failed");
  }
}

See also

Client.getStats()


Client.readAccess

Availability

Flash Communication Server MX.

Usage

Client.readAccess

Description

Property; provides read-access rights to directories that contain application resources (shared objects and streams) for this client. To give a client read access to directories containing application resources, list directories in a string delimited by semicolons.

By default, all clients have full read access, and the readAccess property is set to slash (/). To give a client read access, specify a list of access levels (in URI format), delimited by semicolons. Any files or directories within a specified URI are also considered accessible. For example, if myMedia is specified as an access level, then any files or directories in the myMedia directory are also accessible (for example, myMedia/mp3s). Similarly, any files or directories in the myMedia/mp3s directory are also accessible, and so on.

Clients with read access to a directory that contains streams can play streams in the specified access levels. Clients with read access to a directory that contains shared objects can subscribe to shared objects in the specified access levels and receive notification of changes in the shared objects.

  • For streams, readAccess controls which streams can be played by the connection.
  • For shared objects, readAccess controls if the connection can listen to shared object changes.

Tip: Although you cannot use this property to control access for a particular file, you can create a separate directory for a file if you want to control access to it.

Example

The following onConnect function gives a client read access to myMedia/mp3s, myData/notes, and any files or directories within them:

application.onConnect = function(newClient, name){
  newClient.readAccess = "myMedia/mp3s;myData/notes";
};

See also

Client.writeAccess


Client.referrer

Availability

Flash Communication Server MX.

Usage

Client.referrer

Description

Property (read-only); a string object whose value is set to the URL of the SWF file or the server in which this connection originated.

Example

The following example defines an onConnect callback function that sends a trace to the Output panel indicating the origin of the new client when that client connects to the application:

application.onConnect = function(newClient, name){
  trace("New user connected to server from" + newClient.referrer);
};


Client.__resolve

Availability

Flash Communication Server MX.

Usage

Client.__resolve = function(propName){
  // insert code here
};

Parameters

propName The name of an undefined property.

Returns

The value of the undefined property, which is specified by the propName parameter.

Description

Event handler; provides values for undefined properties. When an undefined property of a Client object is referenced by server-side ActionScript code, that object is checked for a __resolve method. If the object has a __resolve method, the __resolve method is invoked and passed the name of the undefined property. The return value of the __resolve method is the value of the undefined property. In this way, __resolve can supply the values for undefined properties and make it appear as if they are defined.

Example

The following example defines a function that is called whenever an undefined property is referenced:

Client.prototype.__resolve = function (name) {
  return "Hello, world!";
};
function onConnect(newClient){
  trace (newClient.property1); // this will print "Hello World"
}


Client.setBandwidthLimit()

Availability

Flash Communication Server MX.

Usage

Client.setBandwidthLimit(iServerToClient, iClientToServer)

Parameters

iServerToClient The bandwidth from server to client, in bytes per second. Use 0 if you don't want to change the current setting.

iClientToServer The bandwidth from client to server, in bytes per second. Use 0 if you don't want to change the current setting.

Returns

Nothing.

Description

Method; sets the maximum bandwidth for this client from client to server, server to client, or both. The default value for a connection is set for each application in the Application.xml file. The value specified cannot exceed the bandwidth cap value specified in the Application.xml file.

Example

The following example sets the bandwidth limits for each direction, based on values passed to the onConnect function:

application.onConnect = function(newClient, serverToClient, clientToServer){
  newClient.setBandwidthLimit(serverToClient, clientToServer);
  application.acceptConnection(newClient);
}


Client.writeAccess

Availability

Flash Communication Server MX.

Usage

Client.writeAccess

Description

Property; provides write-access rights to directories containing application resources (such as shared objects and streams) for this client. To give a client write access to directories containing application resources, list directories in a string delimited by semicolons. By default, all clients have full write access, and the writeAccess property is set to slash (/). For example, if myMedia is specified as an access level, then any files or directories in the myMedia directory are also accessible (for example, myMedia/myStreams). Similarly, any files or subdirectories in the myMedia/myStreams directory are also accessible, and so on.

  • For shared object, writeAccess provides control over who can create and update the shared objects.
  • For streams, writeAccess provides control over who can publish and record a stream.

Tip: Although you cannot use this property to control access for a particular file, you can create a separate directory for a file if you want to control access to it.

Example

The following example provides write access to the /myMedia/myStreams and myData/notes directories.

application.onConnect = function(newClient, name){
  newClient.writeAccess = "/myMedia/myStreams;myData/notes";
  application.acceptConnection();
};

See also

Client.readAccess


load()

Availability

Flash Communication Server MX.

Usage

load(filename);

Parameters

filename The relative path to an ActionScript file in relation to the main.asc file.

Returns

Nothing.

Description

Method (global); loads an ActionScript file inside the main.asc file. This method executes only when the ActionScript file is first loaded. The loaded file is compiled and executed after the main.asc file is successfully loaded, compiled, and executed, and before application.onAppStart is executed. The path of the specified file is resolved relative to main.asc. This method is useful for loading ActionScript libraries.

Note: For security reasons, your server-side applications directory, which contains ASC files, audio/video FLV files, and ActionScript FLA source files, should not be accessible to a user browsing your website.

Example

The following example loads the myLoadedFile.as file:

load("myLoadedFile.as");


The NetConnection class

The server-side NetConnection class lets you create a two-way connection between a Flash Communication Server application instance and an application server, another Flash Communication Server, or another Flash Communication Server application instance on the same server. You can use NetConnection objects to create powerful applications; for example, you can get weather information from an application server or share an application load with other Flash Communication Servers or application instances.

You can use Macromedia Flash Remoting with the Flash Communication Server to communicate with application servers such as Macromedia ColdFusion MX, Macromedia JRun, Microsoft .NET, and J2EE servers using Action Message Format (AMF) over HTTP. AMF lets you transfer light-weight binary data between a Flash Communication Server or a Flash client and a web application server. For more information, see www.macromedia.com/go/flashremoting.

You can also connect to an application server for server-to-server interactions using standard protocols (such as HTTP) or connect to another Flash Communication Server for sharing audio, video, and data using the Macromedia Real-Time Messaging Protocol (RTMP).

To create a NetConnection object, use the constructor function described below.


Method summary for the NetConnection class

Method | Description
NetConnection.addHeader() | Adds a context header.
NetConnection.call() | Invokes a method or operation on a remote server.
NetConnection.close() | Closes a server connection.
NetConnection.connect() | Establishes connection to a server.

Property summary for the NetConnection class

Property | Description
NetConnection.isConnected | A Boolean value indicating whether a connection has been made.
NetConnection.uri | The URI that was passed by the NetConnection.connect() method.

Event handler summary for the NetConnection class

Event handler | Description
NetConnection.onStatus | Called when there is a change in connection status.

Constructor for the NetConnection class

Availability

Flash Communication Server MX.

Usage

new NetConnection()

Parameters

None.

Returns

A NetConnection object.

Description

Constructor; creates a new instance of the NetConnection class.

Example

The following example creates a new instance of the NetConnection class:

newNC = new NetConnection();


NetConnection.addHeader()

Availability

Flash Communication Server MX.

Usage

myNetConn.addHeader(name, mustUnderstand, object)

Parameters

name A string that identifies the header and the ActionScript object data associated with it.

mustUnderstand A Boolean value; true indicates that the server must understand and process this header before it handles any of the following headers or messages.

object Any ActionScript object.

Returns

Nothing.

Description

Method; adds a context header to the AMF packet structure. This header is sent with every future AMF packet. If you call NetConnection.addHeader() using the same name, the new header replaces the existing header, and the new header persists for the duration of the NetConnection object. You can remove a header by calling NetConnection.addHeader() with the name of the header to remove and an undefined object.

Example

The following example creates a new NetConnection instance, nc, and connects to an application at web server www.foo.com that is listening at port 1929. This application dispatches the service /blag/SomeCoolService. The last line of code adds a header called foo:

nc=new NetConnection();
nc.connect("http://www.foo.com:1929/blag/SomeCoolService");
nc.addHeader("foo", true, new Foo());


NetConnection.call()

Availability

Flash Communication Server MX.

Usage

myNetConnection.call(methodName, [resultObj, p1, ..., pN])

Parameters

methodName A method specified in the form [objectPath/]method. For example, the command someObj/doSomething tells the remote server to invoke the clientObj.someObj.doSomething method, with all the p1, ..., pN parameters. If the object path is missing, clientObj.doSomething() is invoked on the remote server.

resultObj An optional parameter that is used to handle return values from the server. The result object can be any object you defined and can have two defined methods to handle the returned result: onResult and onStatus. If an error is returned as the result, onStatus is invoked; otherwise, onResult is invoked.

p1, ..., pN Optional parameters that can be of any ActionScript type, including a reference to another ActionScript object. These parameters are passed to the methodName specified above when the method is executed on the remote application server.

Returns

For RTMP connections, returns a Boolean value of true if a call to methodName is sent to the client; otherwise, false. For application server connections, it always returns true.

Description

Method; invokes a command or method on a Flash Communication Server or an application server to which the application instance is connected. The NetConnection.call method on the server works the same way as the NetConnection.call method on the client: it invokes a command on a remote server.

Note: If you want to call a method on a client from a server, use the Client.call() method.

Example

This example uses RTMP to execute a call from one Flash Communication Server to another Flash Communication Server. The code makes a connection to the App1 application on server 2 and then invokes the method Sum on server 2:

nc1.connect("rtmp://server2.mydomain.com/App1", "svr2",);
nc1.call("Sum", new Result(), 3, 6);

The following server-side ActionScript code is on server 2. When the client is connecting, this code checks to see whether it has an argument that is equal to svr1. If the client has that argument, the Sum method is defined so that when the method is called from svr1, svr2 can respond with the appropriate method:

application.onConnect = function(clientObj){
  if(arg1 == "svr1"){
    clientObj.Sum = function(p1, p2){
      return p1 + p2;
    }
  }
  return true;
};

The following example uses an AMF request to make a call to an application server. This allows Flash Communication Server to connect to an application server and then invoke the quote method. The Java adaptor dispatches the call by using the identifier to the left of the dot as the class name and the identifier to the right of the dot as a method of the class.

nc = new NetConnection;
nc.connect("http://www.xyz.com/java");
nc.call("myPackage.quote", new Result());


NetConnection.close()

Availability

Flash Communication Server MX.

Usage

myNetConnection.close()

Parameters

None.

Returns

Nothing.

Description

Method; closes the connection with the server. After you close the connection, you can reuse the NetConnection instance and reconnect to an old application or connect to a new one.

Note: The NetConnection.close method has no effect on HTTP connections.

Example

The following code closes the NetConnection instance myNetConn:

myNetConn.close();


NetConnection.connect()

Availability

Flash Communication Server MX.

Usage

myNetConnection.connect(URI, [p1, ..., pN])

Parameters

URI A URI to connect to.

p1, ..., pN Optional parameters that can be of any ActionScript type, including references to other ActionScript objects. These parameters are sent as connection parameters to the application.onConnect event handler for RTMP connections. For AMF connections to application servers, any RTMP parameters are ignored.

Returns

For RTMP connections, a Boolean value of true for success; false otherwise. For AMF connections to application servers, true is always returned.

Description

Method; connects to the host. The host URI has the following format:

[protocol://]host[:port]/appName[/instanceName]

For example, the following are legal URIs:

http://appServer.mydomain.com/webApp
rtmp://rtserver.mydomain.com/realtimeApp

It is good practice to write an application.onStatus callback function and check the NetConnection.isConnected property for RTMP connections to see whether a successful connection was made. For Action Message Format connections, check NetConnection.onStatus.

Example

This example creates an RTMP connection to another Flash Communication Server for the myConn instance of NetConnection:

myConn = new NetConnection();
myConn.connect("rtmp://tc.foo.com/myApp/myConn");

The following example creates an AMF connection to an application server for the myConn instance of NetConnection:

myConn = new NetConnection();
myConn.connect("http://www.xyz.com/myApp/");


NetConnection.isConnected

Availability

Flash Communication Server MX.

Usage

myNetConnection.isConnected

Description

Property (read-only); a Boolean value that indicates whether a connection has been made. It is set to true if there is a connection to the server. It's a good idea to check this property value in the onStatus callback function. This property is always true for AMF connections to application servers.

Example

This example uses NetConnection.isConnected inside an onStatus definition to check if a connection has been made:

nc = new NetConnection();
nc.connect("rtmp://tc.foo.com/myApp");
nc.onStatus = function(infoObj){
  if (info.code == "NetConnection.Connect.Success" && nc.isConnected){
    trace("We are connected");
  }
};


NetConnection.onStatus

Availability

Flash Communication Server MX.

Usage

myNetConnection.onStatus = function(infoObject) {
  // Your code here
};

Parameters

infoObject An information object. For details about this parameter, see Server-Side Information Objects.

Returns

Nothing.

Description

Event handler; invoked every time the status of the NetConnection object changes. For example, if the connection with the server is lost in an RTMP connection, the NetConnection.isConnected property is set to false, and NetConnection.onStatus is invoked with a status message of NetConnection.Connect.closed. For AMF connections, NetConnection.onStatus is used only to indicate a failed connection. Use this event handler to check for connectivity.

Example

This example defines a function for the onStatus handler that outputs messages to indicate whether the NetConnection was successful:

nc = new NetConnection();
nc.onStatus = function(info){
  if (info.code == "NetConnection.Connect.Success") {
    _root.gotoAndStop(2);
  }  else {
    if (! nc.isConnected){
      _root.gotoAndStop(1);
    }
  }
};


NetConnection.uri

Availability

Flash Communication Server MX.

Usage

myNetConnection.uri

Description

Property (read-only); A string indicating the URI that was passed by the NetConnection.connect() method. This property is set to null before a call to NetConnection.connect() or after NetConnection.close is called.


setInterval()

Availability

Flash Communication Server MX.

Usage

setInterval(function, interval[, p1, ..., pN]);
setInterval(object, methodName, interval[, p1, ..., pN]);

Parameters

function The name of a defined ActionScript function or a reference to an anonymous function.

object An object derived from the ActionScript Object object.

methodName The name of the method to call on object.

interval The time (interval) between calls to function, in milliseconds.

p1, ..., pN Optional parameters passed to function.

Returns

A unique ID for this call. If the interval is not set, the method returns -1.

Description

Method (global); continually calls a function or method at a specified time interval until the clearInterval() method is called. This method allows a server-side script to run a generic routine. The setInterval method returns a unique ID that you can pass to the clearInterval() method to stop the routine.

Note: Standard JavaScript supports an additional usage for the setInterval method, setInterval(stringToEvaluate, timeInterval), which is not supported by Server-Side Communication ActionScript.

Example

The following example uses an anonymous function to send the message "interval called" to the server log every second:

setInterval(function(){trace("interval called");}, 1000);

The following example also uses an anonymous function to send the message "interval called" to the server log every second, but it passes the message to the function as a parameter:

setInterval(function(s){trace(s);}, 1000, "interval called");

The following example uses a named function, callback1, to send the message "interval called" to the server log:

function callback1(){trace("interval called");
}
setInterval(callback1, 1000);

The following example also uses a named function, callback2, to send the message "interval called" to the server log, but it passes the message to the function as a parameter:

function callback2(s){    trace(s);}
setInterval(callback2, 1000, "interval called");


The SharedObject class

Shared objects let you share data between multiple client applications in real time. Shared objects can be persistent on the server and you can think of these objects as real-time data transfer devices. You can also use the client-side ActionScript SharedObject object to create shared objects on the client. For more information, see the SharedObject entry in the Client-Side Communication ActionScript Dictionary.The following list describes common ways to use remote shared objects:

  • Storing and sharing data on a server

    A shared object can store data on the server for other clients to retrieve. For example, you can open a remote shared object, such as a phone list, that is persistent on the server. Whenever a client makes a change to the shared object, the revised data is available to all clients that are currently connected to the object or that connect to it later. If the object is also persistent locally and a client changes the data while not connected to the server, the changes are copied to the remote shared object the next time the client connects to the object.

  • Sharing data in real time

    A shared object can share data among multiple clients in real time. For example, you can open a remote shared object that stores real-time data (such as a list of users connected to a chat room) that is visible to all clients connected to the object. When a user enters or leaves the chat room, the object is updated and all clients that are connected to the object see the revised list of chat room users.

Every shared object is identified by a unique name and contains a list of name-value pairs, called properties, just like any other ActionScript object. A name must be a unique string and a value can be any ActionScript data type. (For more information about data types, see Using Flash.) All shared objects have a data property. Any property of the data property can be shared and is called a slot.

A shared object can be owned by the current (local) application instance or by a different (remote) application instance. The remote application instance can be on the same server or on a different server. References to shared objects that are owned by a remote application instance are called proxied shared objects.

The slot of a shared object owned by the local instance can be modified by multiple clients or by the server simultaneously; there is no conflict on the server side when a shared object is modified. For example, a call to SharedObject.getProperty returns the latest value and setting a new value assigns a new value for the named slot and updates the object version. If you write a server-side script that modifies multiple properties, you can prevent other clients from modifying the object during the update, by calling the SharedObject.lock() method before updating the object. Then you can call SharedObject.unlock() to commit the changes and allow other changes to be made. Any change to a shared object results in notification to all the clients that are currently subscribed to the shared object.

When you get a reference to a shared object owned by a remote application instance, any changes made to the object are sent to the instance that owns the object. The success or failure of any changes are sent using the SharedObject.onSync event handler, if it is defined. Also, the SharedObject.lock() and SharedObject.unlock() methods cannot be used to lock or unlock proxied shared objects.

Method summary for the SharedObject class

Method | Description
SharedObject.clear() | Deletes all properties of a persistent shared object.
SharedObject.close() | Unsubscribes from a shared object.
SharedObject.flush() | Causes the server to save the current state of a shared object.
SharedObject.get() | Returns a reference to a shared object.
SharedObject.getProperty() | Gets the value of a shared object property.
SharedObject.getPropertyNames() | Returns an array of all the current valid properties in the shared object.
SharedObject.lock() | Locks the shared object instance. Prevents any changes to this object by clients until the SharedObject.unlock() method is called.
SharedObject.purge() | Causes the server to remove all deleted properties that are older than the specified version.
SharedObject.send() | Sends a message to the client subscribing to this shared object.
SharedObject.setProperty() | Sets a new value for a shared object property.
SharedObject.size() | Returns the number of valid properties in a shared object.
SharedObject.unlock() | Unlocks a shared object instance that was locked with SharedObject.lock.

Property summary for the SharedObject class

Property | Description
SharedObject.name | The name of a shared object.
SharedObject.resyncDepth | The depth that indicates when the deleted values of a shared object should be permanently deleted.
SharedObject.version | The current version number of a shared object.

Event summary for the SharedObject class

Property | Description
SharedObject.handlerName | A placeholder for a property name that specifies a function object that is invoked when a shared object receives a broadcast message whose method name matches the property name.
SharedObject.onStatus | Reports errors, warnings, and status messages for a shared object.
SharedObject.onSync | Invoked when a shared object changes.


SharedObject.clear()

Availability

Flash Communication Server MX.

Usage

SharedObject.clear()

Parameters

None.

Returns

Returns true if successful; false otherwise.

Description

Method; deletes all properties and sends a "clear" event to all clients that subscribe to a persistent shared object. The persistent data object is also removed from persistent shared object. You can use SharedObject.clear to detach from a shared object immediately after SharedObject.get is invoked. You can use SharedObject.clear when you do not want to use a shared object anymore and want to remove it from the server completely. This method lets you create shared objects that persist only for a specified time.

Example

The following example calls the clear method on the shared object myShared:

var myShared = SharedObject.get("foo", true);
var len = myShared.clear();


SharedObject.close()

Availability

Flash Communication Server MX.

Usage

SharedObject.close()

Parameters

None.

Returns

Nothing.

Description

Method; detaches a reference from a shared object. A call to the SharedObject.get method returns a reference to a shared object instance. The reference is valid until the variable that holds the reference is no longer in use and the script is garbage-collected. To destroy a reference immediately, you can call SharedObject.close. You can use SharedObject.close when you don't want to proxy a shared object any longer.

Example

In this example, mySO is attached as a reference to shared object foo. When you call mySO.close you detach the reference mySO from the shared object foo.

mySO = SharedObject.get("foo");
  // insert code here
mySO.close();

See also

SharedObject.get()


SharedObject.flush()

Availability

Flash Communication Server MX.

Usage

SharedObject.flush()

Parameters

None.

Returns

A Boolean value of true if successful, false otherwise.

Description

Method; causes the server to save the current state of the shared object instance. The shared object must have been created with the persistence option.

Example

The following example places a reference to the shared object foo in the variable myShared. It then locks the shared object instance so that no one can make any changes to it, and then saves the shared object by calling myShared.flush. After the shared object is saved, it is unlocked so that further changes can be made.

var myShared = SharedObject.get("foo", true);
myShared.lock();
// insert code here that operates on the shared object
myShared.flush();
myShared.unlock();


SharedObject.get()

Availability

Flash Communication Server MX.

Usage

SharedObject.get(name, persistence [, netConnection])

Parameters

name Name of the shared object instance to return.

persistence A Boolean value: true for a persistent shared object; false for a nonpersistent shared object. If no value is specified, the default value is false.

netConnection A NetConnection object that represents a connection to an application instance. You can pass this parameter to get a reference to a shared object on another server or a shared object that is owned by another application instance. All update notifications for the shared object specified by the name parameter are proxied to this instance, and the remote instance notifies the local instance when a persistent shared object changes. The NetConnection object that is used as the netConnection parameter does not need to be connected when you call SharedObject.get. The server connects to the remote shared object when the NetConnection state changes to connected. This parameter is optional.

Returns

A reference to a shared object instance.

Description

Static method; returns a reference to a shared object instance. To perform any operation on a shared object, the server-side script must get a reference to the named shared object using the SharedObject.get() method. If the object requested is not found, a new instance is created.

There are two types of shared objects, persistent and nonpersistent, and they are in separate name spaces. This means that a persistent and a local shared object can have the same name, but they are two distinct shared objects. Shared objects are scoped to the name space of the application instance and are identified by a string name. The shared object names should conform to the URI specification.

You can also call SharedObject.get to get a reference to a shared object that is in a name space of another application instance. This instance can be on the same server or on a different server and is called a proxied shared object. To get a reference to a shared object from another instance, create a NetConnection object and use the NetConnection.connect() method to connect to the application instance that owns the shared object. Pass the NetConnection object as the netConnection parameter of the SharedObject.get method. The server-side script must get a reference to a proxied shared object before there is a request for the shared object from any client. To do this, call SharedObject.get in the application.onAppStart handler.

If you call SharedObject.get with a netConnection parameter and the local application instance already has a shared object with the same name, the shared object converts to a proxied shared object. All shared object messages for clients connected to a proxied shared object are sent to the master instance.

If the connection state of the NetConnection object that was used as the netConnection parameter changes state from connected to disconnected, the proxied shared object is set to idle and any messages received from subscribers are discarded. The NetConnection.onStatus handler is called when a connection is lost. You can then re-establish a connection to the remote instance and call SharedObject.get, which changes the state of the proxied shared object from idle to connected.

If you call SharedObject.get with a new NetConnection object on a proxied shared object that is already connected and if the URI of the new NetConnection object doesn't match the current NetConnection object, the proxied shared object unsubscribes from the previous shared object, sends a "clear" event to all subscribers, and subscribes to the new shared object instance. When a subscribe to a proxied shared object is successful, all subscribers are reinitialized to the new state. This process lets you migrate a shared object from one application instance to another without disconnecting the clients.

Updates received by proxied shared objects from subscribers are checked to see if the update can be rejected based on the current state of the proxied shared object version and the version of the subscriber. If the change can be rejected, the proxied shared object doesn't forward the message to the remote instance; the reject message is sent to the subscriber.

The corresponding client-side ActionScript method is SharedObject.getRemote.

Example

This example creates a shared object named foo inside the function onProcessCmd. The function is passed a parameter, cmd, that is assigned to a property in the shared object.

function onProcessCmd(cmd){
  // insert code here
  var shObj = SharedObject.get("foo", true);
  propName = cmd.name;
  shObj.getProperty (propName, cmd.newAddress);
}

The following example uses a proxied shared object. A proxied shared object resides on a server or in an application instance (called master) that is different than the server or application instance that the client connects to (called proxy). When the client connects to the proxy and gets a remote shared object, the proxy connects to the master and gives the client a reference to this shared object. The following code is in the main.asc file:

application.appStart = function() {
     nc = new NetConnection();
     nc.connect("rtmp://" + master_server + "/" + master_instance);
     proxySO = SharedObject.get("myProxy",true,nc);
    // Now, whenever the client asks for a persistent
    // shared object called myProxy they will receive myProxy
    // shared object from the master_server/master_instance
};


SharedObject.getProperty()

Availability

Flash Communication Server MX.

Usage

mySharedObject.getProperty(name)

Parameters

name The name of the property in the shared object.

Returns

The value of a SharedObject property.

Description

Method; retrieves the value of a named property in a shared object. The returned value is a copy associated with the property, and any changes made to the returned value do not update the shared object. To update a property, use the SharedObject.setProperty() method.

Example

The following example gets the value of the name property and passes it to the value variable:

value = sharedInfo.getProperty(name);

See also

SharedObject.setProperty()


SharedObject.getPropertyNames()

Availability

Flash Communication Server MX.

Usage

mySharedObject.getPropertyNames()

Parameters

None.

Returns

An array containing all the property names of a shared object.

Description

Method; enumerates all the property names for a given shared object. This method returns an array of strings that refer to the current properties.

Example

This example calls getPropertyNames on the myInfo shared object and places the names into the names variable. It then enumerates those property names in a for loop.

myInfo = SharedObject.get("foo");
var addr = myInfo.getProperty("address");
myInfo.setProperty("city", San Francisco");
var names = myInfo.getPropertyNames();
for (x in names){
  var propVal = myInfo.getProperty(names[x]);
  trace("Value of property " + names[x] + " = " + propVal);
}


SharedObject.handlerName

Availability

Flash Communication Server MX.

Usage

SharedObject.onBroadcastMsg = function([p1,..., pN]){
  // insert code here
};

Parameters

p1, ..., pN Optional parameters passed to the handler method if the message contains user-defined parameters. These parameters are the user-defined JavaScript objects passed to the SharedObject.send method.

Returns

Any return value is ignored by the server.

Description

Event handler; a placeholder for a property name (onBroadcastMsg in the Usage example above) that specifies a function object that is invoked when the shared object receives a broadcast message whose method name matches the property name.

The this keyword used in the body of the function is set to the shared object instance returned by SharedObject.get.

If you don't want the server to receive a particular broadcast message, do not define this handler.

Example

The following example defines a function called broadcastMsg:

var mySO = SharedObject.get("userList", false);
mySO.broadcastMsg = function(msg1, msg2){
    trace(msg1 + " : " + msg2);
};


SharedObject.lock()

Availability

Flash Communication Server MX.

Usage

SharedObject.lock()

Parameters

None.

Returns

An integer indicating the lock count: 0 or greater indicates success; -1 indicates failure. For proxied shared objects, always returns -1.

Description

Method; locks the shared object instance. This method gives the server-side script exclusive access to the shared object; when the SharedObject.unlock() method is called, all changes are batched and one update message is sent to all the clients subscribed to this shared object. If you nest the SharedObject.lock() and SharedObject.unlock() methods, make sure there is an unlock for every lock; otherwise, clients are blocked from accessing the shared object.

You cannot use the SharedObject.lock method on proxied shared objects.

Example

This example locks the myShared shared object, executes the code that is to be inserted, and then unlocks the object:

var myShared = SharedObject.get("foo");
myShared.lock();
// insert code here that operates on the shared object
myShared.unlock();


SharedObject.name

Availability

Flash Communication Server MX.

Usage

SharedObject.name

Description

Property (read-only); the name of a shared object.

Example

This example outputs foo to the NetConnection Debugger:

mySO = SharedObject.get("foo");
trace(mySO.name);


SharedObject.onStatus

Availability

Flash Communication Server MX.

Usage

SharedObject.onStatus = function(info) {
  // insert code here
};

Parameters

info An information object. For more information, see the Appendix, "Client-Side Information Objects," in the Client-Side Communication ActionScript Dictionary.

Returns

Nothing.

Description

Event handler; reports errors, warnings, and status messages associated with either a local instance of a shared object or a persistent shared object.

Example

The following example defines an onStatus event handler for the shared object soInstance:

soInstance = SharedObject.get("foo", true);
soInstance.onStatus = function(infoObj){
  //Handle SO status messages
};


SharedObject.onSync

Availability

Flash Communication Server MX.

Usage

SharedObject.onSync = function(list){
  return;
};

Parameters

list An array of objects that contain information about the properties of a shared object that have changed since the last time the onSync method was called. The notifications for proxied shared objects are different than for shared objects that are owned by the local application instance. The following tables list the descriptions for each type of shared object.

Local shared objects

Code | Meaning
change | A property was changed by a subscriber.
delete | A property was deleted by a subscriber.
name | The name of a property that has changed or been deleted.
oldValue | The old value of a property. This is true for both change and delete messages; on the client, oldValue is not set for delete.

Note: Changing or deleting a property on the server side using the SharedObject.setProperty() method always succeeds, so there is no notification of these changes.

Proxied shared objects

Code | Meaning
success | A server change of the shared object was accepted.
reject | A server change of the shared object was rejected. The value on the remote instance was not changed.
change | A property was changed by another subscriber.
delete | A property was deleted. This notification can occur when a server deletes a shared object or if another subscriber deletes a property.
clear | All the properties of a shared object are deleted. This can happen when the server's shared object is out of sync with the master shared object or when the persistent shared object migrates from one instance to the other. This event is typically followed by a change message to restore all the server's shared object properties.
name | The name of a property that has changed or been deleted.
oldValue | The old value of the property. This is only valid for the reject, change and delete codes.

Note: The SharedObject.onSync method is called when a shared object has been successfully synchronized with the server. The list object may be empty if there is no change in the shared object.

Returns

Nothing.

Description

Event handler; invoked when a shared object changes. You should set this method to point to a function you define in order to receive notification of changes made by other subscribers for shared objects owned by the local application instance. You should also set this method to get the status of changes made by the server as well as by other subscribers for proxied shared objects.

Example

The following example creates a function that is invoked whenever a property of the shared object so changes:

// create a new NetConnection object
nc = new NetConnection();
nc.connect("rtmp://server1.xyx.com/myApp");
// create the shared object
so = SharedObject.get("MasterUserList", true, nc);
// the list parameter is an array of objects containing information
// about successfully of unsuccessfully changed properties
// from the last time onSync() was called
so.onSync = function(list) {
  for (var i = 0; i < list.length; i++) {
    switch (list[i].code ) {
      case "success":
        trace ("success");
        break;
      case "change":
        trace ("change");
        break;
      case "reject":
        trace ("reject");
        break;
      case "delete":
        trace ("delete");
        break;
      case "clear":
        trace ("clear");
        break;
    }
  }
};


SharedObject.purge()

Availability

Flash Communication Server MX.

Usage

SharedObject.purge(version)

Parameters

version A version number. All deleted data that is older than this version is removed.

Returns

Nothing.

Description

Method; causes the server to purge all deleted properties that are older than the specified version. Although you can also accomplish this task by setting the SharedObject.resyncDepth property, the SharedObject.purge() method gives the script more control over which properties to delete.

Example

This example deletes all properties of the myShared shared object that are older than the value of SharedObject.version - 3.

var myShared = SharedObject.get("foo", true);
myShared.lock();
myShared.purge(myShared.version - 3);
myShared.unlock();


SharedObject.resyncDepth

Availability

Flash Communication Server MX.

Usage

SharedObject.resyncDepth

Description

Property; an integer that indicates when the deleted properties of a shared object should be permanently deleted. You can use this property in a server-side script to resynchronize shared objects and to control when shared objects are deleted. The default value is infinity.

If the current revision number of the shared object minus the revision number of the deleted property is greater than the value of SharedObject.resyncDepth, the property is deleted. Also, if a client connecting to this shared object has a client revision that, when added to the value of SharedObject.resyncDepth is less than the value of the current revision on the server, all the current elements of the client shared object are deleted, the valid properties are sent to the client and the client receives a "clear" message.

This method is useful when you add and delete many properties and you don't want to send too many messages to the Flash client. Suppose a client is connected to a shared object that has 12 properties and then disconnects. After that client disconnects, other clients that are connected to the shared object delete 20 properties and add 10 properties. When the client reconnects, it could, for example, receive a delete message for the 10 properties it previously had and then a change message on two properties. You could use SharedObject.resyncDepth to send a "clear" message, followed by a change message for two properties, which saves the client from receiving 10 delete messages.

Example

The following example resynchronizes the shared object mySO if the revision number difference is greater than 10:

mySo = SharedObject.get("foo");
mySo.resyncDepth = 10;


SharedObject.send()

Availability

Flash Communication Server MX.

Usage

SharedObject.send(methodName, [p1, ..., pN])

Parameters

methodName The name of a method on a client shared object instance. For example, if you specify doSomething, the client must invoke the SharedObject.doSomething method, with all the p1, ..., pN parameters.

p1, ..., pN Parameters of any ActionScript type, including references to other ActionScript objects. These parameters are passed to the specified methodName when it executes on the Flash client.

Returns

A Boolean value of true if the message was sent to the client; false otherwise.

Description

Method; executes a method in a client-side script. You can use SharedObject.send() to asynchronously execute a method on all the Flash clients subscribing to a shared object. The server does not receive any notification from the client on the success, failure, or return value in response to this message.

Example

This example calls the SharedObject.send method to execute the doSomething method in the client-side ActionScript and passes doSomething the string "this is a test".

var myShared = SharedObject.get("foo", true);
myShared.send("doSomething", "this is a test");

The following example is the client-side ActionScript code that defines the doSomething method:

connection = new NetConnection();
connection.connect("rtmp://www.macromedia.com/someApp");
var x = SharedObject.getRemote("foo", connection.uri, true);
x.connect(connection);
x.doSomething = function(str) {
// process the str
};


SharedObject.setProperty()

Availability

Flash Communication Server MX.

Usage

sharedInfo.setProperty(name, value);

Parameters

name The name of the property in the shared object.

value An ActionScript object associated with the property, or null to delete the property.

Returns

Nothing.

Description

Method; updates the value of a property in a shared object. A shared object property can be modified by another user of the shared object between successive calls to SharedObject.getProperty() and SharedObject.setProperty(). If you want to preserve transactional integrity, call the SharedObject.lock() method before operating on the shared object; make sure to call SharedObject.unlock() when the operations finish. If you don't call SharedObject.lock() and the SharedObject.setProperty() is called, the change is made to the shared object, and all subscribers of the object are notified before SharedObject.setProperty() returns. If a call to the SharedObject.lock() method precedes a call to SharedObject.setProperty(), all changes are batched and sent when the SharedObject.unlock() method is called.

If you call SharedObject.setProperty on the server side, it invokes a change message in the SharedObject.onSync method on the client side for any Flash Player client that is using the shared object. The name parameter on the server side is the same as an attribute of the data property on the client side. For example, the following two lines of code are equivalent: the first line is server-side ActionScript, and the second is client-side ActionScript:

sharedInfo.setProperty(nameVal, "foo");
clientSO.data[nameVal] = "foo";

Example

This example uses the SharedObject.setProperty method to create the property city with the value San Francisco. It then enumerates all the property values in a for loop and prints out the results in the Output panel by using a trace action.

myInfo = SharedObject.get("foo");
var addr = myInfo.getProperty("address");
myInfo.setProperty("city", "San Francisco");
var names = sharedInfo.getPropertyNames();
for (x in names){
  var propVal = sharedInfo.getProperty(names[x]);
  trace("Value of property " + names[x] + " = " + propVal);
}

See also

SharedObject.getProperty()


SharedObject.size()

Availability

Flash Communication Server MX.

Usage

mySharedObject.size()

Parameters

None.

Returns

An integer indicating the number of properties.

Description

Method; returns the total number of valid properties in a shared object.

Example

This example gets the number of properties of a shared object and assigns that number to the variable len:

var myShared = SharedObjecd.get(application, "foo", true);
var len = myShared.size();


SharedObject.unlock()

Availability

Flash Communication Server MX.

Usage

mySharedObject.unlock()

Parameters

None.

Returns

An integer indicating the lock count: 0 or greater if successful, -1 otherwise. For proxied shared objects, this method always returns -1.

Description

Method; unlocks a shared object instance. This causes the script to relinquish exclusive access to the shared object and lets other clients update the instance. This method also causes the server to commit all changes made after the SharedObject.lock() method is called and sends an update message to all clients.

You cannot use the SharedObject.unlock method on proxied shared objects.

Example

This example illustrates how easy it is to unlock a shared object.

var myShared = SharedObject.get("foo", true);
myShared.lock();
// insert code to manipulate the shared object
myShared.unlock();

See also

SharedObject.lock()


SharedObject.version

Availability

Flash Communication Server MX.

Usage

SharedObject.version

Description

Property (read-only); the current version number of the shared object. Changes made to the shared object either by the Flash Player client or by the server-side script using the SharedObject.setProperty method increment the value of the version property.


The Stream class

The Stream class lets you handle each stream in a Flash Communication Server application. A stream is a one-way connection between Flash Player and Flash Communication Server, or between two servers. Flash Communication Server automatically creates a Stream object with a unique name when NetStream.play or NetStream.publish are called in a client-side script. You can also create a stream in server-side ActionScript by calling Stream.get(). A user can access multiple streams at the same time, and there can be hundreds or thousands of Stream objects active at the same time.

You can use the properties and methods of the Stream class to shuffle streams in a playlist, pull streams from other servers, and play and record streams.

You can also use the Stream class to play MP3 files over a stream, as well as ID3 tags associated with MP3 files.

You can create other Stream properties of any legal ActionScript type, including references to other ActionScript objects, for a particular instance of the Stream class. The properties are available until the stream is removed from the application.

For more information about streams, see the NetStream class entry in the Client-Side Communication ActionScript Dictionary.

Property summary for the Stream class

Property (read-only) | Description
Stream.bufferTime | Indicates how long to buffer messages before a stream is played.
Stream.name | The unique name of a live stream.

Method summary for the Stream class

Method | Description
Stream.clear() | Deletes a stream previously recorded by the server.
Stream.get() | Returns a reference to a Stream object. This is a static method.
Stream.length() | Returns the length of a recorded stream in seconds. This is a static method.
Stream.play() | Controls the data source of the Stream object.
Stream.record() | Records all the data going into the stream.
Stream.send() | Sends a call with parameters to all subscribers on a stream.
Stream.setBufferTime() | Sets the length of the buffer time in seconds.

Event handler summary for the Stream class

Event handler | Description
Stream.onStatus | Called when there is a change in status.


Stream.bufferTime

Availability

Flash Communication Server MX.

Usage

Stream.bufferTime

Description

Property (read-only); indicates how long to buffer messages before a stream is played. This property applies only when playing a stream from a remote server or when playing a recorded stream locally. To set this property use Stream.setBuffertime.

A message is data that is sent back and forth between Flash Communication Server and Flash Player. The data is divided into small packets (messages), and each message has a type (audio, video, or data).

See also

Stream.setBufferTime()


Stream.clear()

Availability

Flash Communication Server MX.

Usage

Stream.clear()

Parameters

None.

Returns

A Boolean value of true if the call succeeds, false otherwise.

Description

Method; deletes a recorded stream file (FLV) from the server.

Example

This example deletes a recorded stream called foo.flv. Before the stream is deleted, the example defines an onStatus handler that uses two information object error codes, NetStream.Clear.Success and NetStream.Clear.Failed, to send status messages to the Output panel.

s = Stream.get("foo");
if (s){
  s.onStatus = function(info){
    if(info.code == "NetStream.Clear.Success"){
      trace("Stream cleared successfully.");
    }
    if(info.code == "NetStream.Clear.Failed"){
      trace("Failed to clear stream.");
    }
  };
  s.clear();
}

Note: The Stream information object is nearly identical to the client-side ActionScript NetStream information object. For more information, see Server-Side Information Objects.

See also

Stream.get()


Stream.get()

Availability

Flash Communication Server MX.

Usage

Stream.get(name)

Parameters

name The name of the stream instance to return.

Returns

A reference to a stream instance.

Description

Method (static); returns a reference to a Stream object. If the requested object is not found, a new instance is created.

Examples

This example gets the stream foo and assigns it to the variable playStream. It then calls the Stream.play method from playStream.

function onProcessCmd(cmd){
  var playStream = Stream.get("foo");
  playStream.play("file1", 0, -1);
}

See also

Stream.clear()


Stream.length()

Availability

Flash Communication Server MX.

Usage

Stream.length(name)

Parameters

name Name of a recorded stream (FLV) file or MP3 file. To get the length of an MP3 file, precede the name of the file with mp3: (for example, "mp3:beethoven").

Returns

The length of a recorded stream file or MP3 file in seconds.

Description

Method (static); returns the length of a recorded stream file or MP3 file in seconds. If the requested file is not found, the return value is 0.

Example

This example gets the length of the recorded stream file myVideo and assigns it to the variable streamLen:

function onProcessCmd(cmd){
  var streamLen = Stream.length("myVideo");
  trace("Length: " + streamLen + "\n");
}

This example gets the length of the MP3 file beethoven.mp3 and assigns it to the variable streamLen:

function onProcessCmd(cmd){
  var streamLen = Stream.length("mp3:beethoven");
  trace("Length: " + streamLen + "\n");
}


Stream.name

Availability

Flash Communication Server MX.

Usage

Stream.name

Description

Property (read-only); contains a unique string associated with a live stream.

You can also use this as an index to find a stream within an application.

Example

The following function, getStreamName, takes a stream reference as an argument, myStream, and returns the name of the stream associated with it.

function getStreamName (myStream) {
  return myStream.name;
}


Stream.onStatus

Availability

Flash Communication Server MX.

Usage

myStream.onStatus = function([infoObject]) {
  // Insert code here
};

Parameters

infoObject An optional parameter defined according to the status message. For details about this parameter, see Server-Side Information Objects.

Returns

Nothing.

Description

Event handler; invoked every time the status of a Stream object changes. For example, if you play a file in a stream, Stream.onStatus is invoked. Use Stream.onStatus to check when play starts and ends, when recording starts, and so on.

Example

This example defines a function that executes whenever the Stream.onStatus event is invoked:

s = Stream.get("foo");
s.onStatus = function(info){
    // insert code here
};


Stream.play()

Availability

Flash Communication Server MX.

Usage

Stream.play(streamName, [startTime, length, reset, remoteConnection])

Parameters

streamName The name of any published live stream, recorded stream (FLV file), or MP3 file.

To play back FLV files, the default Flash file format for recorded streams, specify the name of the stream (for example, "myVideo"). To play back MP3 files that you've stored on the server, or the ID3 tags of MP3 files, you must precede the stream name with mp3: or id3: (for example, "mp3:bolero" or "id3:bolero"). For more information on playing MP3 files, see Developing Communication Applications.

startTime The start time of the stream playback, in seconds. If no value is specified, it is set to -2. If startTime is -2, the server tries to play a live stream with the name specified in streamName. If no live stream is available, the server tries to play a recorded stream with the name specified in streamName. If no recorded stream is found, the server creates a live stream with the name specified in streamName and waits for someone to publish to that stream. If startTime is -1, the server attempts to play a live stream with the name specified in streamName and waits for a publisher if no specified live stream is available. If startTime is greater than or equal to 0, the server plays the recorded stream with the name specified in streamName, starting from the time given. If no recorded stream is found, the play method is ignored. If a negative value other than -1 is specified, the server interprets it as -2. This is an optional parameter.

length The length of play, in seconds. For a live stream, a value of -1 plays the stream as long as the stream exists. Any positive value plays the stream for the corresponding number of seconds. For a recorded stream, a value of -1 plays the entire file, and a value of 0 returns the first video frame. Any positive number plays the stream for the corresponding number of seconds. By default, the value is -1. This is an optional parameter.

reset A Boolean value, or number, that flushes the playing stream. If reset is false (0), the server maintains a playlist, and each call to Stream.play is appended to the end of the playlist so that the next play does not start until the previous play finishes. You can use this technique to create a dynamic playlist. If reset is true (1), any playing stream stops, and the playlist is reset. By default, the value is true.

You can also specify a number value of 2 or 3 for the reset parameter, which is useful when playing recorded stream files that contain message data. These values are analogous to false (0) and true (1), respectively: a value of 2 maintains a playlist, and a value of 3 resets the playlist. However, the difference is that specifying either 2 or 3 for reset returns all messages in the specified recorded stream at once, rather than at the intervals which the messages were originally recorded (the default behavior).

For more information on Flash Communication Server logging see TechNote 16464 on the Macromedia Flash Communication Server Support Center.

remoteConnection A reference to a NetConnection object that is used to connect to a remote server. The requested stream plays from the remote server if this parameter is provided. This parameter is optional.

Returns

A Boolean value: true if the Stream.play call is accepted by the server and added to the playlist; false otherwise. The Stream.play method can fail if the server fails to find the stream or if an error occurs. To get information about the Stream.play call, you can define a Stream.onStatus handler to catch the play status or error.

If the streamName parameter is false, the stream stops playing. A Boolean value of true is returned if the stop succeeds; false otherwise.

Description

Method; controls the data source of a stream with an optional start time, duration, and reset flag to flush any previously playing stream. The Stream.play() method also has a parameter that lets you reference a NetConnection object to play a stream from another server. The Stream.play() method allows you to do the following:

  • Chain streams between servers.
  • Create a hub to switch between live streams and recorded streams.
  • Combine different steams into a recorded stream.

You can combine multiple streams to create a playlist for clients. The server-side Stream.play() method behaves a bit differently than the NetStream.play method on the client side. A play call on the server is similar to a publish call on the client. It controls the source of the data that is coming into a stream. When you call Stream.play on the server, the server becomes the publisher. Because the server has a higher priority than the client, the client is forced to unpublish from the stream if the server calls a play method on the same stream.

In general, if any recorded streams are included in a server playlist, you cannot play the server stream as a live stream.

Note: A stream that plays from a remote server by means of the NetConnection object is a live stream.

If you require a value to begin a stream, you may need to change the Application.xml file's "Enhanced seeking" flag at the server. "Enhanced seeking" is a Boolean flag in the Application.xml file. By default, this flag is set to false. When a play occurs, the server seeks to the closest video keyframe possible and starts from that keyframe. For example, if you want to play at time 15, and there are keyframes only at time 11 and time 17, seeking will start from time 17 instead of time 15. This is an approximate seeking method that works well with compressed streams.

If the flag is set to true, some compression is invoked on the server. Using the previous example, if the flag is set to true, the server creates a keyframe—based on the preexisting keyframe at time 11—for each keyframe from 11 through 15. Even though a keyframe does not exist at the seek time, the server generates a keyframe, which involves some processing time on the server.

Example

This example illustrates how streams can be chained between servers:

application.myRemoteConn = new NetConnection();
application.myRemoteConn.onStatus = function(info){
  trace("Connection to remote server status " + info.code + "\n");
  // tell all the clients
  for (var i = 0; i < application.clients.length; i++){
    application.clients[i].call("onServerStatus", null,
    info.code, info.description);
  }
};
// Use the NetConnection object to connect to a remote server
application.myRemoteConn.connect(rtmp://movie.com/movieApp);
// Setup the server stream
application.myStream = Stream.get("foo");
if (application.myStream){
  application.myStream.play("Movie1", 0, -1, true, application.myRemoteConn);
}

The following example shows Stream.play used as a hub to switch between live streams and recorded streams:

// Set up the server stream
application.myStream = Stream.get("foo");
if (application.myStream){
  // this server stream will play "Live1",
  // "Record1", and "Live2" for 5 seconds each
  application.myStream.play("Live1", -1, 5);
  application.myStream.play("Record1", 0, 5, false);
  application.myStream.play("Live2", -1, 5, false);
}

The following example combines different streams into a recorded stream:

// Set up the server stream
application.myStream = Stream.get("foo");
if (application.myStream){
  // Like the previous example, this server stream
  // will play "Live1", "Record1", and "Live2"
  // for 5 seconds each. But this time,
  // all the data will be recorded to a recorded stream "foo".
  application.myStream.record();
  application.myStream.play("Live1", -1, 5);
  application.myStream.play("Record1", 0, 5, false);
  application.myStream.play("Live2", -1, 5, false);
}

The following example uses Stream.play to stop playing the stream foo:

application.myStream.play(false);

The following example creates a playlist of three MP3 files (beethoven.mp3, mozart.mp3, and chopin.mp3) and plays each file in turn over the live stream foo:

application.myStream = Stream.get("foo");
if(application.myStream) {
  application.myStream.play("mp3:beethoven", 0);
  application.myStream.play("mp3:mozart", 0, false);
  application.myStream.play("mp3:chopin.mp3", 0, false);
}

In the following example, data messages in the recorded stream file log.flv are returned at the intervals which they were originally recorded.

application.myStream = Stream.get("data");
if (application.myStream) {
  application.myStream.play("log", 0, -1);
}

In the following example, data messages in the recorded stream file log.flv are returned all at once, rather than at the intervals which they were originally recorded.

application.myStream = Stream.get("data");
if (application.myStream) {
  application.myStream.play("log", 0, -1, 2);
}


Stream.record()

Availability

Flash Communication Server MX.

Usage

Stream.record(flag)

Parameters

flag This parameter can have the value record, append, or false. If the value is record, the data file is overwritten if it exists. If the value is append, the incoming data is appended to the end of the existing file. If the value is false, any previous recording stops. By default, the value is record.

Returns

A Boolean value of true if the recording succeeds, false otherwise.

Description

Method; records all the data going through a Stream object.

Example

This example opens a stream s and, when it is open, plays sample and records it. Because no value is passed to the record method, the default value, record, is passed.

// To start recording
s = Stream.get("foo");
if (s){
  s.play("sample");
  s.record();
}
// To stop recording
s = Stream.get("foo");
if (s){
  s.record(false);
}


Stream.send()

Availability

Flash Communication Server MX.

Usage

Stream.send(handlerName, [p1, ..., pN])

Parameters

handlerName Calls the specified handler in client-side ActionScript code. The handlerName value is the name of a method relative to the subscribing Stream object. For example, if handlerName is doSomething, the doSomething method at the stream level is invoked with all the p1, ..., pN parameters. Unlike the method names in Client.call() and NetConnection.call(), the handler name can be only one level deep (that is, it cannot be of the form object/method).

Note: Do not use a built-in method name for a handler name. For example, the subscribing stream will be closed if the handler name is close.

p1, ..., pN Parameters of any ActionScript type, including references to other ActionScript objects. These parameters are passed to the specified handler when it is executed on the Flash client.

Returns

A Boolean value of true if the message was sent to the client, false otherwise.

Description

Method; sends a message to all clients subscribing to the stream and the message is processed by the handler specified on the client. Because the server has higher priority than the clients, the server can still send a message on a stream owned by a client. Unlike the Stream.play() method, the server does not need to take ownership of a stream from the client in order to send a message. After send() is called, the client still owns the stream as a publisher.

Example

This example calls the method Test on the client-side Stream object and sends it the string "hello world":

application.streams["foo"].send("Test", "hello world");

The following example is the client-side ActionScript that receives the Stream.send call. The method Test is defined on the Stream object:

tStream.Test = function(str) {
  // insert code to process the str
}


Stream.setBufferTime()

Availability

Flash Communication Server MX.

Usage

Stream.setBufferTime()

Description

Method; increases the message queue length. When you play a stream from a remote server, the Stream.setBufferTime method sends a message to the remote server that adjusts the length of the message queue. The default length of the message queue is 2 seconds. You should set the buffer time higher when playing a high-quality recorded stream over a low-bandwidth network.

When a user clicks a seek button in an application, buffered packets are sent to the server. The buffered seeking in a Flash Communication Server application occurs on the server; the Flash Communication Server doesn't support client-side buffering. The seek time can be smaller or larger than the buffer size, and it has no direct relationship to the buffer size. Every time the server receives a seek request from Flash Player, it clears the message queue on the server. The server tries to seek to the desired position and starts filling the queue again. At the same time, Flash Player also clears its own buffer after a seek request, and the buffer is eventually filled after the server starts sending the new messages.


trace()

Availability

Flash Communication Server MX.

Usage

trace("Hello world");
trace("Value of i = " + i);

Returns

Nothing.

Description

Method (global); displays the value of an expression in the Output panel. The trace message is also published to the logs/application appname stream, which is available in the Administration Console or in the Communication App inspector. The values in the trace expression are converted to strings if possible before they are sent to the Output panel. You can use the trace method to debug a script.


Server-side information objects overview

The Application, NetConnection, and Stream classes provide an onStatus event handler that uses an information object for providing information, status, or error messages. To respond to this event handler, you must create a function to process the information object, and you must know the format and contents of the information object returned.

You can define the following global function at the top of your main.asc file to display all the status messages for the parameters that you pass to the function. You need to place this code in the main.asc file only once.

function showStatusForClass(){
  for (var i=0;i<arguments.length;i++){
    arguments[i].prototype.onStatus = function(infoObj){
    trace(infoObj.code + " (level:" + infoObj.level + ")");
  }
}
showStatusForClass(NetConnection, Stream);

For more information about information objects, see the appendix of the Client-Side Communication ActionScript Dictionary.

An information object has the following properties: level, code, description, and details. All information objects have level and code properties, but only some have the description and/or details properties. The following tables list the code and level properties as well as the meaning of each information object.


Application information objects

The following table lists the information objects for the Application object.

Code

Level

Meaning

Application.Script.Error

Error

The ActionScript engine has encountered a runtime error.

In addition to the standard infoObject properties, the following properties are set:

filename: name of the offending ASC file.lineno: line number where the error occurred.linebuf: source code of the offending line.

Application.Script.Warning

Warning

The ActionScript engine has encountered a runtime warning.

In addition to the standard infoObject properties, the following properties are set:

filename: name of the offending ASC file.lineno: line number where the error occurred.linebuf: source code of the offending line.

Application.Resource.LowMemory

Warning

The ActionScript engine is low on runtime memory. This provides an opportunity for the application instance to free some resources or take suitable action.

If the application instance runs out of memory, it is unloaded and all users are disconnected. In this state, the server will not invoke the Application.onDisconnect event handler or the Application.onAppStop event handler.

Application.Shutdown

Status

This information object is passed to the onAppStop handler when the application is being shut down.

Application.GC

Status

This information object is passed to the onAppStop event handler when the application instance is about to be destroyed by the server.


NetConnection information objects

The NetConnection class has the same information objects as the client-side NetConnection class.

Code | Level | Meaning
NetConnection.Call.Failed | Error | The NetConnection.call method was not able to invoke the server-side method or command.*
NetConnection.Connect.AppShutdown | Error | The application has been shut down (for example, if the application is out of memory resources and must shut down to prevent the server from crashing) or the server has shut down.
NetConnection.call.BadVersion | Error | The URI specified in the NetConnection.connect method did not specify "rtmp" as the protocol. "rtmp" must be specified when connecting to Flash Communication Server.
NetConnection.Connect.Closed | Status | The connection was closed successfully.
NetConnection.Connect.Failed | Error | The connection attempt failed.
NetConnection.Connect.InvalidApp | Error | The application name specified during the connection attempt was not found on the server.
NetConnection.Connect.Rejected | Error | The client does not have permission to connect to the application, or the application expected different parameters from those that were passed.**
NetConnection.Connect.Success | Status | The connection attempt succeeded.

*This information object also has a description property, which is a string that provides a specific reason for the failure.

**This information object also has an application property, which contains the value that the application.rejectConnection server-side method returns.


Stream information objects

The information objects of the Stream class are similar to those of the client-side NetStream class.

Code | Level | Meaning
NetStream.Clear.Success | Status | A recorded stream was deleted successfully.
NetStream.Clear.Failed | Error | A recorded stream failed to delete.
NetStream.Publish.Start | Status | An attempt to publish was successful.
NetStream.Publish.BadName | Error | An attempt was made to publish a stream that is already being published by someone else.
NetStream.Failed | Error | An attempt to use a Stream method failed.*
NetStream.Unpublish.Success | Status | An attempt to unpublish was successful.
NetStream.Record.Start | Status | Recording was started.
NetStream.Record.NoAccess | Error | An attempt was made to record a read-only stream.
NetStream.Record.Stop | Status | Recording was stopped.
NetStream.Record.Failed | Error | An attempt to record a stream failed.
NetStream.Play.Start | Status | Play was started.**
NetStream.Play.StreamNotFound | Error | An attempt was made to play a stream that does not exist.
NetStream.Play.Stop | Status | Play was stopped.
NetStream.Play.Failed | Error | An attempt to play back a stream failed.* **
NetStream.Play.Reset | Status | A playlist was reset.
NetStream.Play.PublishNotify | Status | The initial publish to a stream was successful. This message is sent to all subscribers.
NetStream.Play.UnpublishNotify | Status | An unpublish from a stream was successful. This message is sent to all subscribers.

*This information object also has a description property, which is a string that provides a specific reason for the failure.

**This information object also has a details property, which is a string that provides the name of the streams being played. This is useful for multiple plays. The details property shows the name of the stream when switching from one element in the playlist to the next element.

Previous


Server Management ActionScript Dictionary overview

Macromedia Flash Communication Server MX 1.5 includes a set of advanced methods, the Server Management ActionScript application programming interface (API), that lets you extend the Administration Console or make your own administration and monitoring tools by creating Macromedia Flash MX 2004 applications.

This document describes the Server Management ActionScript API. Entries in this document are listed alphabetically (beginning with the addAdmin() entry). For information about ActionScript, see the ActionScript Reference Guide. For information about Flash Communication Server, see the Client-Side Communication ActionScript Dictionary, the Server-Side Communication ActionScript Dictionary, and Managing Flash Communication Server.


Using the Server Management ActionScript API

To use the Server Management ActionScript API, you need to have Flash MX 2004 and Flash Communication Server installed, and you need to have administrative access to Flash Communication Server. You should be fluent in ActionScript and in creating Flash applications.

The best way to get started using the Server Management ActionScript API is to look at the source code for the Administration Console. Registered users can view the source code for the Administration Console (in the admin.fla file) at the Flash Communication Server Registered User Download Center. To access the source code, go to www.macromedia.com/software/register, complete the registration pages, and download the admin.fla file.

Note: You must provide your product serial number, Macromedia membership ID, and password each time you access this site.


Establishing the connection to the server

Flash Communication Server communicates on port 1935 (the default port). However, to use the Server Management ActionScript API, you must connect to Flash Communication Server through the administration server on port 1111.

Note: This document assumes that you have not changed the default port number for the administration server; if you have, use your valid port number instead of port 1111.

You establish a connection using the NetConnection.connect method, passing in three parameters: the URI of the host administration server, an administrator user name, and an administrator password.

When the administration server host to which you want to connect is a virtual host (one of several services on the same machine), make sure to specify the virtual host's domain name, or IP Address, as part of the URI—for example, rtmp://www.myVhost.com/admin:1111. That way, when you connect to the host machine, you connect to an instance of the server running on your specified virtual host.

Only valid administrators, as defined in the Server.xml configuration file, can connect to the server. You must specify two administrative parameters, the user name and the password for a valid administrator, to the NetConnection.connect method.

The following example shows the call that lets the administrator MHill with password 635xjh27 connect to the server on localhost:

nc = new NetConnection();
nc.connect("rtmp://localhost:1111/admin", "MHill", "635xjh27");

To prevent unauthorized users from accessing the administration server, it is recommended that you use a firewall and limit access to the administration server port (port 1111). For more information about security for Flash Communication Server, see the security white papers.

Syntax example

To make a Server Management ActionScript API call, you'll want to include a callback handler and any required parameters in your code.

In the following example, the getAppStats method is called to retrieve the performance data of a running application; the callback handler new receiveAppStats captures the result of the call; and the value ChatApp is a required parameter that specifies the name of the application:

nc = new NetConnection();
nc.connect("rtmp://localhost:1111/admin", "MHill", "635xjh27");

// Call getAppStats
nc.call("getAppStats", new receiveAppStats(), "ChatApp");


A simple application example

This section contains the code for a simple Flash application that calls the getAppStats method. You can copy and paste this code into Flash MX 2004 to see how a simple call works.

In Flash, create an application with the following elements:

  • An input field named Application Name with a border
  • A button that calls the doGetAppStats method (shown in the code sample that follows)
  • A multiline, dynamic text field called outputBox that has a border
  • A scroll component next to the text field

This simple interface lets you test the Server Management ActionScript API.

Next, in the Actions panel, enter the sample ActionScript code that follows. Be sure to replace admin_name and admin_pass with your valid administrator name and password.

Note: The continuation character (¬) indicates that the code continues to the next line; this character should not appear in code.

/** Establishes the connection to Flash Communication Server **/

nc = new NetConnection();
nc.connect("rtmp://localhost:1111/admin","admin_name","admin_pass");

/** Makes the API call, for example, "GetAppStats" **/
function doGetAppStats() {
  function onGetAppStats()
  {
    this.onResult = function(info)
    {
      if (info.code != "NetConnection.Call.Success")
            outputBox.text = "Call failed: " + info.description;
      else {
            outputBox.text = "Info for "+appName.text+ " returned:" + ¬   newline;
            printObj(info, outputBox);
      }
    }
  }
  nc.call("getAppStats", new onGetAppStats(), appName.text);
}

// This function proceeds through an object, printing all values to the
// destination, including recursively printing objects within objects.
// The tabLevel parameter is used for cosmetic purposes.
function printObj(obj, destination, tabLevel)
{
  if  (arguments.length < 2) {
      trace("ERROR! you need to supply a text object to output to");
      return;
  }
  if (arguments.length < 3)
      tabLevel = 0;

  for (var prop in obj) {
    for (var i = 0; i < tabLevel; i++) // insert requested # of tab characters
      destination.text += "\t";

      destination.text += prop + " = " + obj[prop] + newline;
      if (typeof (obj[prop]) == "object") { // recursively call printObj
        printObj(obj[prop], destination, tabLevel+1 );
      }
    }
}

// Alerts you if there are errors connecting to the server.nc.onStatus = function(info) {
  if (info.code == "NetConnection.Connect.Success") {
    trace("Connected! The call should work")
  } else {
    // use nc.isConnected to test condition of server
    if (! nc.isConnected)
      trace("NO netConnection to server. Call will not work");
    }
}


Information objects

All Server Management ActionScript API methods return data in an information object with the following properties: level, code, timestamp, data, description, and details. All information objects have level, code, and timestamp properties. Some methods have the data property, which contains return data (often in an object or array), and the description and details properties, which typically provide information about errors.

In addition to the information objects that are documented in the Client-Side Communication ActionScript Dictionary, the NetConnection class has information objects that are specific to the Server Management ActionScript API. The following table lists the code and level properties, as well as the meaning of commonly returned information objects.
Code | Level | Meaning
NetConnection.Call.Success | Status | The call is successful. This information object includes a data property, which returns detailed information in an object or array.
NetConnection.Admin.CommandFailed | Error | The method called is nonexistent.*
NetConnection.Call.Failed | Error | A general failure has occurred.*
NetConnection.Call.BadValue | Error | The value of a parameter is invalid.*

*This information object contains description and detail properties, which are strings that provide a more specific reason for the failure.


Method summary

The Server Management ActionScript API contains the following three types of methods:

  • Queries let you monitor Flash Communication Server, its applications, and specific instances of its applications.
  • Administrative commands let you perform administrative tasks for Flash Communication Server, such as adding administrative users and starting and stopping the server, virtual hosts, and applications.
  • Configuration commands: the getConfig command lets you view server configuration keys, and the setConfig command lets you set values for the keys.

Some methods are available only to server administrators, as indicated by an asterisk (*) in the description of each method; virtual host administrators cannot use these methods. In some cases, virtual administrators can use a method with restrictions; these restrictions are described in the dictionary entry for the method.

Note: Parameters in square brackets ([]) are optional; all other parameters are required. If you don't specify an optional parameter, a default value might be used, depending on the method. For example, if you don't specify a virtual host in the scope parameter, it is assumed that you want to perform the command on the virtual host to which you connected when you logged on to Flash Communication Server.

Queries for monitoring the server

The following table lists the methods you can use to monitor the server.
Method | Description
getActiveInstances() | Returns an array of strings that contains the names of all running application instances on the connected virtual host.
getAdaptors() | Returns an array of adaptor names.
getAdminContext() | Returns the administrative context for the administrator (administrator type, name of adaptor, and name of the virtual host).
getApps() | Returns an array of strings that contains the names of all the applications that are installed.
getAppStats() | Returns aggregate information of all instances for an application.
getInstanceStats() | Returns detailed information about a single running instance of an application.
getIOStats() | Returns the I/O information: bytes in, bytes out, and so on.*
getLicenseInfo() | Returns license key information.
getLiveStreams() | Returns a list of all live streams currently publishing to a particular application.
getLiveStreamStats() | Returns detailed information about a live stream.
getMsgCacheStats() | Returns server TCMessage cache statistics.
getNetStreams() | Returns a list of all network streams that are currently connected to the application.
getNetStreamStats() | Returns detailed information about a specific network stream.
getScriptStats() | Gets the performance data for a script running on the specified instance of an application.
getServerStats() | Retrieves the server status and statistics about the operation of the server, including the length of time the server has been running and I/O and message cache statistics.*
getSharedObjects() | Returns a list of all persistent and nonpersistent shared objects that are currently in use by the specified instance of an application.
getSharedObjectStats() | Returns detailed information about a shared object.
getUsers() | Returns a list of all users who are currently connected to the specified instance of an application.
getUserStats() | Returns detailed information about a specified user.
getVHosts() | Returns an array of vhosts defined for the specified adaptor.
getVHostStats() | Returns statistics for a vhost.
ping() | Returns a status string indicating the condition of the server.

*Only server administrators can use this method.

Commands for managing the server

The following table lists the methods you can use to manage the server.
Method | Brief description
addAdmin() | Adds an administrator to the system.*
addApp() | Adds a new application.
changePswd() | Changes the password for an administrator in the system.
gc() | Forces garbage collection of server resources.*
reloadApp() | Unloads an instance of an application if it is loaded, and then reloads the instance.
removeAdmin() | Removes an administrator from the system.*
removeApp() | Removes an application or an instance of an application.
restartVHost() | Restarts a virtual host.
startServer() | Starts or restarts Flash Communication Server.*
startVHost() | Starts the specified virtual host if it stops. Enables a new virtual host if the virtual host directories have been created in the file system.*
stopServer() | Shuts down the Flash Communication Server.*
stopVHost() | Stops a virtual host.
unloadApp() | Unloads all instances of an application or one instance of an application. Disconnects all users.

*Only server administrators can use this command.

Commands for configuring the server

The following table lists the methods you can use to configure the server.
Method | Description
getConfig() | Returns configuration information for the specified configuration key.
setConfig() | Sets a value for a specified configuration key.

Entries in this document are listed alphabetically.


addAdmin()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

addAdmin(admin_name, password [,scope])

Parameters

admin_name String that contains the user name of the administrator being added.

password Password of that administrator. The password is encoded before it is written to the Server.xml configuration file.

scope Optional; string that specifies whether the administrator is a server administrator or a virtual host administrator, and for which virtual host. To add a server administrator, specify server.

To add a virtual host administrator to the virtual host to which you're connected, omit this parameter. To add a virtual host administrator to a different virtual host, specify the virtual host as adaptor_name/virtual_host_name.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success. The Server.xml configuration file is updated with the new administrator.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.CommandFailed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

If the specified administrator already exists in the system, this command fails.

Description

Adds an administrator to the system. You can add a server administrator or a virtual host administrator, depending on the parameters you specify.

You must be a server administrator to add an administrator to the system.

Example

The following three examples show how you can specify parameters in a call to the addAdmin command:

/* Adds a server administrator named "GLee" with password "boat4907" */
nc.call("addAdmin", new onAddAdmin(), "GLee", "boat4907", "server");

/* Adds a virtual host administrator named "ChrisM" with password "tree2981" */
nc.call("addAdmin", new onAddAdmin(), "ChrisM", "tree2981");

/* Adds a virtual host administrator "DHong" with password "wate3235" */
/* for vhost tree.oak.com */
nc.call("addAdmin", new onAddAdmin(), "DHong", "wate3235", "_defaultRoot_/ ¬ tree.oak.com");


addApp()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

addApp(app_name)

Parameters

app_name String that contains the name of the application to be added.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.BadValue or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Adds a new application to the virtual host by creating the required directory for the new application in the directory tree. Once the directory for the new application is created, you (or another administrator with file system access) can put any required server-side scripts in the directory. The client-side code uses the new application directory in the URI parameter of the NetConnection.Connect call.

Example

The following example shows a call to add the ChatApp application to the connected virtual host:

nc = new NetConnection();
nc.connect("rtmp://localhost:1111/admin", "JLee", "x52z49ab");

nc.call("addApp", new onAddApp(), "ChatApp");


changePswd()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

changePswd(admin_name, password [, scope])

Parameters

admin_name String that contains the name of the administrator whose password is being changed.

password String that contains that administrator's new password.

scope Optional; string that specifies whether the administrator is a server administrator or virtual host administrator, and for which virtual host.

To change the password for the specified administrator on the virtual host to which you're connected, omit this parameter. To change the password for the specified administrator on a different virtual host, specify adaptor_name/virtual_hostname.

To change a server administrator's password, specify server.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.CommandFailed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

If the specified administrator does not exist, this command fails.

Description

Changes the password for the specified administrator. The password is encoded before it is written to the Server.xml configuration file.

Virtual host administrators can change only their own password.

Example

/* Change password for server administrator named "ASilva" to "cbx5978y" */
nc.call("changePswd", new onChangePswd(), "ASilva", "cbx5978y", "server");

/* Change password for virtual host administrator named "JLee" to "kbat3786" */
nc.call("changePswd", new onChangePswd(), "JLee", "kbat3786");

/* Change password for virtual host administrator "JLee" to "kbat3786" on */
/* virtual host "tree.oak.com" */
nc.call("changePswd", new onChangePswd(), "JLee", "kbat3786", "_defaultRoot_/¬ tree.oak.com");


gc()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

gc()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.CommandFailed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Forces collection and elimination of all server resources that are no longer used, such as closed streams, instances of applications, and nonpersistent shared objects. This operation is performed within about one second of the call.

You must be a server administrator to perform this operation.


getActiveInstances()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getActiveInstances()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an array of strings containing the names of all running instances of an application.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Returns an array of strings that contains the names of all running application instances on the connected virtual host.


getAdaptors()

Availability

  • Flash Player 6.
  • Flash Communication Server MX 1.5.

Usage

getAdaptors()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an array of strings containing the names of all the adaptors.

Description

Returns an array of adaptors that are defined. You must be a server administrator to perform this command.


getAdminContext()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getAdminContext()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:

Property

Description

admin_type

String; the type of administrator, either server or vhost.

adaptor

String; name of the adaptor for which the user is an administrator.

vhost

String; name of the virtual host for which the user is an administrator.

connected

String; true if the administrator is connected, through the administration server, to Flash Communication Server; false if the administrator is connected only to the administration server and not Flash Communication Server.

It is possible for an administrator to be logged on to the administration server on port 1111 but not have an active connection to Flash Communication Server, which communicates on port 1965.

Description

Gets the administrative context for an administrator, including information about the specified user's administrative permissions, the name of the adaptor and virtual host to which the user is connected, and whether the user is currently connected to Flash Communication Server.


getApps()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getApps()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an array of strings containing the names of all the applications that are installed.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Returns an array of strings that contains the names of all the applications that are installed.

See also

getActiveInstances(), getAppStats(), getInstanceStats()


getAppStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getAppStats(app_name)

Parameters

app_name String that contains the name of the application for which you want performance data.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:
Property | Description
launch_time | ActionScript Date object; time the application started.
up_time | Number; time, in seconds, the application has been running.
msg_in | Number; total number of messages processed by this application.
msg_out | Number; total number of messages sent by this application.
msg_dropped | Number; total number of messages dropped by this application.
bytes_in | Number; total number of bytes read by this application.
bytes_out | Number; total number of bytes written by this application.
accepted | Number; total number of connection attempts accepted by this application.
rejected | Number; total number of connection attempts rejected by this application.
connected | Number; total number of connections currently active.
total_connects | Number; total number of socket connections to the application since the application was started.
total_disconnects | Number; total number of disconnections from the application since the application was started.
total_instances_loaded | Number; total number of instances that have been loaded since the application started. This property does not represent the total number of active instances loaded. To get the number of active instances loaded, subtract the value of total_instances_unloaded from total_instances_loaded.
total_instances_unloaded | Number; total number of instances that have been unloaded since the application started.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Gets aggregate performance data for all instances of the specified application.

See also

getApps(), getInstanceStats()


getConfig()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getConfig(key [,scope])

Parameters

key String that specifies the configuration key for which information is retrieved.

A key is specified as a list of subkeys that are delimited by slashes (/). The first subkey specifies the XML configuration file that contains the desired configuration key. Subsequent subkeys correspond to tags that are relative to the XML configuration file; the hierarchy and names of the subkeys match the tags in the XML file.

Flash Communication Server has four server configuration files: Server.xml, Adaptor.xml, Vhost.xml, and Application.xml. Depending on your permissions, you can get configuration keys for all these files, as described in the following list:

  • For the Server.xml file, specify Admin or Server as the first subkey. All subsequent keys correspond to tags that are relative to the <Admin> or <Server> tag in the Server.xml file.

    You must be a server administrator to view configuration keys in the <Server> tag.

    Virtual host administrators can view configuration keys in the <Admin> tag for their own virtual host only. They might not be able to view certain kinds of sensitive information; for example, they can view the names of other administrators for their own virtual host, but they cannot view those administrators' passwords or permission settings.

  • For the Adaptor.xml file, specify as the first subkey Adaptor:adaptor_name, where adaptor_name is the name of the adaptor. All subsequent keys correspond to tags that are relative to the <Adaptor> tag in the Adaptor.xml file.
  • For the Vhost.xml file, specify as the first subkey Adaptor:adaptor_name/VirtualHost:vhost_name, where adaptor_name is the name of the adaptor and vhost_name is the name of the virtual host. All subsequent keys correspond to tags that are relative to the <VirtualHost> tag in the Vhost.xml file.
  • For the Application.xml file of an application that is running on the same virtual host to which you connected when you logged on to the administration server, specify as the first subkey Application:app_name, where app_name is the name of the application.

    To get a key in the Application.xml file for an application that is running on a different virtual host, specify the full key Adaptor:adaptor_name/VirtualHost:vhost_name/Application:app_name. You must also specify the scope parameter.

    To get the default Application.xml file, specify Application without the colon (:) and the app_name attribute.

scope String; to get a configuration key in the Server.xml file, Adaptor.xml file, or Vhost.xml file, specify a slash (/).

To get a configuration key in the Application.xml file for an application that is running on the same virtual host to which you connected when you logged on to Flash Communication Server, omit this parameter.

Tip: To determine the adaptor or virtual host to which you're connected, use the getAdminContext method.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an XML string for the specified tag.

If the call fails (that is, if the specified configuration key isn't found), the server returns an empty string.

Description

Gets information for the specified configuration key in a specified configuration file. Flash Communication Server has four configuration files: Server.xml, Adaptor.xml, Vhost.xml, and Application.xml.

Virtual host administrators can view configuration keys in the Vhost.xml file and Application.xml files for their own virtual hosts.

You must be a server administrator to view most of the configuration keys for the Server.xml and Adaptor.xml files.

For a description of the XML configuration files, see Managing Flash Communication Server.

Tip: It is possible to have more than one XML tag with the same name at the same level in the XML tree. In the configuration file, you should distinguish such tags by using a name attribute in the XML tag (for example, if you have more than one VirtualHost tag: <VirtualHost name="www.redpin.com"></VirtualHost>). When you call the getConfig command and specify the configuration subkeys, you can indicate which tag you want by specifying the tag name, followed by a colon and the correct name attribute, for example, Admin/Adaptor:_defaultRoot_/VirtualHost:www.redpin.com.

Examples

The following examples show how to get configuration keys in each of the four XML files:

// Establish connection to server
nc = newNetConnection();
nc.connect("rtmp://localhost:1111/admin", "JLee", "xm1472dy");

// For a virtual host administrator, find key in Server.xml
key = "Admin/Server/UserList/User:JLee/Password";
nc.call("getConfig", new onGetConfig(), key, "/");

// For a server administrator; find key in Server.xml
key = "Server/LicenseInfo";
nc.call("getConfig", new onGetConfig(), key, "/");

// Find key in Adaptor.xml
key = "Adaptor:_defaultRoot_/HostPortList/HostPort";
nc.call("getConfig", new onGetConfig(), key, "/");

// Find key in Vhost.xml
key = "Adaptor:_defaultRoot_/VirtualHost:_defaultVhost_/RecordAccessLog";
nc.call("getConfig", new onGetConfig(), key, "/");

// Find key in Application.xml for an application on the virtual host you
// connected to when you logged on to the administration server
// Note that the previous subkeys and the second parameter "/" are not necessary
key = "Application:FinanceApp/RecordAppLog";
nc.call("getConfig", new onGetConfig(), key);

// Find key in Application.xml for an application on a different virtual host
key = "Adaptor:_defaultRoot_/VirtualHost:www.redpin.com/Application:ChatApp/ ¬ RecordAppLog";
nc.call("getConfig', new onGetConfig(), key, "/");

See also

getAdminContext(), setConfig()


getInstanceStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getInstanceStats(app_instance)

Parameters

app_instance String that contains the name of the instance of the application for which you want performance statistics, in the form application_name/instance_name. You must specify both the application name and the instance name, separated by a slash (/), even if you want performance statistics for the default instance of the application.

For example, to specify the default instance for an application named ChatApp, specifyChatApp/_defInst_.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:

Property

Description

launch_time

ActionScript Date object; time the instance was launched.

up_time

Number; length of time, in seconds, the instance has been running.

msg_in

Number; total number of messages processed by this instance of the application.

msg_out

Number; total number of messages sent by this instance of the application.

msg_dropped

Number; total number of messages dropped by this instance of the application.

bytes_in

Number; total number of bytes read by this instance of the application.

bytes_out

Number; total number of bytes written by this instance of the application.

accepted

Number; total number of connection attempts accepted by this application.

rejected

Number; total number of connection attempts rejected by this application.

connected

Number; total number of connections currently active.

total_connects

Number; total number of socket connections to this instance of the application since the instance was started.

total_disconnects

Number; total number of socket disconnections from this instance of the application since the instance was started.

script

Object that contains script engine performance data. The following are properties of the script object:

time_high_water_mark: Number; maximum amount of time, in seconds, that the script has taken to execute an event.

queue_size: Number; total number of events currently in the script engine queue.

total_processed: Number; total number of events processed by the script engine.

total_process_time: Number; number of seconds taken to process the number of events in total_processed.

queue_high_water_mark: Number; maximum number of events in the queue.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Gets the performance data for a specified instance of an application.

If you only need information about the performance of a specific script, use the getScriptStats method.

See also

getActiveInstances(), getAppStats(), getScriptStats()


getIOStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getIOStats()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:
Property | Description
msg_in | Number; total number of messages processed by the adaptor.
msg_out | Number; total number of messages sent by the adaptor.
bytes_in | Number; total number of bytes read by the adaptor.
bytes_out | Number; total number of bytes written by the adaptor.
reads | Number; total number of system read calls.
writes | Number; total number of system writes.
connected | Number; number of currently active socket connections to the adaptor.
total_connects | Number; total number of socket connections to the adaptor since the adaptor was started.
total_disconnects | Number; total number of socket disconnections from the adaptor.
msg_dropped | Number; total number of messages dropped.
tunnel_bytes_in | Number; tunneling header bytes in (this is the overhead over and above RTMP payload).
tunnel_bytes_out | Number; tunneling header bytes out (overhead in the other direction).
tunnel_requests | Number; number of tunneling requests thus far.
tunnel_responses | Number; number of tunneling responses thus far.
tunnel_idle_requests | Number; number of tunneling requests that had no payload (network chatter overhead).
tunnel_idle_responses | Number; number of tunneling responses that had no payload (network chatter overhead).

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Returns detailed information about the network I/O characteristics of the connected adaptor.

You must be a server administrator to perform this operation.


getLicenseInfo()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getLicenseInfo()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:

Property

Description

name

String; product name, for example, Flash Communication Server MX.

version

String; version number, for example, 1.0.

build

String; build number.

copyright

String; copyright information.

key

String; license key that is set in the Server.xml file.

If you have more than one license key, this string is a concatenation of all your valid license keys, delimited by semicolons (;).

type

Number; type of license. If you have multiple licenses, they must have the same type number. Possible values are shown here:

0=Commercial

1=Educational

family

Number; license family, which determines the value of other properties. If you have multiple licenses, they must have the same family number. Possible values are shown here:

0=Personal

1=Professional

edition

Number; edition, for example, single, trial, beta, unlimited, and so on. If you have multiple licenses, they must have the same edition number.

max_connections

Number; maximum number of socket connections allowed, which is determined by license family.

If you have more than one license, this number is the sum of the max_connections values of all your licenses.

max_adaptors

Number; maximum number of adaptors (network cards) that you can configure for the server, which is determined by license family. If the license family is Personal, the value of max_adaptors is 1.

max_vhosts

Number; maximum number of virtual hosts allowed, which is determined by license family. If the license family is Personal, the value of max_vhosts is 1.

max_cpu

Number; maximum number of CPUs allowed, which is determined by license family.

If this number is greater than 1, you can run the server on multiprocessor computers.

max_bandwidth

Number; maximum bandwidth, in megabits per second. If you have multiple licenses, this number is the sum of the max_bandwidth values of all your licenses.

key_details

Array; contains the information for each license key. If you have more than one license key, there is one array element for each license key.

Each array element is an object that contains the following properties:

key: String; license key as set in Server.xml.

type: Number; 0=Commercial, 1=Educational.

family: Number; 0=Personal, 1=Professional.

edition: Number.

max_connections: Number; maximum socket connections allowed for this license.

max_adaptors: Number; maximum adaptors (network cards) allowed for this license. If the license family is Adaptor, this value is 1.

max_vhosts: Number; maximum number of virtual hosts for each adaptor, for this license. If the license family is Personal, this value is 1.

max_cpu: Number; maximum number of CPUs allowed. If this number is greater than 1, you can run the server on multiprocessor computers.

max_bandwidth: Number; maximum bandwidth, in megabits per second.

product_code: Number; determined by license family.

valid: A Boolean value; 1=true, license is valid; 0=false, license is invalid.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Retrieves complete license information including information on the maximum bandwidth and maximum number of connections, adaptors, virtual hosts, and CPUs that are allowed by the license. License information for all your licenses is first summarized, followed by specific information about each license.


getLiveStreams()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getLiveStreams(app_instance)

Parameters

app_instance String that contains the name of the instance of the application, in the form application_name/instance_name.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an array of strings containing the names of all the live streams that are currently publishing to the specified instance of an application.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Gets an array of strings that contains the names of all the live streams that are currently publishing to the specified instance of an application.

See also

getLiveStreamStats()


getLiveStreamStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getLiveStreamStats(app_instance, stream_name)

Parameters

app_instance String that contains the name of the instance of the application, in the form application_name/instance_name.

stream_name String that contains the name of the stream.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:
Property | Description
publisher | Object; publisher statistics. The object has the following properties: client: Number; the user ID. publish_time: ActionScript Date object; time that the stream was published.
subscribers | Array of subscriber statistics. The array contains a subscriber property that is an object containing the following properties: client: Number; user ID. subscribe_time: ActionScript Date object; the time that the user subscribed to the stream.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Gets detailed information, such as publisher statistics and user ID, for a live stream.

See also

getLiveStreams()


getMsgCacheStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX 1.5.

Usage

getMsgCacheStats()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following message cache statistics:
Property | Description
allocated | Number; total number of message objects allocated.
reused | Number; total number of objects used.
size | Number; current size.

Description

Returns server TCMessage cache statistics. You must have server administrative privileges to perform this operation.


getNetStreams()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getNetStreams(app_instance)

Parameters

app_instance String that contains the name of the instance of the application, in the form application_name/instance_name.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an array of numbers. The numbers represent the server-assigned IDs of all network streams that are currently connected to the specified instance of the application.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Returns an array of numbers that represent the server-assigned IDs of all the network streams that are currently connected to the specified instance of the application.

See also

getNetStreamStats()


getNetStreamStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getNetStreamStats(app_instance, netstream_ID)

Parameters

app_instance String that contains the name of the instance of the application, in the form application_name/instance_name.

netstream_ID Number that represents the ID of the network stream or an array of numbers that represents the network stream ID.

To get information for all the network streams that are currently connected, specify a value of -1 for the netstream_ID parameter.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an array of statistics for the network stream. Each element in the array is an object that has the following properties:
Property | Name
stream_id | Number; stream ID.
name | String; stream name or empty if the stream is idle.
type | String; stream type. Possible values are shown in the following list: idle publishing playing live play recorded
client | Number; user ID.
time | ActionScript Date object; possible values are shown in the following list: If type = idle, value is 0. If type = publishing, value is the time the stream was published. If type = playing live, value is the time the playback of the stream started. If type = play recorded, value is the time the playback of the stream started.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Gets detailed information for one or more network streams that are connecting to the specified instance of an application.

See also

getNetStreams()


getScriptStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getScriptStats(app_instance)

Parameters

app_instance String that contains the name of the instance of the application, in the form application_name/instance_name.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:
Property | Description
time_high_water_mark | Number; maximum amount of time, in seconds, the script has taken to execute an event.
queue_size | Number; total number of events currently in the script engine queue.
total_processed | Number; total number of events processed by the script engine.
total_process_time | Number; number of seconds taken to process the number of events in total_processed.
queue_high_water_mark | Number; maximum number of events in the queue.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Gets the performance data for a script running on the specified instance of an application.


getServerStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getServerStats()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:
Property | Description
launch_time | ActionScript Date object; time the server was started.
up_time | Number; length of time, in seconds, that the server has been running.
io | I/O statistics, returned as an object with the following properties: msg_in: Number; total number of messages processed by the server. msg_out: Number; total number of messages sent by the server. bytes_in: Number; total number of bytes read by the server. bytes_out: Number; total number of bytes written by the server. reads: Number; total number of system read calls. writes: Number; total number of system writes. connected: Number; total number of active socket connections to the server. total_connects: Number; total number of socket connections to the server. total_disconnects: Number; total number of socket disconnections from the server.
msg_cache | Flash Communication Server message packet cache statistics, returned as an object with the following properties: allocated: Number; total number of message objects allocated. reused: Number; total number of objects reused. size: Number; size of the cache, in number of message packets.
memory_Usage | Number. On Microsoft Windows NT 4.0, the approximate percentage of the last 1000 pages of physical memory in use. On Windows 2000 or Windows XP, the approximate percentage of total physical memory in use.
cpu_Usage | Number; approximate percentage of CPU in use.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Retrieves the server status and statistics about the operation of the server, including the length of time the server has been running and I/O and message cache statistics.

You must be a server administrator to perform this operation.

If you only need information about the I/O characteristics of the server, use the getIOStats method instead.

See also

getIOStats()


getSharedObjects()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getSharedObjects(app_instance)

Parameters

app_instance String that contains the name of the instance of the application, in the form application_name/instance_name.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:
Property | Description
persistent | Array of strings that contain persistent shared object names.
volatile | Array of strings that contain shared object names that are not persistent.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

This call fails if you supply an application or instance name that does not exist.

Description

Gets the names of all the shared objects that are currently active.

See also

getSharedObjectStats()


getSharedObjectStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getSharedObjectStats(app_instance, object_name, persistence)

Parameters

app_instance String that contains the name of the instance of the application, in the form application_name/instance_name.

object_name String that contains the name of the shared object. You can get the names of all active shared objects by using the getSharedObjects command.

persistence A Boolean value: true (1) for persistent; false (0) for nonpersistent.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:
Property | Description
version | Number; version number of the shared object.
num_properties | Number; total number of properties in the shared object.
msg_in | Number; total messages in to the shared object.
msg_out | Number; total messages out from the shared object.
total_connects | Number; total number of connections to the shared object.
total_disconnects | Number; total number of disconnections from the shared object.
connected | Number; number of active subscribers.
resync_depth | Number; maximum version retained before resynchronization. If the difference between the server version number and the client version number is greater than the resync_depth value, Flash Communication Server sends only changes between versions.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Gets detailed information about a shared object.

See also

getSharedObjects()


getUsers()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getUsers(app_instance)

Parameters

app_instance String that contains the name of the instance of the application, in the form application_name/instance_name.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an array of strings that represent the IDs of users who are connected to the specified instance of an application. The user IDs are assigned by the server.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Gets an array of strings that represent the server-assigned IDs of all users who are connected to the specified instance of an application.

See also

getUserStats()


getUserStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

getUserStats(app_instance, user_ID)

Parameters

app_instance String that contains the name of the instance of the application, in the form application_name/instance_name.

user_ID String that contains the user ID, as assigned by the server. You can retrieve a user ID with the getUsers command.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object. The data object has the following properties:
Property | Description
connect_time | ActionScript Date object; time, in seconds, that the user has been connected to the specified instance of the application.
msg_in | Number; total number of messages processed by this user.
msg_out | Number; total number of messages sent by this user.
msg_dropped | Number; total number of messages dropped by this user.
bytes_in | Number; total number of bytes read by this user.
bytes_out | Number; total number of bytes written by this user.
msg_queue | Object that contains the client message queue statistics. The msg_queue object contains the following properties: total_queues: Total number of queues for this client. audio: Total number of audio messages in all audio queues. video: Total number of video messages in all video queues. other: Total number of command/data messages in the other queue.
protocol | String; protocol used by the client to connect to the server (RTMP or RTMPT).
stream_ids | Array of numbers that represent the stream IDs.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Gets the performance data for the connection of a specified user.

See also

getUsers()


getVHosts()

Availability

  • Flash Player 6.
  • Flash Communication Server MX 1.5.

Usage

getVHosts([adaptorName])

Parameters

adaptorName Optional string that contains the user name of the adaptor. If not specified, it is assumed to be "_defaultRoot_".

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an array of strings containing the names of all the virtual hosts.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Returns an array of vhosts defined for the specified adaptor. You must be a server administrator to perform this command.


getVHostStats()

Availability

  • Flash Player 6.
  • Flash Communication Server MX 1.5.

Usage

getVHostStats([adaptorName, vhostName])

Parameters

adaptorName Optional string that contains the user name of the adaptor. If not specified, it is assumed to be "_defaultRoot_".

vhostName Optional string that contains the user name of the virtual host. If not specified, it is assumed to be "_defaultVHost_".

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a data property that is an object containing the virtual host performance data. The data object has the following properties:
Property | Description
msg_in | Number; total number of messages processed by this vhost.
msg_out | Number; total number of messages sent by this vhost.
msg_dropped | Number; total number of messages dropped by this vhost.
bytes_in | Number; total number of bytes read by this vhost.
bytes_out | Number; total number of bytes written by this vhost.
accepted | Number; total number connections accepted by this vhost.
rejected | Number; total number of connections rejected by this vhost.
connected | Number; total number of connections currently active.
total_apps | Number; total number of applications that have been created.
total_connects | Number; total number of connections to the server.
total_disconnects | Number; total number of disconnections from the server.
total_instances_loaded | Number; total number of instances that have been loaded. This property does not represent the total number of active instances loaded. To get the number of active instances loaded, subtract the value of total_instances_unloaded from total_instances_loaded.
total_instances_unloaded | Number; total number of instances that have been unloaded.
bw_in | Number; current bandwidth in, in bytes per second.
bw_out | Number; current bandwidth out, in bytes per second.
tunnel_bytes_in | Number; total number of bytes read through the tunnel.
tunnel_bytes_out | Number; total number of bytes written through the tunnel.
tunnel_requests | Number; number of current requests.
tunnel_idle_requests | Number; number of currently idle requests.
tunnel_idle_responses | Number; number of currently idle responses.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Returns aggregate performance data for all instances for all applications for the specified vhost. You must be a server administrator to perform this command.


ping()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

ping()

Parameters

None.

Returns

If the call succeeds, the server sends a reply information object with a level property of status, a code property of NetConnection.Call.Success, and a timestamp property that is a Date object. The Date object indicates the time that the command was executed.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Call.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Verifies that the server is running; the server responds with a status message. You can use this command to check the status of the server.


reloadApp()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

reloadApp(app_name)

Parameters

app_name String that contains the name of the application or instance of the application, in the form application_name[/instance_name]. To reload the default instance of an application, specify only the name of the application.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.Command.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Shuts down the specified application or instance of the application, if running, and reloads it. All users are disconnected.

After this command runs, users must reconnect to the application or instance of the application.

You can use this command to preload an instance of an application or reload it when application configuration changes are made or the script that is associated with the application has been changed.

See also

unloadApp()


removeAdmin()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

removeAdmin(admin_name [,scope])

Parameters

admin_name String that contains the user name of the administrator being removed.

scope Optional; string that specifies which administrator you want to remove.

To remove a virtual host administrator from the virtual host to which you're connected, omit this parameter. To remove a virtual host administrator from a different virtual host, specify the virtual host as adaptor_name/virtual_hostname.

To remove a server administrator, specify server.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.Command.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

If the specified administrator does not exist, the call fails.

Description

Removes an administrator from the system. Depending on the parameters you specify, you can remove server administrators or virtual host administrators.

You must be a server administrator to remove an administrator from the system.

Example

The following examples show the removeAdmin method:

/* Remove a server administrator named "DYoung" */
nc.call("removeAdmin", new onRemoveAdmin(), "DYoung", "server");

/* Remove a virtual host administrator named "LPark" */
nc.call("removeAdmin", new onRemoveAdmin(), "LPark");

/* Remove a virtual host administrator "JGarcia" from vhost tree.oak.com */
nc.call("removeAdmin", new onRemoveAdmin(), "JGarcia", "_defaultRoot_/ ¬
tree.oak.com");

See also

addAdmin()


removeApp()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

removeApp(app_name)

Parameters

app_name String that contains the name of the application or instance of the application you want to remove, in the form application_name[/instance_name].

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.Command.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Removes the specified application or instance of an application from the virtual host. First, all instances of the specified application are unloaded. Then the application directory is removed from the virtual host. If you specify an instance of an application, only that instance is unloaded and removed, and all streams and shared objects for that instance are deleted.

Example

The following example shows how you remove the entire application ChatApp and then shows how you remove a specific instance Instance1 of an application ChatApp.

nc = new NetConnection();
nc.connect("rtmp://localhost:1111/admin", "JGarcia", "ezcabby1");

/* Removes the application along with all instances of the application */

nc.call("removeApp", new onRemoveApp(), "ChatApp");

/* Removes only the specified instance */

nc.call("removeApp", new onRemoveApp(), "ChatApp/Instance1");

See also

addApp()


restartVHost()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

restartVHost([scope])

Parameters

scope Optional; string that specifies which virtual host you want to restart.

To restart the virtual host to which you're connected, omit this parameter.

To restart a different virtual host, specify the virtual host as adaptor_name/virtual_hostname.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.Command.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Restarts a virtual host that is currently running. Restarting a virtual host disconnects all connected users, unloads all currently loaded applications, and reloads the configuration files for that virtual host.

If you make changes to the configuration files for a virtual host, you can use this command to restart the virtual host without restarting the server.

Users must reconnect each time you restart a virtual host. Before using this command, you might want to take steps to notify connected users.

Virtual host administrators can only restart the virtual hosts to which they are connected. You must be a server administrator to start a virtual host other than the one to which you're connected.

Tip: To start a virtual host that is stopped, use the startVHost command. You must be a server administrator to perform this command.

Example

The following example shows a call to restart the connected virtual host and then a call to restart a specified virtual host tree.oak.com on the default adaptor:

/* Restart the connected virtual host */
nc.call("restartVHost", new onRestartVHost());

/* Restart the virtual host tree.oak.com on the default adaptor */
nc.call("restartVHost", new onRestartVHost(), "_defaultRoot_/tree.oak.com");

See also

reloadApp(), startVHost(), stopVHost()


setConfig()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

setConfig(key, key_value, [,scope])

Parameters

key String that specifies the configuration key for which you want to change the value.

A key is specified as a list of subkeys delimited by slashes (/). The first subkey specifies the XML configuration file that contains the desired configuration key. Subsequent subkeys correspond to tags that are relative to that XML configuration file; the hierarchy and names of the subkeys match the tags in the XML file.

Flash Communication Server has four server configuration files: Server.xml, Adaptor.xml, Vhost.xml, and Application.xml. Depending on your permissions, you can change the values of configuration keys for all these files:

  • For the Server.xml file, specify Admin or Server as the first subkey. All subsequent keys correspond to tags that are relative to the <Admin> or <Server> tag in the Server.xml file.

    You must be a server administrator to set configuration keys in the <Server> tag.

    Virtual host administrators can set configuration keys for their own virtual host only. They might not be able to set certain kinds of sensitive information; for example, they can set their own password, but they cannot set other virtual host administrators' passwords or permission settings.

  • For the Adaptor.xml file, specify as the first subkey Adaptor:adaptor_name, where adaptor_name is the name of the adaptor. All subsequent keys correspond to tags relative to the <Adaptor> tag in the Adaptor.xml file.
  • For the Vhost.xml file, specify as the first subkey Adaptor:adaptor_name/VirtualHost:vhost_name, where vhost_name is the name of the virtual host. All subsequent keys correspond to tags relative to the <VirtualHost> tag in the Vhost.xml file.
  • For the Application.xml file of an application that is running on the same virtual host to which you connected when you logged on to the administration server, specify as the first subkey Application:app_name, where app_name is the name of the application.

    To get a key in the Application.xml file for an application that is running on a different virtual host, specify the full key: Adaptor:adaptor_name/VirtualHost:vhost_name/Application:app_name. You must also specify the scope parameter; see the code example later in this entry.

    To get the default Application.xml file, specify Application without the colon (:) and the app_name attribute.

Note: If a subkey is specified but a corresponding tag doesn't exist in the XML file, a new tag is created in the XML file.

key_value String; the value to set for the specified configuration key.

scope String; to change a configuration key in the Server.xml file, Adaptor.xml file, or Vhost.xml files, you must specify a slash (/) for this parameter.

To change a configuration key in the Application.xml file for an application that is running on the same virtual host to which you connected when you logged on to Flash Communication Server, omit this parameter.

Tip: To determine the adaptor or virtual host to which you're connected, use the getAdminContext method.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success. The value of the configuration key is changed.

If the call fails, the server sends a reply information object with a level property of error, a code property of NetConnection.Call.BadValue, and a description property that contains a string describing the cause of the failure.

This call fails if the specified configuration key cannot be found or if you do not have permissions to change its value.

Description

Changes the value of the specified configuration key in a specified configuration file. Flash Communication Server has four server configuration files: Server.xml, Adaptor.xml, Vhost.xml, and Application.xml.

Virtual host administrators can change the values of configuration keys in the Vhost.xml file and Application.xml files for their own virtual hosts.

You must be a server administrator to change the values of most configuration keys in the Server.xml and Adaptor.xml files.

For a description of the XML configuration files, see Managing Flash Communication Server.

Tip: It is possible to have more than one XML tag with the same name at the same level in the XML tree. In the configuration file, you should distinguish such tags by using a name attribute in the XML tag (for example, if you have more than one virtual host: <VirtualHost name="www.redpin.com"></VirtualHost>.) When you call the setConfig command and specify the configuration subkeys, you can indicate which tag you want by specifying the tag name, followed by a colon and the correct name attribute, for example:Adaptor:_defaultRoot_/VirtualHost:www.redpin.com.

Examples

The following examples show how to set new values for configuration keys in each of the four XML files:

// Establish connection to server
nc = newNetConnection();
nc.connect("rtmp://localhost:1111/admin", "LGreen", "123jn098");

// For a virtual host administrator, change key in Server.xml
// Set Password for user LGreen to "strawman28"
key = "Admin/Server/UserList/User:LGreen/Password";
val = "strawman28"
nc.call("setConfig", new onSetConfig(), key, val, "/");

// For a server administrator, change key in Server.xml
// Set LicenseInfo to "Helloworld"
key = "Server/LicenseInfo";
val = "Helloworld";
nc.call("setConfig", new onSetConfig(), key, val, "/");

// Change key in Adaptor.xml
// Set HostPort to 128.0.0.1:1938
key = "Adaptor:_defaultRoot_/HostPortList/HostPort";
val = "128.0.0.1:1938";
nc.call("setConfig", new onSetConfig(), key, val, "/");

// Change key in Vhost.xml
// Set RecordAccessLog to true
key = "Adaptor:_defaultRoot_/VirtualHost:_defaultVHost_/RecordAccessLog";
val = "true";
nc.call("setConfig", new onSetConfig(), key, val, "/");

// Change key in Application.xml for an application on the virtual host
// you connected to when you logged on to the administration server.
// Note that the previous subkeys and the final parameter "/" are not
// necessary.
key = "Application:FinanceApp/RecordAppLog";
val = "true";
nc.call("setConfig", new onSetConfig(), key, val);

// Change key in Application.xml for a different virtual host.
// The adaptor and virtual host names and the second parameter are necessary.
key = "Adaptor:_defaultRoot_/VirtualHost:www.redpin.com/Application:ChatApp/ ¬ RecordAppLog";
val = "true";
nc.call("setConfig', new onSetConfig(), key, val, "/");

See also

getAdminContext(), getConfig()


startServer()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

startServer([start_type])

Parameters

start_type Optional; string that specifies how you want to restart the server.

If the server is not running and you want to start it, omit this parameter. If the server is already running and you want to stop it and then restart it, you must specify restart for this parameter. (If the server is running and you omit this parameter, this command does nothing.)

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.Command.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Starts the Flash Communication Server service or stops it and restarts it.

You must be a server administrator to perform this operation.

See also

stopServer()


startVHost()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

startVHost(vhost_name)

Parameters

vhost_name String that contains the name of the virtual host you want to start or the new virtual host you want to enable, in the form [adaptor/]vhost.

If you are enabling a new virtual host on the adaptor to which you're connected, omit adaptor/.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.Command.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Starts a stopped virtual host or enables a new virtual host.

This command lets you enable a new virtual host at runtime without restarting the server. The new virtual host directory and configuration files must already be present in the server's conf directory; the startVHost command does not create or copy any directories or configuration files. For information on adding virtual hosts, see Managing Flash Communication Server.

You must be a server administrator to use the startVHost command.

Tip: This command starts a new virtual host for the current session. If you want the new virtual host to be started each time the server is restarted, add it to the server configuration file.

Example

The following example starts a virtual host named diamond.world.com on the currently connected adaptor and then starts a virtual host named diamond.world.com on the gem adaptor.

/* Starts a virtual host named diamond.world.com */
nc.call("startVHost", new onStartVHost(), "diamond.world.com");

/* Starts a virtual host named diamond.world.com on the adaptor, gem */
nc.call("startVHost", new onStartVHost(), "gem/diamond.world.com");

See also

restartVHost()


stopServer()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

stopServer(stop_type)

Parameters

stop_type String; possible values are normal or abort.

If you use the value normal, the server shuts down, allowing running applications to end normally.

If you use the value abort, the server immediately shuts down and running applications will not be allowed to stop normally.

Use the value abort only in an emergency or if specifying normal does not work.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.Command.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Shuts down the Flash Communication Server. If you use this command while users are connected, you should take steps to notify users of an imminent server shutdown so that they do not lose their work.

You must be a server administrator to perform this operation.

See also

startServer()


stopVHost()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

stopVHost([vhost_name])

Parameters

vhost_name Optional; string that contains the virtual host that you want to stop. To stop the virtual host to which you're connected, omit this parameter.

To stop a different virtual host, specify vhost_name in the form adaptor_name/vhost_name.

You must be a server administrator to stop a virtual host other than the one to which you're connected.

Note: Be careful about stopping the virtual host to which you are currently connected. If you stop the virtual host you are currently logged on to, your connection to that virtual host ends; you must have the appropriate permissions to log on to another virtual host and start the stopped virtual host.

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.Command.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Stops a running virtual host. After the virtual host stops, all applications are unloaded and all users are disconnected. The virtual host does not accept any requests until it has been restarted by means of the startVHost command or until the server is restarted.

Example

The following example stops the virtual host tree.oak.com and then stops the virtual host tree.oak.com on the default adaptor.

/* Stop the vhost named tree.oak.com */
nc.call("stopVHost", new onStopVHost(), "tree.oak.com");

/* Stop the vhost named tree.oak.com on the default adaptor */
nc.call("stopVHost", new onStopVHost(), "_defaultRoot_/tree.oak.com");

See also

restartVHost(), startVHost()


unloadApp()

Availability

  • Flash Player 6.
  • Flash Communication Server MX.

Usage

unloadApp(app_instance)

Parameters

app_instance String that contains the name of the application or instance of the application, in the form application_name[/instance_name].

Returns

If the call succeeds, the server sends a reply information object with a level property of status and a code property of NetConnection.Call.Success.

If the call fails, the server sends a reply information object with a level property of error and a code property of NetConnection.Admin.Command.Failed or a more specific value, if available. Some objects might also have a description property that contains a string describing the cause of the failure.

Description

Shuts down all instances of the specified application or instance of an application. If an application name is specified, all instances of the application are shut down and all the users who are connected to any instance of the application are immediately disconnected. If an instance of an application is specified, only that instance is shut down, and all the users who are connected to that instance are immediately disconnected.

Note: Before using this command, take steps to notify users of the imminent shutdown of an application.

See also

reloadApp()

Previous


About

100% ActionScript Dictionary (for Flash MX Professional 2004)

//Welcome to Danger's Flash Blog
//2004-01-26
//V1.0.1
getURL("http://www.dengjie.com");