ActionScript Techniques

I don't know how many times I have seen the phrase "ActionScript is based on the ECMAScript-262 Specification" in Flash books. I don't understand why it is overlooked or not explored further. Flash ActionScript is not some home-grown proprietary language that has no standard of coding. It is an extension of the founding principles and ISO-standard processes of ECMAScript, the ECMAScript-262 Specification, Third Edition?December 1999, to be specific. Server-side ActionScript is extended from the efforts of Netscape Communication's server-side JavaScript 1.5 implementation, which in turn is fully compliant with ECMA-262, Third Edition.

How many of you have actually downloaded the papers associated with ECMA? If you are serious about developing Communication applications, then you must get into the minds of the Macromedia engineers that built it. To fully understand the power of the ActionScript language, download and print these documents, and then put them in a binder marked Flash ActionScript Reference:

  • ECMAScript Language Specification: ftp://ftp.ecma.ch/ecma-st/Ecma-262.pdf

  • Server-Side JavaScript Core Guide: http://developer.netscape.com/docs/manuals/js/core/jsguide14/CoreGuideJS14.pdf

  • Server-Side JavaScript Core Guide: http://developer.netscape.com/docs/manuals/js/core/jsguide15/contents.html

If you belong to an organization that follows an ISO (http://www.iso.ch/) standard practice, then Flash and the Flash Communication Server is an option for you. When someone asks, "To what coding standard do you develop?" you can reply with a big smile and confidence, "ECMAScript, Third Edition?December 1999."

Now to understand how you implement the language specifically in Flash MX, let's look at some style and formatting considerations.

ActionScript Style and Formatting

Flash has evolved a great deal since ActionScript was first introduced in version 4.0. Flash 5 adopted the ECMA standard but selectively chose what it would and would not support, such as Scope chain. Flash MX has now fully adopted the entire standard. Flash is a completely different application of the ECMA language than its original "web page" use. The primary difference is that Flash is a state-full environment, whereas the web page is stateless. This means that variables and objects are discarded whenever the user leaves the web page.

The other clear difference is the authoring environment. Flash was a visual tool that was originally designed for the deployment of vector-based animation. The introduction of ActionScript launched it into an entirely new sector. ActionScript has gone through two major redefinitions since its inception, and it retains backwards compatibility in this third generation. Through its growth, ActionScripting practices have also endured many different variations. It is not a strict language, and allows for the developer to shortcut techniques practiced in other languages.

ActionScript can be placed everywhere, including any frame on any layer or on any MovieClip or button. Although you can place ActionScript almost anywhere, that doesn't mean you should. There is no formal style guide (yet) for Flash applications, so the following suggestions should be considered a single point of view.

Placing Code

ActionScript should only be placed on frames within a single layer in the _root Timeline. It was not possible to do this with Flash 5, but now that you can reference any Flash object (including buttons) from the Timeline, you should kick the old habit of putting ActionScript inside MovieClips or on buttons. If you've done this in the past, you know what a nightmare the technique can be when debugging. Avoid the temptation, and take a bit of extra time now to understand how to access objects from the Timeline. It will save you mountains of time later.

Commenting

Commenting is one of the most important styles to follow. Comment everything. If you think you are over commenting, then you aren't commenting enough. Each command you run, each function, object, or array you build, each time you connect with the server or handle messages returned from the server, add a comment. Here is how you comment in ActionScript:

// this is a single-line ActionScript comment 

/*
      this is a multiline
      ActionScript comment
*/

In the book's exercises, you probably noticed a significant number of comments. Write your code as if you are writing a book. This will make you a popular member of the development team, allowing anyone, including new employees, to easily interpret what you built. When you open an application after developing it six months ago, you will understand what is going on in the code. The extra time spent describing what you are doing is a healthy long-term investment to your sanity.

Avoiding Spaghetti Code

Spaghetti code may not be a formal term, but it describes code that is strung together with patches and fixes that start to resemble cancerous tumors?and we all know the fatal results of a tumor. Code is not resistant. This form of coding can be avoided with a solid planning stage, and if a new feature is required, don't just code a solution. Planning upgrades and understanding what elements will be affected will help you avoid bugs, and let you keep the meatballs on your plate, not in your code.

Variable Naming

There are two benefits to naming your variables properly. First, you can use code hinting in the ActionScript Editor and within Macromedia Dreamweaver MX to help you develop. Second, it is a form of self-documentation (once again, more commenting). A variable named n tells you nothing, but a variable named username_str tells you what the value of the variable will represent and the variable's datatype. Instead of building an onSync handler like this:

c.onsync = function(i) { 
            for (n in i) { trace("sync message: " + i[n].code); }

write the same function using proper variable suffixes and descriptive variable names:

remoteData_so = function(infoObj_array) { 
            for (pos in infoObj_array){
                  trace("sync message: " + infoObj_array[pos].code);
            }
}

Imagine a new member of your development team trying to decipher the first version of the function. It would be a headache, to say the least. If you used the second example, however, the developer probably would be thanking you before you even had a chance to explain what the function does. It's all about communication?see the tie-in?

Using Functions

Use functions to encapsulate code and to practice code reuse. The exercises in this book often encapsulate a series of commands within functions. This technique makes explaining what is going on at particular sections of the code easier. Employing this method of encapsulation will increase your reuse of code, plus ensure that only the script you want to run will run. Functions are essential for Flash Communication applications, because many times you have to wait for a response from the client or server before performing operations. For example, you can't connect to a NetStream before the connection has been accepted and confirmed. To achieve this, the Flash player should wait for the server to respond with a NetConnection.connect.success code before connecting to the NetStream. Failure to wait is the cause of many problems when building Flash Communication applications.

Coding Strategies

Any Flash application you build, with or without the Communication Server, should have a coding strategy. It is particularly important when you build communication applications because of the many elements involved. Three basic strategies you must develop are:

  • Data storage

  • Client/server roles

  • Using the Flash Timeline

There are many more strategies you should consider, but these three are a good place to start.

Data Storage

The worst thing you can possibly do is randomly create a variable, function, or object without a strategy. Variables can contain any ActionScript type. Functions are saved into variables. Objects are instantiated into variables. Arrays, strings, XML, everything you do is stored within a variable. Developing a strategy for variable names and how data will be stored within them is extremely important. This is compounded when you introduce the remote SharedObject into the mix. As you have read, remote SharedObjects announce changes to data slots to every SharedObject connection. If every bit of data is stored in an object within a single slot, the Flash client will have to download and parse the entire slot to handle the changes locally. Some good guidelines are:

  • Create a map of what will be stored and where it will be stored.

  • Make strategic decisions for creating new variables and accessing data.

  • Don't underestimate the power of the local SharedObject, especially for handling disconnected clients (such as the PocketPC).

  • When working with Flash Remoting MX, don't return the entire database recordset. Doing so is inefficient, is unnecessary, and will consume resources of the device. Only return to Flash and the Communication Server what it needed.

You also need to build a strategy for using variables in the _global, local, and MovieClip scopes. Flash Player 6 has fixed a serious interpreter variation from the scope chain defined in the ECMA standard; so in Flash MX, using the variable scope is more efficient and useful. Objects within the _global scope are accessible from any Timeline within the application. The _global scope is useful for maintaining persistent data, such as user information or local SharedObject information. You can also access it from dynamically loaded SWF movies. Local objects are only local to the Timeline they are created on. While they can be accessed anywhere, they are deleted if a movie is unloaded. Object structures are good ways to consolidate variables or arrays. For example, an object that describes a user might look like this:

/* Define the userInfo_object with some initial data */ 
_global.userInfo_obj = ({name: "Kevin Towes", company = "Pangaea NewMedia"});

/* Add / Update a property of the UserInfo_obj object */
_global.userInfo_obj.phone = "416-922-1600";

/* Read the data from any timeline */
trace("Company" + userInfo_obj.company);

This approach would be much more organized and efficient than storing each variable within the _global root. To clear the user or logout, simply clear the entire object.

Client/Server Roles

Understanding the relationship between the client and the server is extremely important. Developing Flash Communication Server applications is not like developing standard Flash applications. A clear understanding of Flash player logic, business logic, data storage and handling, security, and general application control must be assessed before starting the application. The tutorial chapters in the next part of this book will step you through some advanced exercises that will strategically place logic on the server and on different client interfaces.

There can never be a general rule when it comes to determining where processes will occur; the answer depends on the application you build. Games will differ greatly from a slideshow presentation or a chat room. The server may be responsible for handling login and password authentication or returning data from a database. The client can also do the same thing. Understanding the capabilities of each system and the roles each will play is your first step. Visualizing the scope of it on paper is the next step.

When going through the process, calculate roles for the server and, if required, different interfaces. Determine how each device will handle a disconnection or changing data. For example, you use Flash Communication Server to return a recordset and save it in a SharedObject. Flash client A has the ability to change or add data. When the data is changed and returned to the SharedObject, the server responds by returning the updated recordset to the application server for database inclusion. At the same time, Flash client B can only read the data and responds differently. Now, throw in the possibility of a connection failure anywhere along the path from database server to application server to communication server to client A and client B. Do you see where a seemingly simple operation just got very complex? Drawing it out will help, as will planning a strategy on each system for operating on and handling the exchange of information.

Timeline

Your comfort with the Flash Timeline probably depends on your background. Designers and animators tend to enjoy the Timeline and use it to all of its abilities (sometimes too much), but programmers are just the opposite. Programmers tend to build 100% of the Flash application on a single Frame. I even have seen an extreme case where a programmer wanted nothing to do with the Flash stage and used the attachMovie method to place, code, and interact with MovieClips and buttons. Some designers and animators, of course, can be just as determined to avoid opening the ActionScript Editor.

The Timeline can be a difficult concept, but when you have embraced it and come to a compromise of keyframe design and coding, your world inside Flash will become much more productive and enjoyable.

A technique that goes over well with programmers is to consider the keyframes on the Timeline as completely different applications. Another way to think of them is as different interfaces within the same application. Chapters 9 and 10 illustrate good examples of using the Timeline to develop unique interfaces. This Timeline technique lets the developer build initial functionality and handle interface changes more efficiently. You should also consider the use of #include, pulling ActionScript out of Flash all together and using a JavaScript editor or Dreamweaver MX to produce the ActionScript.



    Part I: 10 Quick Steps for Getting Started
     
    ASPTreeView.com
     
    Evaluation has РСУ»ЕХФexpired.
    Info...