1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Flash: ActionScript Language Reference- P11 docx

104 263 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề ActionScript Language Reference
Thể loại tài liệu
Định dạng
Số trang 104
Dung lượng 321,57 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Example The following example shows how to use the XML.childNodes property to return an array of child nodes: // create a new XML document var doc:XML = new XML; // create a root node va

Trang 3

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

Trang 4

Usage 1: Operator; a unary operator that discards the expression value and returns an undefined

value The void operator is often used in comparisons using the equality (==) operator to test for

Usage 2: In the following example, a function that returns a value is defined using the Void return

type, which results in a compile-time error:

function myFunction():Void {

return "This will cause a compile-time error.";

}

/* the following function call will generate a compile-time error:

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 2: A function with return

type Void may not return a value.

return "This will cause a compile-time error.";

Trang 5

condition An expression that evaluates to true or false

statement(s) The instructions to execute if the condition evaluates to true

Returns

Nothing

Description

Statement; evaluates a condition and if the condition evaluates to true, runs a statement or series

of statements before looping back to evaluate the condition again After the condition evaluates to

false, the statement or series of statements is skipped and the loop ends

The while statement performs the following series of steps Each repetition of steps 1 through 4

is called an iteration of the loop The condition is retested at the beginning of each iteration, as

shown 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

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 curly braces ({}) used to enclose the block of statements to be executed by the while

statement are not necessary if only one statement will execute

Example

In the following example, the while statement is used to test an expression When the value of i

is less than 20, the value of i is traced When the condition is no longer true, the loop exits

Trang 7

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 statement 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 statement 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 statement

• The object specified in the object parameter in the outermost with statement

• 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 that contains the currently executing script

• The Global object (built-in objects such as Math and String)

To set a variable inside a with statement, you must have declared the variable outside the with

statement, 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 statement without declaring it, the with statement 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 statement was called

CHAPTER 2

ActionScript Language Reference

Trang 8

Instead of using with(), you can use direct paths If you find that paths are long and

cumbersome to type, you can create a local variable and store the path in the variable, which you can then reuse in your code, as shown in the following ActionScript:

var shortcut = this._parent._parent.name_txt;

shortcut.text = "Hank";

shortcut.autoSize = true;

For more information on best practices in writing code and code readability, see Chapter 3,

“Avoiding the with statement,” on page 87 of Using ActionScript in Flash.

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 because they exist in the object activation scope of the function polar(), they resolve

to the corresponding local variables

Trang 9

An XML document is represented in Flash by the XML class Each element of the hierarchical

document is represented by an XMLNode object

Note: The XML and XMLNode objects are modeled after the W3C DOM Level 1 recommendation:

www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html That recommendation

specifies a Node interface and a Document interface The Document interface inherits from the Node

interface, and adds methods such as createElement() and createTextNode() In ActionScript, the

XML and XMLNode objects are designed to divide functionality along similar lines.

Method summary for the XML class

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.

CHAPTER 2

ActionScript Language Reference

Trang 10

Property summary for the XML class

Collections summary for the XML class

Event handler summary for the XML class

XML.contentType 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 , discards, during the parsing process, text nodes that

contain only white space.

XML.lastChild Read-only; references the last child in the list for the specified node XML.loaded Read-only; checks whether 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 that indicates the success or failure of an XML

document parsing operation.

XML.xmlDecl Specifies information about a document’s XML declaration.

XML.attributes Returns an associative array that contains all the attributes of the specified

node.

XML.childNodes Read-only; returns an array that contains references to the child nodes of

the specified node.

Event handler Description

XML.onData Invoked when XML text has been completely downloaded from the

server, or when an error occurs downloading XML text from a server XML.onLoad Returns a Boolean value indicating whether the XML object was

successfully loaded with XML.load() or XML.sendAndLoad()

Trang 11

The following example creates a new, empty XML object:

var my_xml:XML = new XML();

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:

var other_xml:XML = new XML("<state name=\"California\">

<city>San Francisco</city></state>");

See also

XML.createElement() , XML.createTextNode()

Trang 12

headerName A string that represents an HTTP request header name.

headerValue A string that represents the value associated with headerName

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

The following example adds a custom HTTP header named SOAPAction with a value of Foo to

an XML object named my_xml:

Trang 13

Method; appends the specified node to the XML object’s child list This method operates directly

on the node referenced by the childNode parameter; it does not append a copy of the node If the node to be appended already exists in another tree structure, appending the node to the new location will remove it from its current location If the childNode parameter refers to a node that already exists in another XML tree structure, the appended child node is placed in the new tree structure after it is removed from its existing parent node

Example

This example does the following things in the order shown:

• Creates two empty XML documents, doc1 and doc2

• Creates a new node using the createElement() method, and appends it, using the

appendChild() method, to the XML document named doc1

• Shows how to move a node using the appendChild() method, by moving the root node from

doc1 to doc2

• Clones the root node from doc2 and appends it to doc1

• Creates a new node and appends it to the root node of the XML document doc1

var doc1:XML = new XML();

var doc2:XML = new XML();

// create a root node and add it to doc1

var rootnode:XMLNode = doc1.createElement("root");

doc1.appendChild(rootnode);

trace ("doc1: " + doc1); // output: doc1: <root />

trace ("doc2: " + doc2); // output: doc2:

// move the root node to doc2

doc2.appendChild(rootnode);

trace ("doc1: " + doc1); // output: doc1:

trace ("doc2: " + doc2); // output: doc2: <root />

// clone the root node and append it to doc1

Trang 14

var clone:XMLNode = doc2.firstChild.cloneNode(true);

doc1.appendChild(clone);

trace ("doc1: " + doc1); // output: doc1: <root />

trace ("doc2: " + doc2); // output: doc2: <root />

// create a new node to append to root node (named clone) of doc1 var newNode:XMLNode = doc1.createElement("newbie");

clone.appendChild(newNode);

trace ("doc1: " + doc1); // output: doc1: <root><newbie /></root>

Trang 15

Property; an associative array that contains all the attributes of the specified XML object

Associative arrays use keys as indexes, instead of the simple ordinal integer indexes used by regular

arrays In the XML.attributes associative array, the key index is a string representing the name of the attribute The value associated with that key index is the string value associated with that

attribute For example, if you have an attribute named color, you would retrieve that attribute’s

value by using the color as the key index, as the following code shows:

var myColor:String = doc.firstChild.attributes.color

Example

The following example shows the XML attribute names:

// create a tag called 'mytag' with

// an attribute called 'name' with value 'Val'

var doc:XML = new XML("<mytag name=\"Val\"> item </mytag>");

// assign the value of the 'name' attribute to variable y

var y:String = doc.firstChild.attributes.name;

trace (y); // output: Val

// create a new attribute named 'order' with value 'first'

doc.firstChild.attributes.order = "first";

// assign the value of the 'order' attribute to variable z

var z:String = doc.firstChild.attributes.order

trace(z); // output: first

The following is displayed in the Output panel:

Val

first

Trang 16

Read-only property; 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 the XML.appendChild(), XML.insertBefore(), and XML.removeNode() methods to manipulate child nodes

This property is undefined for text nodes (nodeType == 3)

Example

The following example shows how to use the XML.childNodes property to return an array of child nodes:

// create a new XML document

var doc:XML = new XML();

// create a root node

var rootNode:XMLNode = doc.createElement("rootNode");

// create three child nodes

var oldest:XMLNode = doc.createElement("oldest");

var middle:XMLNode = doc.createElement("middle");

var youngest:XMLNode = doc.createElement("youngest");

// add the rootNode as the root of the XML document tree

// create an array and use rootNode to populate it

var firstArray:Array = doc.childNodes;

trace (firstArray);

// output: <rootNode><oldest /><middle /><youngest /></rootNode>

// create another array and use the child nodes to populate it

var secondArray:Array = rootNode.childNodes;

trace(secondArray);

// output: <oldest />,<middle />,<youngest />

See also

XML.nodeType

Trang 17

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 the

deep parameter is set to false, or the my_xml node has no child nodes, firstChild and

lastChild are also null

Example

The following example shows how to use the XML.cloneNode() method to create a copy of a node:

// create a new XML document

var doc:XML = new XML();

// create a root node

var rootNode:XMLNode = doc.createElement("rootNode");

// create three child nodes

var oldest:XMLNode = doc.createElement("oldest");

var middle:XMLNode = doc.createElement("middle");

var youngest:XMLNode = doc.createElement("youngest");

// add the rootNode as the root of the XML document tree

// create a copy of the middle node using cloneNode()

var middle2:XMLNode = middle.cloneNode(false);

Trang 18

// insert the clone node into rootNode between the middle and youngest nodes rootNode.insertBefore(middle2, youngest);

Trang 19

The following example creates a new XML document and checks its default content type:

// create a new XML document

var doc:XML = new XML();

// trace the default content type

trace(doc.contentType); // output: application/x-www-form-urlencoded

The following example defines an XML packet, and sets the content type for the XML object The data is then sent to a server and shows a result in a browser window

var my_xml:XML = new XML("<highscore><name>Ernie</name><score>13045</score>

Trang 20

The following example creates three XML nodes using the createElement() method:

// create an XML document

var doc:XML = new XML();

// create three XML nodes using createElement()

var element1:XMLNode = doc.createElement("element1");

var element2:XMLNode = doc.createElement("element2");

var element3:XMLNode = doc.createElement("element3");

// place the new nodes into the XML tree

Trang 21

The following example creates two XML text nodes using the createTextNode() method, and places them into existing XML nodes:

// create an XML document

var doc:XML = new XML();

// create three XML nodes using createElement()

var element1:XMLNode = doc.createElement("element1");

var element2:XMLNode = doc.createElement("element2");

var element3:XMLNode = doc.createElement("element3");

// place the new nodes into the XML tree

doc.appendChild(element1);

element1.appendChild(element2);

element1.appendChild(element3);

// create two XML text nodes using createTextNode()

var textNode1:XMLNode = doc.createTextNode("textNode1");

var textNode2:XMLNode = doc.createTextNode("textNode2");

// place the new nodes into the XML tree

Trang 22

See also

XML.createElement()

Trang 23

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 XML.docTypeDecl property, but no DTD validation is performed

If no DOCTYPE declaration was encountered during a parse operation, the XML.docTypeDecl

property is set to undefined The XML.toString() method 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

Trang 24

The following example shows how to use XML.firstChild to loop through a node’s child nodes:

// create a new XML document

var doc:XML = new XML();

// create a root node

var rootNode:XMLNode = doc.createElement("rootNode");

// create three child nodes

var oldest:XMLNode = doc.createElement("oldest");

var middle:XMLNode = doc.createElement("middle");

var youngest:XMLNode = doc.createElement("youngest");

// add the rootNode as the root of the XML document tree

// use firstChild to iterate through the child nodes of rootNode

for (var aNode:XMLNode = rootNode.firstChild; aNode != null; aNode =

// loop through the strings in each language node

// adding each string as a new element in the language array

Trang 25

To view the entire script, see XML_languagePicker.fla in the HelpExamples folder:

• Windows: \Program Files\Macromedia\Flash MX 2004\Samples\HelpExamples\

• Macintosh: HD/Applications/Macromedia Flash MX 2004/Samples/HelpExamples/

See also

XML.appendChild() , XML.insertBefore() , XML.removeNode()

Trang 26

The following example shows how to use the XML.getBytesLoaded() method with the XML.getBytesTotal() method to trace the progress of an XML.load() command You must replace the URL parameter of the XML.load() command so that the parameter refers to a valid XML file using HTTP If you attempt to use this example to load a local file that resides on your hard disk, this example will not work properly because in test movie mode Flash Player loads local files in their entirety

// create a new XML document

var doc:XML = new XML();

var checkProgress = function(xmlObj:XML) {

var bytesLoaded:Number = xmlObj.getBytesLoaded();

var bytesTotal:Number = xmlObj.getBytesTotal();

var percentLoaded:Number = Math.floor((bytesLoaded / bytesTotal ) * 100); trace ("milliseconds elapsed: " + getTimer());

trace ("bytesLoaded: " + bytesLoaded);

trace ("bytesTotal: " + bytesTotal);

trace ("percent loaded: " + percentLoaded);

doc.load("[place a valid URL pointing to an XML file here]");

var intervalID:Number = setInterval(checkProgress, 100, doc);

See also

XML.getBytesTotal()

Trang 28

var my_xml:XML = new XML("<login><username>hank</username>

<password>rudolph</password></login>");

if (my_xml.firstChild.hasChildNodes()) {

// use firstChild to iterate through the child nodes of rootNode

for (var aNode:XMLNode = my_xml.firstChild.firstChild; aNode != null; aNode=aNode.nextSibling) {

Trang 29

The following example loads an XML file with a text node that contains only white space; the

foyer tag comprises fourteen space characters To run this example, create a text file named

flooring.xml, and copy the following tags into it:

Create a new Flash document named flooring.fla and save it to the same directory as the XML file

Place the following code into the main Timeline:

// create a new XML object

var flooring:XML = new XML();

// set the ignoreWhite property to true (default value is false)

Trang 30

/* output (line breaks added for clarity):

• Windows: \Program Files\Macromedia\Flash MX 2004\Samples\HelpExamples\

• Macintosh: HD/Applications/Macromedia Flash MX 2004/Samples/HelpExamples/

Trang 31

childNode The XMLNode object to be inserted.

beforeNode The XMLNode object 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 the appendChild()

method If beforeNode is not a child of my_xml, the insertion fails

Example

The following example is an excerpt from the XML.cloneNode() example:

// create a copy of the middle node using cloneNode()

var middle2:XMLNode = middle.cloneNode(false);

// insert the clone node into rootNode between the middle and youngest nodes rootNode.insertBefore(middle2, youngest);

See also

XMLNode class

Trang 32

Read-only property; an XMLNode value that references the last child in the node’s child list The

XML.lastChild property is null if the node does not have children This property cannot be used to manipulate child nodes; use the appendChild(), insertBefore(), and removeNode()

methods to manipulate child nodes

Example

The following example uses the XML.lastChild property to iterate through the child nodes of an XML node, beginning with the last item in the node’s child list and ending with the first child of the node’s child list:

// create a new XML document

var doc:XML = new XML();

// create a root node

var rootNode:XMLNode = doc.createElement("rootNode");

// create three child nodes

var oldest:XMLNode = doc.createElement("oldest");

var middle:XMLNode = doc.createElement("middle");

var youngest:XMLNode = doc.createElement("youngest");

// add the rootNode as the root of the XML document tree

// use lastChild to iterate through the child nodes of rootNode

for (var aNode:XMLNode = rootNode.lastChild; aNode != null; aNode =

Trang 33

XML.lastChild 1033

The following example creates a new XML packet and uses the XML.lastChild property to iterate through the child nodes of the root node:

// create a new XML document

var doc:XML = new XML("<rootNode><oldest /><middle /><youngest /></

rootNode>");

var rootNode:XMLNode = doc.firstChild;

// use lastChild to iterate through the child nodes of rootNode

for (var aNode:XMLNode = rootNode.lastChild; aNode != null;

Trang 34

is executed

In SWF files running in a version of the player earlier than Flash Player 7, the url parameter must

be in the same superdomain as the SWF file that issues this call A superdomain is derived by

removing the leftmost component of a file’s URL For example, a SWF file at

www.someDomain.com can load data from sources 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, the url parameter must be in exactly the same domain (see “Flash Player security features” in Using ActionScript in Flash) For

example, a SWF file at www.someDomain.com can load data only from sources that are also at

www.someDomain.com If you want to load data from a different domain, you can place a

cross-domain policy file on the server that is hosting the SWF file For more information, see “About

allowing cross-domain data loading” in Using ActionScript in Flash.

When the load() method 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 event handler 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 define a custom function that executes when the onLoad event handler of the XML object is invoked

Example

The following simple example uses the XML.load() method:

// create a new XML object

var flooring:XML = new XML();

// set the ignoreWhite property to true (default value is false)

Trang 36

The following example uses the XML.loaded property in a simple script:

var my_xml:XML = new XML();

Trang 37

methods to manipulate child nodes

Example

The following example is an excerpt from the example for the XML.firstChild property, and shows how you can use the XML.nextSibling property to loop through an XML node’s child nodes:

for (var aNode:XMLNode = rootNode.firstChild; aNode != null; aNode =

Trang 38

The following example creates an element node and a text node, and checks the node name of each:

// create an XML document

var doc:XML = new XML();

// create an XML node using createElement()

var myNode:XMLNode = doc.createElement("rootNode");

// place the new node into the XML tree

doc.appendChild(myNode);

// create an XML text node using createTextNode()

var myTextNode:XMLNode = doc.createTextNode("textNode");

// place the new node into the XML tree

var my_xml:XML = new XML("<login><username>hank</username>

<password>rudolph</password></login>");

if (my_xml.firstChild.hasChildNodes()) {

// use firstChild to iterate through the child nodes of rootNode

for (var aNode:XMLNode = my_xml.firstChild.firstChild; aNode != null; aNode=aNode.nextSibling) {

if (aNode.nodeType == 1) {

Trang 40

In Flash Player, the built-in XML class only supports 1 (ELEMENT_NODE) and 3 (TEXT_NODE).

Example

The following example creates an element node and a text node, and checks the node type of each:

// create an XML document

var doc:XML = new XML();

// create an XML node using createElement()

var myNode:XMLNode = doc.createElement("rootNode");

// place the new node into the XML tree

doc.appendChild(myNode);

// create an XML text node using createTextNode()

Integer value Defined constant

Ngày đăng: 24/12/2013, 01:17

TỪ KHÓA LIÊN QUAN

w