2. Working with Events and Functions

Lesson overview

In this lesson, you will learn to do the following:

• Use code snippets to create ActionScript that navigates the Flash Timeline in response to button clicks.

• Add code to a function created by a code snippet.

• Write event listeners to listen for mouse events.

• Write event-handling functions that respond to mouse events.

• Combine strings of text with variable values to populate a text field.

• Create and call a function that sets the language in a text field.

• Use buttons to change the value of a variable.

This lesson will take approximately 2 hours.

image

In the previous lesson, you created code directly in frames of the Timeline that ran automatically when the frame containing the code played. You also began working with events when you added the code snippet to the Lesson 1 file. In this lesson, you will get a deeper understanding of events in ActionScript. Understanding the event model in ActionScript 3.0 is probably the biggest step in mastering the basics of the language and being able to create rich interactive applications.

ActionScript 3.0 has many built-in events, and many actions can occur when an event takes place. A large part of learning ActionScript is learning what events are available and determining how to respond when an event takes place. And as you get more comfortable with ActionScript, you can create your own custom events.

image

ActionScript events and functions create more interactive possibilities for you and your users.

The process of working with events is not complex. You write code that tells an object to listen for an event, and you write a function that occurs in response to that event. Unlike in ActionScript 1 and 2, the basic syntax for listening and responding to events is the same throughout ActionScript 3.0. However, mastering this syntax can challenge many beginners. The good news is that in Flash CS5, you can use the Code Snippets panel to write the syntax to create basic event listeners. This panel also provides a terrific way to become familiar with ActionScript syntax.

In this lesson, you will first use code snippets to write an event listener that navigates the Flash Timeline when a button is clicked. You will then gradually transition to writing your own event listener functions.

Working with event-handling functions

Listening to and responding to an event in ActionScript is a two-part process. One piece of code, called an addEventListener() method, gives the instruction to listen for a specific event from a particular object. Another piece of code, called an event-handler function, responds when that event takes place.

For example, if you have a button onstage, you might want it to do three things:

• Display a menu when the user rolls over the button.

• Hide the menu when the user rolls off the button.

• Navigate to a frame on the Timeline when the user clicks the button.

This example uses only one button, but there are three separate events to listen for (ROLL_OVER, ROLL_OUT, and CLICK), and three separate sets of actions that may occur, depending on which event took place.

For the first event in our example, if the instance name of the button were button1, you would tell ActionScript to listen for the ROLL_OVER event, like this:

button1.addEventListener(MouseEvent.ROLL_OVER, showMenu);

There would be a similar line of code for the ROLL_OUT and CLICK events.

You use an addEventListener method to tell an object in ActionScript 3.0 to begin listening for a specific event. Once addEventListener is called, it continues to listen until it is removed. The first element inside the parentheses of the addEventListener method indicates which event to listen for. In this case, from the category MouseEvent, we are specifically listening for ROLL_OVER. Notice that the actual event names are all uppercase with underscores between words. The convention of using the uppercase constants for event names may give you a little extra to remember when you are beginning, but it also helps identify errors when compiling the files and is worth the effort to memorize.

After the event name, and separated by a comma, is the name of the function that occurs when the ROLL_OVER event takes place. A function is just a block of code that performs one or more, usually related, tasks. An event-handler function is one that responds to an event.

Functions can be created and given any name that you like, following the same three rules that we saw for naming variables in Lesson 1, “Using Code Snippets and Navigating the Flash Timeline.” In the example, the function name is showMenu. It is a good idea to name functions so that they describe what they are supposed to do.

The basic syntax for our function looks like this:

function showMenu(e:MouseEvent):void {
//all the ActionScript to show the menu would go here between the
//left and right curly braces.
}

Note

ActionScript is always case sensitive. You may notice in the function and variable names in this book and other places the odd convention of starting with a lowercase character and then beginning subsequent words in the name with uppercase characters, as in showMenu(). While this convention is by no means required, it is a common programming practice, sometimes referred to as “camel case,” that helps indicate what type of item is being dealt with. You may want to consider adopting this convention in your work.

When creating a function in ActionScript 3.0, always start with the lowercase word function and then the name you choose to give your function. After that, you add a set of parentheses that contains what are called parameters. You will work with parameters more in the coming lessons; for now, it is enough to know that the required parameter for an event-handling function contains a reference to the event that triggered the function.

After the parentheses, a colon precedes information about the type of data that the function returns. In this case, void means that the function does not return data. You will learn much more about functions in coming lessons.

After that, a pair of curly braces contains all the code that will take place each time an event triggers the function.

If all this is not absolutely clear, don’t worry. After a little practice, it begins to make more and more sense, and pretty soon the process will be second nature. And the payoff will be worth it. As already mentioned, becoming comfortable working with event listeners and event-handling functions is probably the biggest step in learning ActionScript 3.0, and the technique is consistent through the entire language. So what you learn in this lesson will be your entryway into many of the interactive possibilities with ActionScript 3.0.

As you saw in Lesson 1, code snippets can be used to create functions that respond to mouse events. You will begin this lesson by using a code snippet that creates an eventListener function that navigates the Flash Timeline when a button is clicked. After this, you will gradually make the transition to writing eventListener code yourself.

In your own work, you may prefer to continue to use code snippets as a starting point, or you may find that you can eventually work more efficiently by typing your code yourself.

Using code snippets to create navigation

This lesson will start with the file from Lesson 1. You can start this exercise with your completed version of that file; otherwise, in Flash CS5, open the lesson02_start.fla file in the Lessons > Lesson02 > Start folder.

image

Creating button instances to control navigation

For many simple Flash web projects, most interactivity consists of navigation triggered by button clicks. The ability to write ActionScript that responds to a button CLICK event is also the foundation for understanding much of the rest of the ActionScript language, since all other ActionScript events work in similar ways.

To get you started with this important functionality, Flash CS5 ships with a collection of code snippets that write code to create timeline navigation triggered by button clicks. You will soon use one of these snippets, after we add a new button to the project.

  1. In the Flash Timeline, select Frame 1 of the buttons layer.
  2. If it is not already visible, open the Library panel (Window > Library).
  3. From the Library panel, drag an instance of the Button component and place it next to the existing Flash Support button at the lower-right corner of the Stage.
  4. Select the new button onstage, and in the Component Parameters section of Property inspector (Window > Properties), locate the label property.
  5. In the field to the right of the label property, type Home and press Enter (Windows) or Return (Mac).

    You should see the label on the button update to “Home.” You will use this button to allow the user to navigate to the home frame.

    Now give the button an instance name.

  6. With the Home button selected, go to the Property inspector, place the cursor in the instance name field, and give the button the instance name home_btn.

    image

    Note

    Instance names follow the naming rules already discussed for variables and functions.

Adding a code snippet for navigation

The intended purpose of the Home button you just added is to allow the user to jump to the frame of the Timeline labeled home when the button is clicked. You can use the Code Snippets panel to add some code to make this work.

  1. If they are not already visible, open the Actions panel (Window > Actions) and the Code Snippets panel (Window > Code Snippets).
  2. In the Timeline, select Frame 2 of the Actions panel. This is the frame where you will place the code snippet.
  3. On the Stage, select the button with the label Home. Remember that this button has been given the instance name home_btn.
  4. In the Code Snippets panel, open the Timeline Navigation folder and double-click the snippet named Click To Go To Frame And Stop.

    image

    You should now see the following code in the Actions panel below the code that was already there:

    image

The code snippet that was created added an event listener for the Home button instance. Now, when the button is clicked it will automatically call the function that is somewhat verbosely named fl_ClickToGoToAndStopAtFrame (changing the function name in a code snippet does not modify its behavior, and you will change this function’s name in the next section).

When a function is called, all the code between the curly braces is executed. In this case, that means that when the user clicks the Home button, the function will send the Timeline to Frame 5. The goto action is the same as we used in Lesson 1. The only difference is that now it is triggered by a button event. You will modify the frame that this function navigates to in the next section.

Modifying the code snippet

Code snippets provide a very easy way to create correct ActionScript syntax, but rarely does any given code snippet perform exactly the function that you want. More typically, you choose that snippet that most closely matches your needs and then customize the code to suit your purpose. You will make a few modifications to the code snippet you just created to make it perform the way you want and make it easier to read.

Remember that the light gray characters in the code snippet are descriptive and nonfunctional comments. If you read the Instruction comments, you will see that to make this code navigate to a desired frame, you replace the number 5 in the line that reads

gotoAndStop(5);

with a reference to the frame that you actually want the user to go to. One way to do this is to simply replace the 5 with a different number. In the case of the home frame, this would be Frame 50. However, a better way to refer to this frame in the code would be by its label name. Using label names instead of frame numbers in your scripts makes it much easier to make changes to the content in the frames of your Timeline without having to modify your code. You use frame labels in a goto method by typing the label name in quotation marks between the parentheses that now contain the number 5.

  1. In the Actions panel, modify the line that reads:

    gotoAndStop(5);

    so that it now reads:

    gotoAndStop("home");

  2. Save your work and test your movie (Control > Test Movie). If you click the Home button while the opening animation is playing, the Timeline should skip directly to the home frame.
  3. Close the lesson02_start.swf file to leave the testing environment.

    You can see how easy it is to modify the code snippet to achieve the desired navigation.

    It would be no problem to leave this code as it is in your project. However, a couple of additional modifications to the code snippet will make it easier to work with as your project develops.

    One change you may wish to make to the code snippet is renaming the function. Right now the function has the long and generic name fl_ClickToGoToAndStopAtFrame. It is a good practice to name your functions in a way that describes their specific purpose. Let’s change the snippet’s default function name to the shorter and more descriptive name goHome. You will need to change this name in two places: in the addEventListener method and in the function itself.

  4. In the Actions panel, locate the line that reads:

    home_btn.addEventListener(MouseEvent.CLICK, fl_ClickToGoToAndStopAtFrame);

  5. Change this line to:

    home_btn.addEventListener(MouseEvent.CLICK, goHome);

  6. Next locate the line that reads:

    function fl_ClickToGoToAndStopAtFrame(event:MouseEvent):void {

  7. Change this line to:

    function goHome(event:MouseEvent):void {

    Changing the function name in this way has no effect on the code’s behavior, but it does make it more succinct and easier to understand.

    After you have used a code snippet a few times and understand the included comments (in gray), you may want to delete the comments; doing so does not affect the behavior of the code.

  8. Delete the comments.

    Here is the code so far for Frame 2 with comments removed:

    info_txt.text = String(count);

    home_btn.addEventListener(MouseEvent.CLICK, goHome);

    function goHome(e:MouseEvent):void {
     gotoAndStop("home");
    }

As you get more comfortable with ActionScript, you will probably want to make a few additional modifications to this code to make it still easier to read, but for now let’s move on.

Having successfully created button navigation with a code snippet, you will now try creating similar code by typing it yourself.

Creating event listeners

Although code snippets are convenient, to get the most out of ActionScript 3.0 it is important to be thoroughly confident in your understanding of basic ActionScript syntax. This competence comes only with time, study, and practice. Once you have mastered the syntax for an ActionScript task, you may still find that code snippets are often a great time-saving tool. Now, though, it’s time to begin writing ActionScript code on your own. You’ll start by creating another event listener, writing your own code from scratch.

Adding a restart button

Now let’s add some functionality on the home page to enable the user to restart the animation.

  1. Add a keyframe (F6) to the buttons layer on the home frame.
  2. Click somewhere on the Stage away from the two buttons to deselect them, and then select just the Home button.
  3. With the Home button selected, go to the Property inspector (Window > Properties) and change the label name from Home to Restart.
  4. Also in the Property inspector, with the button still selected, change the button’s instance name from home_btn to restart_btn.
  5. With the Actions panel visible, select the home frame of the actions layer.
  6. Add the following code in the Actions panel below the existing code:

    restart_btn.addEventListener(MouseEvent.CLICK, goStart);

    Be careful to match the capitalization exactly, and notice that addEventListener and MouseEvent.CLICK turn blue when typed correctly. The color-coding of ActionScript as you type provides useful feedback to let you know you are typing things correctly. Keywords in ActionScript 3.0 turn blue by default. If you type something that is part of the ActionScript language and it appears as black text, double-check your spelling and capitalization.

    Note

    It doesn’t matter how many empty lines you place between sections of your code. Many programmers like to leave space between sections of code for clarity; others like to keep things concise by starting new blocks of code on every line. As you start to get comfortable with ActionScript, you will find a style that you prefer.

    After this code has been added, when the Restart button is clicked it will try to call a function named goStart. So, let’s add this function to make the code work.

  7. In the Actions panel, on a line below the code you just added, insert the following code:

    function goStart(e:MouseEvent):void {
     count=1;
     gotoAndPlay("loop");
     }

    This function will be the one that responds to a click of the Restart button. When the function is called, the Timeline will be sent back to the beginning of the animation, and the variable count will be reset to 1. Remember that count is the variable that keeps track of the number of times that the opening animation has played, so by setting count to 1, you are restarting the movie with its initial setting.

  8. Save your work and test your movie.

    When you reach the home frame in the testing environment, the button that previously said “Home” should now say “Restart.” The Restart button should respond to the code you added by replaying the opening animation, with the button again reading “Home.” Notice that the Flash Support button works the same throughout. Because you did not change its instance name, it always responds to the listener and function that you created for it on Frame 1.

    image

If everything is working, congratulations! You are well on your way to being comfortable with ActionScript 3.0. If you had problems with your code, compare it carefully with the example code. If there are errors in the code, the Output panel should appear with descriptions of the errors, and it will show on which lines they appear. Note which line numbers contain the errors, and check your spelling and the color-coding of your ActionScript on those lines. Especially make note of capitalization, and be sure that the instance names of your buttons match the names in your event listeners.

Modifying the text field dynamically

Right now, when your movie loops over the opening animation, the text field is instructed to display the number representing the number of times the animation has played. The number is currently accurate, but the user feedback is not elegant. Let’s make the information in the text field more useful by adding some prose to the field to make a complete sentence.

  1. With the Actions panel and the Timeline visible, select the loop frame (Frame 2) in the actions layer of the Timeline.
  2. In the Actions panel, change the code that currently reads:

    info_txt.text = String(count);

    so that it reads:

    info_txt.text = "The animation has played " + String(count) + "x.";

    The plus signs are used to concatenate (or join) the literal text (in quotation marks) with the value of the count variable to form a sentence.

  3. Save your work and test the movie once more. The text field should now read “The animation has played 1x (2x, 3x, and so on).”

    image

Adding buttons to control language

To solidify what you’ve covered so far, add a few more buttons to the Stage to let the user control the language that is displayed in the text field. You will begin by adding a variable that keeps track of the user’s language choice and sets a default language to the first frame of the movie.

  1. With the Actions panel and the Timeline visible, select Frame 1 of the actions layer.
  2. Add the following code below the existing code:

    var language:String = "English";

    Now you’ll add code that checks the value of the language variable before adding text to the text field.

  3. With the Actions panel and the Timeline visible, select Frame 2 of the actions layer.
  4. In the Actions panel on Frame 2, select the line of code that reads:

    info_txt.text = "The animation has played " + String(count) + "x.";

    and cut it (Control+X for Windows or Command+X for Mac) to the clipboard.

  5. Place the cursor in the Actions panel below the final line of existing code.
  6. Create a new function to check which language has been set by adding the following code in the Actions panel:

    function setLanguage():void {
     if(language == "English") {
     }
    }

  7. In the line above the first right curly brace (}), paste the code that you cut, so that the function now reads:

    image

    Note

    The conditional statement in the setLanguage() function checks to see if the language has been set to English. Note that it performs this comparison by using two equals signs (==).

    In ActionScript 3.0, you check to see if one value matches another value with two equals signs. In this case, you are checking to see if language is equal to “English.”

    It is especially important to remember to use two equals signs when comparing values, because a single equals sign (=) is what is used to set one value to equal another. In other words, a single equals sign in this example would be used to set language to English, not to check to see if language is English.

    When the function is called, it will now check to see if the language variable is set to “English” (which is the default because of the code you added in step 2). If the language is English, then the text field will display your message.

    Soon you will add buttons that will let the user choose German or Spanish as well as English, so let’s put those two additional possibilities into the conditional statement.

  8. Add to the setLanguage() function so that it reads:

    image

    Unlike the functions that we created earlier, the setLanguage() function is not an event-handler function, meaning it is not intended to respond to a specific type of event. This is because this function needs to run at the very start of the application as well as any time the user changes the language selection.

    Note

    In a Flash project that has large amounts of content for different languages, the translations will more likely be stored in an external location, such as an XML file, and loaded into Flash at runtime. You will learn about working with external XML files in later lessons.

    To call this type of freestanding function, you just refer to it by name and add a pair of parentheses after the name. If there were any parameters to pass to the function, they would go between the parentheses. This particular function does not have any parameters.

  9. In the Actions panel, select the line after the setLanguage() function.
  10. Call the setLanguage() function, so it sets the text correctly at the beginning of the animation loop, by typing the following code:

    setLanguage();

    Finally, you will add buttons that let the user change the language.

  11. Select Frame 1 of the buttons layer in the Timeline.
  12. In the Library panel (Window > Library), you will see three buttons named English Button, German Button, and Spanish Button. Drag one instance of each button to the upper-left corner of the Stage. These are just stock buttons with some text added to them.
  13. In the Properties panel, name the instances of the new buttons english_btn, german_btn, and spanish_btn, respectively.
  14. Continuing in Frame 2 of the actions layer, add a listener to each button by typing the following code below the last line that you added:

    english_btn.addEventListener(MouseEvent.CLICK, setEnglish);
    german_btn.addEventListener(MouseEvent.CLICK, setGerman);
    spanish_btn.addEventListener(MouseEvent.CLICK, setSpanish);

    When one of these three buttons is clicked, it needs to do two things:

    • Set the language variable to the language that was chosen.

    • Call the setLanguage() function, which will change the contents of the text field.

    Remember, the conditional statement in the setLanguage() function uses the value of the language variable to determine what gets written in the text field.

  15. On the lines below the listeners you just created, add the following code:

    image

    image

  16. Save your work and test your movie.

    The text field will always display English first. While the opening animation is playing, you should be able to use the new buttons to switch the contents of the text field between English, German, and Spanish. If you click the Restart button, the currently selected language should be retained until it is changed (by clicking a different button).

    image

Some suggestions to try on your own

If you made it all the way through this lesson, congratulations! You can now consider yourself a serious student of ActionScript, and you may be amazed at what you can accomplish using just the techniques we have covered in these first two lessons.

To practice and become more comfortable with the techniques covered in this lesson, you can try to add a few more features to the lesson02_start.fla file. Here are some examples:

• Add additional languages. This will involve adding new buttons, as well as new listeners and functions, to the existing ActionScript. Use any languages that you happen to know, use a translation site such as www.freetranslation.com, or just make up your own translation.

• Translate the text in the home frame. Right now you have translated only the content of the text field during the opening animation, but you could write a similar function for the text in the home frame to translate that text based on the language the user chooses.

• Using ActionScript similar to what you added on the Flash Support button, add buttons with links to other URLs.

• Using ActionScript similar to what you added on the Home button, add buttons that go to and stop at specific frames or go to and play specific frames of the animation.

Review questions

1 Describe how the addEventListener() method is used in ActionScript 3.0.

2 What is one way to describe a mouse click in the addEventListener() method?

3 Which character is used in ActionScript 3.0 to join or concatenate strings of text and variable names?

4 What is the syntax for checking to see if one value is equal to another? What is the syntax for setting a variable to a given value?

Review answers

1 The addEventListener() method is used to listen for a specific event on a specific object and to respond to that event by calling an event-handling function.

2 In an addEventListener() method, a mouse click could be described as MouseEvent.CLICK, as in:

Button1.addEventListener(MouseEvent.CLICK, doSomething);

3 The plus sign (+) is used to concatenate text with evaluated code. This is commonly used to set the text property of a dynamic text field. Here is an example:

someTextField.text = "Hello" + userName;

4 Two equals signs are used to compare values to see if they are the same, as in:

if(password == 3456789) {
 enterSafely();
}

A single equals sign is used to set the value of a variable, as in:

var firstUSPresident:String = "Washington";

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.141.6