Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
101
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 2

A method is always followed by a pair of round brackets, which contain any parameters that the method accepts. In this instance, the getDay method takes no parameters, so the brackets remain empty:

var specialDate:Date = new Date(2006, 5, 3); specialDate.setYear(2007);

trace(specialDate.getDay()); // Returns 0, which is Sunday

The Date class consists only of methods; to see a property in action, convert the date to a string, and assign it to a text field:

var specialDate:Date = new Date(2006, 5, 3); this.createTextField(“specialDateField”, 1, 0, 0, 200, 20); this.specialDateField.text = currentDate.toString();

A few things are going on in this code. Starting on the second line, this is a special movie clip reference that points to the current timeline. One of the methods available to all movie clips is createTextField(). (You can find more details about the movie clip class within the Flash help panel under ActionScript 2.0 Reference ActionScript Classes MovieClip.) createTextField() assigns the new text field to _level0, which is made into a property that can be accessed through dot notation as _level0.specialDateField. (Don’t worry about the other parameters for now.)

According to the TextField class documentation, the text property enables you to set the contents of the text field. The last line takes a string representation of the date and assigns it to the text property for the text field. The last line also shows how dot notation can be used to chain together properties and methods. The specialDateField property is made available from _level0, and the text property is in turn made available from specialDateField.

There’s really no limit to the number of methods and properties that can be chained together, although as you can imagine, as the number increases, it becomes more and more difficult to read the code. Chaining is very useful for accessing nested movie clips, something you see more of in Chapter 4.

Discerning Special Variables and Keywords

A number of special variables are built into the Flash player. Of particular note are _level0, _root, _global, and this. The first three should be avoided, but you should know what they are and why to avoid them. The last one, this, is a very useful keyword that’s important to understand. The following sections discuss each of these.

_root

Flash uses the concept of movie clips, where each movie clip is a container that can contain other content, such as images, graphics, or other movie clips. When you start with a completely empty slate, there is still one special movie clip that makes up the main stage that you see. That starting movie clip always exists; it is called the root timeline, and it can be accessed from any script in any timeline through the _root keyword. For example, if you drag a button component onto the stage from the Components panel, and change the instance name to saveButton, you can refer to that button from any other timeline by accessing _root.saveButton. To reposition the button, for instance, you could do the following:

_root.saveButton._x = 20;

_root.saveButton._y = 10;

38

Getting Started with ActionScript 2.0

You should avoid using the _root keyword because it prevents your code from being reusable in anything other than a project with the same movie clip structure as yours, which is not very likely. If you were to load your movie into another movie, the _root references would then refer to that parent movie, and your code would fail completely. The alternative is to use relative addressing using _parent and this keywords. You learn more about this in later chapters.

_level0

Flash is organized so that content can be layered in different ways, with separate layerings for depths and for levels. Each movie clip uses the concept of depth, in that each item placed within a movie clip is placed on a different depth number. If any two separate units of content within the same movie clip overlap, the content in the higher depth shows over the content with the lower depth number. This behavior is seen within the visual development environment when creating two layers within the timeline and placing content in each of those layers assigns the content to two different depths. It also can be seen with the movie clip method createEmptyMovieClip(<name>, <depth>), which requires that a depth number that is unique within the parent movie clip be assigned to the new movie clip.

Levels are similar to depths, however they exist only at the top of a movie, and they are managed differently. At least one depth is always in use, which is referred to by the keyword _level0. This keyword works in exactly the same way as the _root keyword, and in fact _level0 and _root are synonyms — both can be called from any timeline to refer to the base of the movie. The same issue about using _root also applies to _level0, so you are discouraged from using it. This book does not cover the use of levels because that is a legacy feature better served by loading content into movie clips, which is discussed later in the book.

_global

_global is a special keyword that enables you to access a variable from any code anywhere. By simply assigning data to any global variable you create, you can access that data from anywhere. For example, if you create a global variable called currentScore:

_global.currentScore = 200;

You can refer to it variable from anywhere as

trace(_global.currentScore);

Although this may be convenient, it is discouraged for a few reasons:

You cannot strongly type a global variable, so type-related errors are harder to debug.

It encourages sloppy programming, especially when you start working with functions.

It is harder to find all the places where the global variable is being manipulated.

You spend more time with global variables in Chapter 5.

this

The this keyword refers to the parent of whatever code is making the reference. When the reference is made in code that sits in a movie clip, it refers to the movie clip holding the code. Here’s a trace statement called from the root timeline:

39

Chapter 2

trace(this); // Outputs: _level0

If the same trace statement were made in another nested movie clip, it would show the path to that movie clip.

If you drag a button component onto the stage from the Components panel and change the instance name to saveButton, you can refer to that button from the same timeline by accessing this.saveButton, like this:

this.saveButton._x = 20;

this.saveButton._y = 10;

The this keyword is often implied, so you could refer to saveButton on its own to achieve the same result.

You see more of this in action in Chapter 7.

Working with Collections of Data

So far you’ve looked at variables that contain only one thing at a time. Now take a look at some types of variables that can store multiple things, namely arrays and associative arrays.

Understanding Arrays

An array is a container that can hold any number of individual pieces of data. Each piece of data within a particular array needs to be of the same data type, so one array could potentially store a sequence of strings, and another array could store just true and false values. In general, each item stored in the array is somehow related and used in a similar fashion to every other item. For example, an array might be used to store a list of high scores, or perhaps a list of logged-in users.

Arrays are always indexed by sequential integers, starting with 0. In an array of 50 elements, for example, the last element is found at index number 49. It might seem a little odd to represent the first array element by the number 0, but it is a convention adopted from the C language where it makes for faster array access, and is used in C++, Java, and most other modern programming languages.

Arrays are created through the following syntax:

var loggedInUsers:Array = new Array();

The first part of the syntax, var loggedInUsers:Array, should look familiar by now; here, though, it uses a new data type: Array. new is a special keyword that makes a copy of whatever follows it, and Array()can be thought of as a template that the new keyword copies from and assigns to the loggedInUsers variable. The end result is that once this line is invoked, loggedInUsers contains an empty data structure that is then used to actually hold your data.

Arrays can also be created and simultaneously pre-populated with data, as the following example shows:

var loggedInUsers:Array = new Array(“johndoe”, “janedoe”);

40

Getting Started with ActionScript 2.0

Here the loggedInUsers array is declared and populated with two elements, “johndoe” and “janedoe”. There is also an alternate syntax:

var loggedInUsers:Array = [];

var loggedInUsers:Array = [“johndoe”, “janedoe”];

The syntax used is largely personal preference; however, the first version is more explicit and is used throughout this book.

To set or retrieve any particular element in an array, use the square bracket syntax for the index number of the element to access:

var loggedInUsers:Array = new Array(“johndoe”, “janedoe”); trace(loggedInUsers[0]);

//Outputs: johndoe trace(loggedInUsers[1]);

//Outputs: janedoe

Do not worry about having to know which piece of data corresponds to which index. The purpose of an array is to provide an easy mechanism to search through data. You use indexes in Chapter 3 when you explore loops, which enable you to go through each element in an array and do something useful with it. The main purpose at this point for the indexes is to provide an ordering to the data, so that element zero is stored before element one, which is stored before element two, and so on.

You can add data to an array in two ways: by using the push() method or by assigning a value to a particular array element. The push() method is convenient because it does not need to know how many elements are already defined: it automatically appends the data after the last defined array element. The following example shows the creation and population of the loggedInUsers array, and then the use of push() to add another element to the array:

var loggedInUsers = new Array(); loggedInUsers[0] = “johndoe”; trace(loggedInUsers);

// Outputs: johndoe

loggedInUsers.push(“janedoe”);

trace(loggedInUsers);

// Outputs: johndoe,janedoe

Macromedia Flash does not force elements to be assigned values starting at position 0 in the array. Assigning a value to a particular non-zero element before assigning values to elements earlier in the array, however, causes the earlier elements to be listed as undefined, as the following example shows:

var loggedInUsers = new Array(); loggedInUsers[3] = “johndoe”;

trace(loggedInUsers);

// Outputs: undefined,undefined,undefined,johndoe

This is generally not a recommended approach to assigning data to an array.

An array’s length property is determined solely on the position of the last element. If element 3 is the last element containing data, the length of the array is 4. If an array contains no defined elements, its length is 0.

41

Chapter 2

The keywords null and undefined have special meanings in ActionScript. A variable that has been declared with the var keyword but contains no data is represented by the null value, whereas a variable that has not been declared at all is represented by the undefined value.

Once an array has been populated with data, numerous methods are available to manipulate it, including the following:

Method

Description

 

 

concat()

Combines two arrays into one single array, or adds any number of elements

 

to the end of one array.

join()

Joins each array element into a single string value.

push()

Adds a new element to the end of an array.

reverse()

Reverses the order of an array.

shift()

Removes the first element of an array, and returns that element.

slice()

Extracts a range of elements from an array.

sort()

Changes the ordering of elements in an array.

sortOn()

Changes the ordering of elements in a multidimensional array based on a

 

specific field.

splice()

Adds and removes elements in an array.

toString()

Outputs a string representation of an array.

unshift()

Adds elements to the beginning of an array.

 

 

The following sections explore some of the more common array methods.

concat()

The concatenation method — concat() — takes two arrays and combines them, or takes one array and adds elements to the end. The method does not directly manipulate the source array(s); instead, it concatenates the array values together and returns a new array. Here are some examples:

//Join two arrays together, then assign the new joined array back to

//the variable firstArray.

var loggedInUsers:Array = new Array(“johndoe”, “janedoe”, “rahibdoe”); var recentUsers:Array = new Array(“ngt”, “loc”);

loggedInUsers = loggedInUsers.concat(recentUsers); trace(loggedInUsers);

//Outputs: johndoe,janedoe,rahibdoe,ngt,loc

//Add elements to the end of an array

var newlyAddedUsers:Array = new Array(“ngt”, “loc”);

42

Getting Started with ActionScript 2.0

newlyAddedUsers = newlyAddedUsers.concat(“schin”, “bchan”); trace(newlyAddedUsers);

// Outputs: ngt,loc,schin,bchan

join()

The join() method is used to output a string representation of an array. The method converts each array element to a string, and then places each of those strings together into one large string, separated by a delimiter character. The delimiter character that is passed to join() can be anything you want, and it can actually be more than one character in length. If no delimiter is specified, a comma is used. The join() method does not touch the original array; instead, the new string is passed as a return value that can then be assigned to another variable or passed as a parameter to another method. Here’s an example:

// Concatenate each of the array elements together.

var loggedInUsers:Array = new Array(“johndoe”, “janedoe”, “rahibdoe”);

trace(loggedInUsers.join(“:”));

// Outputs: johndoe:janedoe:rahibdoe

The counterpart to the join() method is the split() method, which chunks up a string into an array. There are some very powerful ways of doing string manipulation by chaining together join() and split() methods. See Chapter 18 for more on using these methods together.

push()

As you saw earlier, the push() method is an easy way to add elements to an array. Without it, adding an element to the end of an existing array would look like this:

loggedInUsers[loggedInUsers.length-1] = “johndoe”;

push() makes it simpler:

loggedInUsers.push(“johndoe”);

This syntax is more readable, is easier to understand, and results in comparable performance.

sort()

Thankfully, ActionScript arrays come with built-in methods to perform various sorting tasks. The built-in documentation for the sort() method makes it look a little intimidating, but it is in fact very simple to use.

To sort an array in ascending alphabetical order (from a to z), use sort() with no additional options specified:

var birdsArray:Array = new Array(“robin”, “hummingbird”, “parakeet”, “crane”); birdsArray.sort();

trace(birdsArray);

// Outputs: crane,hummingbird,parakeet,robin

To sort an array in descending order (from z to a), add the DESCENDING parameter to sort():

var birdsArray:Array = new Array(“robin”, “hummingbird”, “parakeet”, “crane”); birdsArray.sort(Array.DESCENDING);

trace(birdsArray);

// Outputs: robin,parakeet,hummingbird,crane

43

Chapter 2

A number of other options can be passed to sort(), including the following:

Array.CASEINSENSITIVE — Letter case is ignored when determining sort order.

Array.UNIQUESORT — Specifies that any particular value cannot appear more than once in an array. The sort stops early if it finds that this is the case.

Array.RETURNINDEXEDARRAY — Leaves the original array unchanged, and returns a sorted copy of the array.

Array.NUMERIC — The array is sorted by number rather than by string, allowing 3 to come before 15 in the sort order.

Multiple options can be passed if each is separated by the | symbol.

When sorting strings, it is a good idea to use the case-insensitive search; otherwise you might not get what you expect in the results. For example:

var birdsArray:Array = new Array(“robin”, “Woody Woodpecker”, “crane”, “parakeet”); birdsArray.sort();

trace(birdsArray);

// Outputs: Woody Woodpecker,crane,crane,parakeet,robin

A standard sort — sort() — lists uppercase elements before listing lowercase ones. Now if you sort the same array using the Array.CASEINSENSITIVE option, all of the elements are output in alphabetical order, which is probably the result you want:

birdsArray.sort(Array.CASEINSENSITIVE);

trace(birdsArray);

// Outputs: crane,crane,parakeet,robin,Woody Woodpecker

To sort a numerical array, use the Array.NUMERIC option. Here’s why:

// Perform sort on an array of numbers

var fileSizes:Array = new Array(15, 3, 260, 22, 43); fileSizes.sort();

trace(fileSizes);

// Outputs: 15,22,260,3,43

The standard sort() outputs the elements in the order of the first digit (the 1 in 15, the 2 in 22 and 260, and so on). The Array.NUMERIC option considers the entire element in its sort:

fileSizes.sort(Array.NUMERIC);

trace(fileSizes);

// Outputs: 3,15,22,43,260

Here’s an example of combining options, resulting in a reverse numerical output (two options, separated by a |):

fileSizes.sort(Array.NUMERIC | Array.DESCENDING); trace(fileSizes);

// Outputs: 260,43,22,15,3

44

Getting Started with ActionScript 2.0

splice()

The splice() method enables you to add and delete the array in one call. The general splice syntax is as follows:

myArray.splice(index, numDelete, addedElements);

You delete elements by setting the index from which to start deletion, and passing in the number of elements to delete:

var birdsArray:Array = new Array(“robin”, “crane”, “parakeet”);

//Delete two elements, starting from array index 1. birdsArray.splice(1, 2);

trace(birdsArray);

//Outputs: robin

Replacing elements is a combination of adding and removing elements at the same time. First, elements are deleted starting from the index number provided in the first parameter, and then elements are inserted, also starting from the index number provided:

var birdsArray:Array = new Array(“robin”, “crane”, “parakeet”);

//Delete one element at index 1, then insert

//elements “blue jay” and “finch” at index 1. birdsArray.splice(1, 1, “blue jay”, “finch”); trace(birdsArray);

//Outputs: robin,blue jay,finch,parakeet

One element at index 1, “crane”, is deleted, and then “blue jay” and “finch” are inserted at index 1, pushing anything currently at position one and later further to the right.

If you want to add elements at one index and remove elements at another index, you need to use two separate splice() calls specifying two different indexes, like this:

var birdsArray:Array = new Array(“robin”, “crane”, “parakeet”);

//Delete “robin” at index 0 birdsArray.splice(0, 1);

//Insert “blue jay” element at index 1 birdsArray.splice(1, 0, “blue jay”); trace(birdsArray);

//Outputs: crane,blue jay,parakeet

Here, element 0 ”robin” — is deleted, and then “blue jay” is inserted at element 1.

Exploring Associative Arrays and Objects

An associative array is very similar to the indexed array, but instead of defining an order (index) to pieces of data, it defines relationships among data pairs. For example, say the following pieces of data are to be stored:

User nderksen is a guest.

User jberg is an administrator.

User msmithe is a moderator.

45

Chapter 2

These three pairs of related data are represented by the following associative array:

var userAccountsArray:Object = new Object(); userAccountsArray[“nderksen”] = “guest”; userAccountsArray[“jberg”] = “administrator”;

userAccountsArray[“msmithe”] = “moderator”; trace(userAccountsArray[“nderksen”]);

// Outputs: guest

With the data stored in this manner, doing a lookup requires no looping through data to find a value. A quick single trace line does the trick.

The general form for an associative array is as follows:

var myAssociativeArray:Object = new Object();

myAssociativeArray[<key>] = <value>;

An associative array behaves differently from a regular array in several important ways:

Associative arrays are indexed by string, not by number.

The ordering of elements in an associative array is not guaranteed. Element order can change as the associative array is manipulated.

Array methods and properties, such as push(), splice(), and length, do not apply to associative arrays.

An associative array is not created by making a new instance of the Array class, as indexed arrays are. Instead, it is created through a new instance of the Object class. Before you learn why this is the case, you should understand the Object class.

An associative array can be created from an array instance, but none of the Array class’s properties or methods will work on the array. Historically, associative arrays were frequently implemented this way; however, the proper technique is to create them by instantiating the Object class.

Viewing the Object Class as a Container

The Object class is the base class from which all other ActionScript classes are derived. Through the mechanism of inheritance, all classes have access to the methods and properties that the Object class provides. In addition, the Object class acts as a container that can store related pairs of data.

Two ways exist to create a new copy of the Object class. The first uses the new keyword to generate the Object instance and then assigns values to properties that you make up:

var userData:Object = new Object(); userData.firstName = “Nathan”; userData.lastName = “Derksen”; trace(userData.firstName);

//Outputs: Nathan trace(userData.lastName);

//Outputs: Derksen

Most classes don’t let you just make up arbitrary properties on-the-fly, but the Object class does. As a result, it makes a great container for data.

46

Getting Started with ActionScript 2.0

The second approach uses a shorthand notation that creates the object and assigns the properties in one step:

var userData:Object = {firstName:”Nathan”, lastName:”Derksen”}; trace(userData.firstName);

//Outputs: Nathan trace(userData.lastName);

//Outputs: Derksen

Once an Object container contains data, two ways exist to retrieve that data. The first accesses the property directly through dot notation, as you just saw with userData.firstName. Here’s an example of the second:

var userData:Object = {firstName:”Nathan”, lastName:”Derksen”}; trace(userData[“firstName”]);

//Outputs: Nathan trace(userData[“lastName”]);

//Outputs: Derksen

Are you thinking, “Didn’t I just see this a moment ago?” Indeed you did! This syntax is identical to the syntax for accessing associative array elements. It turns out that associative arrays are just another front to the Object class, and the two syntaxes are completely interchangeable.

The following example shows how values are set with the associative array notation and retrieved with the dot notation:

var userData:Object = new Object(); userData[“firstName”] = “Nathan”; userData[“lastName”] = “Derksen”; trace(userData.firstName);

//Outputs: Nathan trace(userData.lastName);

//Outputs: Derksen

Revisiting the Associative Array

Although the associative array and the Object are really the same thing, it is still useful to conceptually separate the two. By combining an associative array with a collection of objects, you can store much more complex sets of data. Here’s some example data to illustrate how that’s done:

User nderksen is a guest; has been a forum member since April 1, 2005; and has made 24 posts.

User jberg is an administrator; has been a forum member since February 18, 2003; and has made 1,824 posts.

User msmithe is a moderator; has been a forum member since September 9, 2004; and has made 943 posts.

The information can be easily stored and accessed using a combination of associative array and Object syntax:

var userAccountsArray:Object = new Object();

userAccountsArray[“nderksen”] = {group:”guest”, joined:”2005/04/01”, posts:24};

userAccountsArray[“jberg”] = {group:”administrator”, joined:”2003/02/18”, ; posts:1824};

47