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

Beginning ActionScript 2.0 2006

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

Chapter 26

6.Publish your SWF file and navigate to the folder where your SWF file was published. This is probably the workspace folder where your FLA is residing if you haven’t made any Publish Settings changes to the FLA.

7.In the same folder as the SWF file, create a new folder and name it fscommand.

8.If you are on a PC, find the Calculator program. This program is usually within the System32 folder in your Windows folder. If you are on a Mac, find a suitable file to open. Copy the file and paste it into the fscommand folder. Do not delete this program from its original location; simply copy it.

9.Open the Publish Settings dialog. Be sure the Windows Projector option is checked and click the Publish button.

10.Test the application by navigating to your workspace folder and double-clicking the fscommandExec.exe file. Click the Open Calculator button.

11.The calculator application opens.

How It Works

Using a simple command, Flash was able to launch another program.

The example utilized an innocuous program for the purposes of demonstration. However, the target application could be a second Projector file, an installer executable, or something interesting such as a custom Visual Basic executable capable of launching more sophisticated programs.

Many Flash developers become frustrated with this process because limiting what Flash can launch to the fscommand folder and limiting the file type to .exe is so restrictive that they’re convinced there must be a way around a particular launch problem. But there isn’t. The limitations of the Flash projector are there for security purposes so that the Flash IDE alone cannot be used to create malicious system programs.

SDK

If Flash’s available methods for system interaction are too limiting for the scope of your project, you’ll need to take a different approach with a third-party executable creation tool, or write your own. If writing your own sounds appealing, Macromedia offers an SDK for developing a wrapper that utilizes the Flash ActiveX player.

The SDK is often a desirable method when creating Flash for specific environments for kiosks or other controlled and isolated environments. Because the SDK relies on the ActiveX player, though, a target system must have the plug-in installed on the Internet Explorer browser. Little recourse is provided within the SDK; plug-in detection and failure can be difficult to resolve.

Third Parties

The ActiveX issue is also present in third-party wrappers, which use the SDK to create their products. This has recently changed on a few third-party wrappers.

658

Communicating between the Flash Plug-in and the Operating System

However, one wrapper in particular is officially Flash-enabled. Northcode 3.0 has obtained a license to offer a wrapper creation tool that is allowed to bundle the Flash player with the .exe itself, meaning that the systems that run the executable do not need any Flash player installed, and no Flash player install process is required. This makes Northcode a top contender when choosing a third-party wrapper.

Newer wrappers no longer require fscommand, either. Instead, wrappers such as Northcode allow developers to write ActionScript with extended objects and classes that work much like the native ActionScript objects.

Each third-party wrapper has its own syntax, documentation, and level of clarity of code. Most offer to add the objects to the Flash ActionScript editor definitions file, as well as add help files directly within the Flash IDE.

Most third-party wrappers such as Jester, Northcode, Flash Studio, and others offer trial downloads. I recommend downloading them, and trying them out before choosing one to deploy on a project. Be aware that the trials are limited. Usually a time limit is placed on the EXE file, or the EXE file the demo produces runs on your system only. Be sure to purchase a license before distributing software.

Be polite. Your executable is a guest on a user’s system. Be respectful of RAM usage, disk space, screen space, window options, and stability. As with any SWF file, always test your product on as many systems as possible to ensure quality.

Don’t make system changes just because you can. For example, storing persistent data in registry files or saving data to text files that only your application can access is silly when Flash offers SharedObjects.

Summar y

In this chapter, you explored wrappers and their use in Flash, took a look at various third-party offerings, and learned how to use Flash and other executables.

Exercises

1.Determine the operating system and display a different welcome message to the user.

2.Using fscommand, create two projector files. Use one projector to open the other.

3.Create a simple screen saver in Windows.

659

27

Creating Custom Classes

By this point, you have become reasonably familiar with how to code using ActionScript. Hopefully, you have applied your new skills to a personal project or two and are thinking ahead to bigger and better things. In this chapter, you learn some of the next steps to ActionScript coding, specifically the process of creating custom classes. Custom classes are immensely useful for any developer because they take you to the next level of organization and reusability.

Working with Classes

In Chapter 5 you were introduced to a number of object-oriented programming principles. You saw these principles as they apply to the classes built into the Flash player. Although you can achieve many things with just that knowledge, you can do so much more by creating your own custom classes.

Recall the definition of object-oriented programming from Chapter 5:

To package data and the code that acts on that data into a single entity.

The mechanism to make this possible is the class. By working with your own classes, you allow yourself to organize and package your own code in a way that makes re-use significantly easier, and that makes your code so much cleaner. Chapter 5 already went through much of the motivation for object-oriented programming with classes, so this chapter gets right into the mechanics of it.

Defining the Class

The first requirement for a class is that it must exist in its own file, which is named the same as the class itself. If you create a class called MyClass, you would define it in a file called MyClass.as and save it in the same folder as the FLA file that uses it. This enforcement ensures that class files are self-contained and separate from everything else.

Chapter 27

In the MyClass.as file, the core class definition might look something like this:

class MyClass

{

public var myProperty:String;

public function MyClass()

{

// ...

}

public function myMethod():String

{

// ...

}

}

This definition consists of a class block that encompasses all of the class code. Within it are defined all of the properties (basically variables) and methods (functions) that the class will use.

The first function block in the definition is a special function called a constructor. Its role is to carry out any actions that are to be performed when a copy (instance) of the class is created. You see more about the constructor shortly.

To actually use the preceding class, simply call the following from the main timeline. This is the same mechanism for creating any other class instance, such as you would do for creating a new Date, LoadVars, or XML class instance:

var myClassInstance:MyClass = new MyClass();

The Flash compiler will automatically search in a number of places to find the definition for MyClass, including the folder containing the FLA file. If it finds a file called MyClass.as containing a class block called MyClass, it will then reference that definition file when the new keyword is used. It will also enforce type checking, using MyClass as the data type.

Data types within Flash are themselves classes, or at least have class-based versions of them. You can see this by going to <Flash Program Root>/First Run/Classes/FP8/ and examining the contents of the

.as files there.

Give creating a custom class a try.

Try It Out

Your First Class

In this exercise, you create a simple custom class with a property, a method, and a constructor.

1.Create a new ActionScript document by selecting File New and choosing ActionScript File from the New Document panel.

2.Select File Save As and choose an appropriate folder for the file. Give the file the name

HelloWorldClass.as and save it.

3.Enter the following code into the new ActionScript file:

662

Creating Custom Classes

class HelloWorldClass

{

public var messageText:String;

public function HelloWorldClass(inputMessage:String)

{

messageText = inputMessage;

}

public function getMessage():String

{

return messageText;

}

}

4.Save the file (File Save).

5.Create a new Macromedia Flash document by selecting File New and choosing Flash Document from the New Document panel.

6.Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and enter in the following ActionScript code:

var message_obj:HelloWorldClass = new HelloWorldClass(“The quick brown fox”); var message2_obj:HelloWorldClass = new HelloWorldClass(“”); message2_obj.messageText = “jumped over the lazy dog.”;

trace(“message_obj message text: “ + message_obj.getMessage()); trace(“message2_obj message text: “ + message2_obj.getMessage());

7.Select File Save As, name the file tryItOut_helloWorld.fla, and save it in the same directory as HelloWorldClass.as.

8.Choose Control Test Movie to try it out.

How It Works

This exercise defines a single class and then creates two instances of that class. The first instance is passed a string through the constructor, which then assigns that string to the messageText property. The second instance passes a blank string through to the constructor and then sets the property directly. In both cases, the getMessage() method returns the contents of the messageText property for the corresponding class instance.

The trace statements show that both class instances contain their own data stores. Each instance contains its own copy of the messageText property, so changing it in one place will not affect it in the other.

Public Versus Private

In the world of re-use, when a class is given to others to use, a specific set of properties and methods are given to the developers using the class to access. These public properties and methods are supposed to be stable, in that changes to the internal class workings should not substantially change which public properties and methods can be used and what types of data that they use. Any such changes would require

663

Chapter 27

developers using a new version of your class to have to rewrite some of their code to accommodate your changes. This is definitely not a welcome task, and will not make you very popular. Even if the class is only for your personal use, development goes more smoothly if there are stable, well-defined connections between your classes.

Although each class will allow some of its properties and methods to be publicly accessed, there will also be support code within the class that may be prone to significant change. This support code is considered to be private and should not be accessible outside of the class. By declaring support properties and methods as private, Flash prevents access to these from any outside code.

The means of controlling property and method access is through the public or private keyword placed in front of each property or method declaration. The checking is done at compile time, not at runtime; if any external code tries to access a private property or method from your class, the compile will halt with an error message indicating what the access violation was and where it occurred.

The next exercise shows the effect of the public and private keywords.

Try It Out

Making Code Private

In this exercise, you work with making properties and methods private and see how the compiler responds under different scenarios.

1.Open the completed tryItOut_helloWorld.fla file from the first Try It Out exercise or open up the source Flash project file from the book’s source files at <source file directory>/Chapter 27/ tryItOut_helloWorldClass/tryItOut_helloWorld.fla.

2.Open the completed HelloWorldClass.as file from the first Try It Out exercise, or open up the source Flash project file from the book’s source files at <source file directory>/Chapter 27/ tryItOut_helloWorldClass/HelloWorldClass.as.

3.Change the public keyword in front of the messageText property declaration to private:

private var messageText:String;

4.Return to the FLA file and select Control Test Movie.

5.Return to the .as file and change the private keyword in front of the messageText property declaration back to private. Change the public keyword in front of the getMessage() method to be private instead:

private function getMessage():String

6.Return to the FLA file and select Control Test Movie.

7.Return to the .as file and change the private keyword in front of the getMessage() method declaration back to public. Change the public keyword in front of the HelloWorldClass() constructor to be private instead:

private function HelloWorldClass(inputMessage:String)

8.Return to the .fla file and select Control Test Movie.

664

Creating Custom Classes

How It Works

When a method or a property is declared as being private, the compiler warns about any attempted access and aborts the compile. In step 3 of the exercise, the property is changed to be private. When attempting to test the movie, the compiler gives the following message:

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 3: The member is private and cannot be accessed.

message2_obj.messageText = “jumped over the lazy dog.”;

The error provides a description of the issue, shows the line of code, and indicates where in the class file the line is located. In this case, you were attempting to change the contents of the variable; however, just trying to read the variable would have caused the same error.

In step 5, the getMessage() method is changed to be private. When attempting to test the movie, the compiler gives the following message:

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 5: The member is private and cannot be accessed.

trace(“message_obj message text: “ + message_obj.getMessage());

**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 6: The member is private and cannot be accessed.

trace(“message2_obj message text: “ + message2_obj.getMessage());

The compiler indicates that the getMessage() method cannot be accessed and aborts the compile. If there are multiple violations of private properties or methods, the compiler will generate a complete list of all the access violations.

In step 7 you see why constructors always need to be public. With the access set to private, you cannot even create an instance of the class.

Take a closer look at the constructor.

Defining the Constructor

As mentioned at the start of this section, the role of the constructor is to perform any actions that are to be performed when an instance of the class is created. The constructor is also used for passing startup data into the class instance. This function is special because of the following:

It has the same name as the class itself.

It is not explicitly called.

It has no return type.

The compiler knows which method is the constructor by looking for a method declaration with the same name as the class itself. Unlike a method, a constructor cannot be explicitly called. If you try to explicitly call the constructor, nothing will happen. The constructor is to be called exactly once and no more, so it does not behave like a normal method. In the following example, you see that attempting to call a constructor as if it were a normal method has no effect. The output of getMessage() does not change to “foo”, and the test to see whether the method exists returns undefined:

665

Chapter 27

var message_obj:HelloWorldClass = new HelloWorldClass(“The quick brown fox”); message_obj.HelloWorldClass(“foo”);

trace(“message_obj message text: “ + message_obj.getMessage());

// Outputs: message_obj message text: The quick brown fox

trace(“constructor handle: “ + message_obj.HelloWorldClass); // Outputs: constructor handle: undefined

Because a constructor is not explicitly called, it can never return data and can have no return type. If you try declaring one, even if it is just a Void return type, the compiler will return an error.

Passing Startup Data

When a class is instantiated, there is often some initial data that the class needs before it can do any work. If the class is responsible for drawing something on the stage, it might need a handle to the movie clip that it should draw to. If the class is to manipulate data, it might need an initial copy of that data.

You specify what kind of initial data a class will accept by specifying arguments in the constructor:

public function HelloWorldClass(arg1:String, arg2:Number, arg3:Boolean ... )

Each constructor argument corresponds to one parameter that is to be passed into the new class:

var newInstance:HelloWorldClass = new HelloWorldClass(“foo”, 2, true, ... );

Within the constructor, you will generally want to save the passed-in data for later use. You do this by creating private properties and assigning them the data that was passed in. The following example allows for three parameters to be passed into the new class instance, and then assigns the values to private properties that can be used elsewhere within the class:

private var pMessageText:String; private var pNumLoops:Number; private var pUseSeparator:Boolean;

public function HelloWorldClass(messageText:String, numLoops:Number, ; useSeparator:Boolean)

{

pMessageText = messageText; pNumLoops = numLoops; pUseSeparator = useSeparator;

}

Try this out. In the course of the next few Try It Out examples, you put together a class that will create a photo thumbnail button suitable for use in a Flash-based photo album.

Try It Out

Create a Photo Thumbnail Class

In this example, you start creating the framework for a class that creates a clickable button out of a dynamically loaded thumbnail image.

666

Creating Custom Classes

1.Create a new ActionScript document by selecting File New and choosing ActionScript File from the New Document panel.

2.Select File Save As and choose an appropriate folder for the file. Give the file the name

ThumbnailButton.as and save it.

3.Enter the following code into the new ActionScript file:

class ThumbnailButton

{

private var pParentTimeline:MovieClip; private var pThumbnailName:String; private var pThumbnailHolder:MovieClip; private var pImageHolder:MovieClip; private var pBorderHolder:MovieClip; private var pClickHandler:Function;

private var pMovieClipLoader:MovieClipLoader;

public function ThumbnailButton(parentTimeline:MovieClip, ; thumbnailName:String)

{

pParentTimeline = parentTimeline; pThumbnailName = thumbnailName;

pThumbnailHolder = pParentTimeline.createEmptyMovieClip(pThumbnailName,; pParentTimeline.getNextHighestDepth());

pImageHolder = pThumbnailHolder.createEmptyMovieClip(“imageHolder”, ; pThumbnailHolder.getNextHighestDepth());

pBorderHolder = pThumbnailHolder.createEmptyMovieClip(“borderHolder”, ; pThumbnailHolder.getNextHighestDepth());

pMovieClipLoader = new MovieClipLoader(); pMovieClipLoader.addListener(this);

}

}

4.Save the file (File Save).

5.Create a new Macromedia Flash document by selecting File New and choosing Flash Document from the New Document panel.

6.Click the first frame in the timeline, open the Actions panel (Window Development Panels Actions), and enter in the following ActionScript code:

var myThumbnail:ThumbnailButton = new ThumbnailButton(this, “myThumbnail”);

7.Select File Save As, name the file tryItOut_thumbnailButton.fla, and save it in the same directory as HelloWorldClass.as.

8.Choose Control Debug Movie to try it out. Click the play button within the Debug panel, and note the movie clip structure shown in the top left of the Debug panel.

667