ActionScript: Creating Reusable Code

written by: Gabriel Savimbi; article published: year 2007, month 06;



In: Categories » Computers and technology » Flash » ActionScript: Creating Reusable Code

You want to perform a series of actions at various times without duplicating code unnecessarily throughout your movie.

Create a function and then call (i.e., invoke) it by name whenever you need to execute those actions.

There is more than one way to create (i.e., define or declare) a function. Here is how to create a named function:

function functionName (  ) {
   // Statements go here.
   }
   To call (i.e., execute) the named function, refer to it by name, such as:
functionName(  );

Here is how to create a function literal:

functionName = function (  ) {
   // Statements go here.
   };

Although not strictly required, it is considered a best practice to include a semicolon following the closing curly brace when defining a function literal.

Grouping statements into a function allows you to define the function once but execute it as many times as you'd like. This is useful when you need to perform similar actions at various times without duplicating the same code in multiple places. Keeping your code centralized in functions makes it easier to understand (because you can write the function once and then ignore the details when using it) and easier to maintain (because you can make changes in one place rather than in multiple places).

There are two common ways of defining ActionScript functions: as named functions or function literals (a.k.a. anonymous functions). Each of these ways of declaring a function has its own use.

The named function declaration is the most common choice (when not defining a function to be used as a method) and has at least one advantage over function literals: named functions are accessible within the entire keyframe (or on( ) or onClipEvent( ) handler) even if they come after the call to the function.

For example, even though the writeMessage( ) function is not declared until after it is invoked, the function is still available:

// Invoke the writeMessage(  ) function, which is declared later in the script.
   writeMessage(  );
// Declare (define) the writeMessage(  ) function as a named function.
   function writeMessage (  ) {
   trace("Hello, friend.");
   }
// The function is available before or after it has been declared.
   writeMessage(  );

In contrast, a function literal is accessible only from lines of code that come after the declaration:

// The ActionScript interpreter will not be able to find a function with this name, 
   // and so nothing happens (it fails silently).
   writeMessage2(  );
// Declare (define) the writeMessage2(  ) function as an anonymous function literal
   writeMessage2 = function (  ) {
   trace("Hello, friend.");
   };
// However, the function is available from lines of code after it has been declared.
   writeMessage2(  );

However, there are several reasons to use function literals:

You can assign a function literal to a global variable so that the function can be accessed from any timeline.

Function literals offer a convenient, compact, and intuitive way to define methods for objects.

Function literals can be treated like other variables, in that they can be passed to other functions or have their values reassigned.

Here, we assign a function literal as a property of the _global object:

_global.launchBookExamples = function (  ) {
   getURL("http://www.person13.com/ascb", "_blank");
   };\

Therefore, from anywhere on any timeline, you can execute the function by simply using its name. For example, you might attach this script to a button:

myButton.onRelease = function (  ) {
   launchBookExamples(  );
   };

Here, we define the function as a method of a movie clip (where onEnterFrame( ) is a special, built-in method for movie clips that you need to define before it can be used):

myClip_mc.onEnterFrame = function (  ) {
   trace("Hooray for methods!");
   };

Of course, you can define custom methods as well by simply assigning the function literal to a new property of the object:

myClip_mc.myCustomMethod = function (  ) {
   trace("Hooray for methods!");
   };

It is also worth noting that you can set one method equal to another method. This technique is often used to assign the same actions to a movie clip or button for two different events. You can define an anonymous function and assign it to one of the event handler methods, and then simply assign one event handler method to the other. A common example of this is when you want to define the same actions for when a user releases a button or movie clip and when they release outside:

// Define an onRelease(  ) method for a movie clip.
   myMovieClip.onRelease = function (  ) {
   trace("Hooray for methods!");
   };
// Assign the same method definition to the onReleaseOutside(  ) method as well.
   myMovieClip.onReleaseOutside = myMovieClip.onRelease;

Functions can also be passed as data. You can conveniently pass a function literal to another function that requires a function as one of its arguments, such as setInterval( ) or the Array.sort( ) method:

// Set an interval that calls a function that increments a variable, i, and displays
   // the value.
   setInterval(function (  ) {trace(++i);}, 1000);

Functions are subject to the same scope limitations as variables. Timeline functions are accessible only while the timeline on which they are defined exists. A timeline function can be a named function or an anonymous function assigned to a timeline variable. Additionally, timeline functions can be called only by using the proper target path. When you access the function from the same timeline, you do not need to include the target path, but when you want to access the function from another timeline, you need to make sure you provide the correct path.

// Explicitly invoke a function that is defined on the main timeline.
   _root.myFunction(  );

If your function is used within the same timeline only, you don't need to worry about scope issues. However, if you intend to use the function throughout many timelines, two solutions are generally employed:

Define the function as a global function. If you make a function a global function, you can call it by name from any timeline in the movie without having to worry about scope:

_global.myFunction = function (  ) {
   trace("Global functions are fun!");
 };

Define the function as a (static) method of a global class. All of the built-in classes are global by default, and if you define a class with a global constructor, then even your custom classes can be global. This technique is really a variation on the first, but with the advantage that classes offer you a way of organizing your functions in a potentially meaningful way (for example, the built-in Math class organizes many mathematical functions).

legal disclaimer

1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service

Useful tools and features

Translate this article to...    Send this article to you or to a friend

Link to this article from your page   
If you like this article (tutorial), please link to it from your web page using the information above. Linking to this page, this is the only way to help us improve our service, the same time providing your visitors with a way to improve their online experience.

related articles

1. Scripting Masks in Flash
Use the Drawing API to create a shape and then use MovicClip.setMask( ) to apply the mask. Masks can be used to create unique shapes or visual effects. For example, you can use masks to create wipes and transitions or interesting animations in which only the masked portion of the artwork is visible at a given time. You can even create masks that change shape over time, and use them to mask bitmapped graphics (in movie clips). You can use any movie clip as a mask of another movie clip using the setMask( ) method. The setMask( ...

2. Drawing a Triangle using ActionScript
Create a custom MovieClip.drawTriangle( ) method using the Drawing API and invoke it on a movie clip. You can determine and plot the vertices of a triangle given the lengths of two sides and the angle between them. This is a better approach than specifying the lengths of the three sides because knowing the lengths of two sides and the angle between them always determines a triangle, whereas three arbitrary sides may not fit together to make a triangle. The custom drawTriangle( ) method accepts six parameters: ab ...

3. ActionScript: Filling a Shape with a Solid or Translucent Color
Use the beginFill( ) and endFill( ) methods to initiate and close a shape drawn at runtime. To draw a filled shape, call beginFill( ) prior to any other drawing methods, including the custom methods you have defined such as drawCircle( ) and drawPolygon( ). Invoke endFill( ) after calling other drawing methods to create the shape. You cannot apply a fill to an existing shape drawn at authoring time or runtime. You must invoke beginFill( ) before drawing the shape to be filled. This example creates a solid blue ...

4. Drawing a rectangle using ActionScript
Create a custom MovieClip.drawSimpleRectangle( ) method using the Drawing API and invoke it on a movie clip. To draw a simple rectangle, specify the stroke's attributes using the lineStyle( ) method and then draw four lines using the lineTo( ) method: // Create rectangle_mc with a depth of 1 on the main timeline. _root.createEmptyMovieClip("rectangle_mc", 1); // Specify a one-pixel, solid, black line. rectangle_mc.lineStyle(1, 0x000000, 100); // Draw four lines to form the perimeter ...

5. How to draw a rectangle with rounded corners
You want to draw a rectangle with rounded corners, an offset, or rotation.Create a custom MovieClip.drawRectangle( ) method using the Drawing API and invoke it on a movie clip. The drawSimpleRectangle( ) method is, as the name suggests, quite simple. Let's create a more complex version that also: Draws a rectangle with a specified angle of rotation Let's you specify the rectangle center's coordinates Can draw a rectangle with rounded corners The drawRectangle( ) method accepts...

6. Reusing and Organizing Code in Flash Movies
You want to reuse code that you've created for one project in another Flash movie. Or you want to write your ActionScript code in an external text editor. Place your ActionScript code in external .as files and use the #include directive to add them to your Flash movies: // Adds all the code within MyActionScriptFile.as to your Flash movie. #include "MyActionScriptFile.as" Use the #include directive to incorporate code from external text files into your Flash movie during compilation from a .fla file ...

7. Drawing a Circle using ActionScript
Create a custom MovieClip.drawCircle( ) method using the Drawing API and invoke it on a movie clip. You can create a circle in ActionScript with eight curves. Fewer curves results in a distorted circle and too many curves hinders performance. Let's create a custom method of the MovieClip class for drawing circles. This method, drawCircle( ), allows for three parameters: radius The radius of the circle x The x coordinate of the circle's center point. If undefined, the circle is centered at x =...

8. ActionScript: Repeating a Task at Timed Intervals
You want to perform an action or actions at a specific timed interval. Use the setInterval( ) function. The setInterval( ) function allows you to specify an interval (in milliseconds) at which your Flash movie will invoke a function. Use setInterval( ) to perform a particular action over time but not necessarily at the frequency of the frame rate of the movie. // Define a function. function myIntervalFunction ( ) { // Output the difference between the current timer value and its value from the ...