Adobe Flex Authors: Matthew Lobas, PR.com Newswire, Shelly Palmer, Kevin Benedict

Related Topics: Adobe Flex

Adobe Flex: Article

Understanding Classpaths

Step beyond the built-in toolset

All objects in recent versions of ActionScript are defined by something called classes. Think of classes as blueprints that determine the unique combination of characteristics, actions, and reactions that comprises a particular object of a certain type. By "object," we are talking about the familiar things a Flash developer deals with every day: movie clips (the MovieClip class), text fields (the TextField class), buttons, sounds, math functions, components, you name it. They are all defined by classes.

As of Flash MX 2004 (aka Flash 7), classes are stored in external text files, usually with the .as file extension, and imported into a SWF at compile time, which is the point at which Flash gathers together all your ActionScript, symbols, and other relevant content, and "compiles" them into the special code structure (bytecode) of the SWF file played by the Flash Player.

Out of the box, Flash provides hundreds of built-in ActionScript classes. The great part is, you can even write your own! But there's a catch: the Flash compiler, which converts ActionScript into bytecode, must be told where new classes are located, or it won't be able to find them. That's what this article is about.

A Brief History
Flash 5 was the first to support the #include directive, which made it possible to compile external ActionScript into a SWF. This was a very cool feature, because it encouraged developers to share solutions to common problems in the form of code snippets and function libraries located in external text files. The fact that these snippets could be conceptually distilled from a given FLA made them particularly convenient, especially in light of other ActionScript advances at the time, such as the ability to write custom functions.

Note: It should be mentioned that #include has caused a bit of confusion over the years. This directive is effectively a placeholder: its purpose is to insert external ActionScript into your FLA as if the code were already in the FLA. This is not the same thing as loading ActionScript dynamically - a feature many have asked for, but one that is not yet available in Flash as of this writing.

By the time Flash MX (aka Flash 6) arrived, ActionScript featured a then-new Object.prototype property, and hotshots began to employ object-oriented principles in Flash for the first time. A full discussion of prototype-based object-oriented programming (OOP) is beyond the scope of this article, but for the sake of this brief history, suffice it to say that Object.prototype allowed developers to extend native objects such that, for example, all normal arrays might support a new shuffle() method. This was also true for custom-made objects. Ah, those were the heady days!

Even so, prototype-based OOP was "merely" the sort used in JavaScript: certainly practical, but often sneered at by "real programmers," who tended to prefer the greater breadth of class-based OOP. It wasn't until Flash MX 2004 that ActionScript supported bona fide classes. Thanks to new strict datatyping and something called classpaths, which will be covered in the next section, Flash developers could finally write classes in the same format as those shipped with the product - classes they could create, use, and share in ways more advantageous than ever before.

Classpaths Point the Way
To build the objects required of it, the Flash compiler looks up whatever classes it needs to - for directions, basically. One of the places it checks by default is a special folder it knows as $(LocalData)/Classes, much like you might head to the pantry for staples like rice or sugar. The actual location of this folder is typically one of the following, depending on what operating system and version of Flash you have:

Windows XP

  • C:\Documents and Settings\<user name>\Local Settings\Application Data\Macromedia\Flash MX 2004\<language code>\Configuration\Classes
  • C:\Documents and Settings\<user name>\Local Settings\Application Data\Macromedia\Flash 8\<language code>\Configuration\Classes
  • Hard Disk: Users: <user name>: Library: Application Support: Macromedia: Flash MX 2004: Configuration: Classes
  • Hard Disk: Users: <user name>: Library: Application Support: Macromedia: Flash 8: Configuration: Classes
In addition, the compiler looks for classes in whatever folder contains the current FLA. These two conceptual locations are stored as user preferences in the global classpaths setting.

To see these classpaths for yourself, proceed as follows. In Flash MX 2004, select Edit > Preferences, choose the ActionScript tab, and click the ActionScript 2.0 Settings button. In Flash 8, select Edit > Preferences, choose ActionScript from the listbox at left, and click the ActionScript 2.0 Settings button.

Note the existing entries of both the dot (.), which represents "current folder," and the aforementioned $(LocalData)/Classes. If either of these is accidentally deleted, simply add it back. (see Figure 1)

To add a path, click the Add New Path button and either type a folder by hand or click the Browse To Path button to browse. Now, why would you want to add a path? In a word: convenience. With #include, you have to remember the actual file location of your .as file ... if you keep all your function libraries in one place, chances are good that folder isn't the same one that contains your current FLA. With classpaths, however, you can maintain all your class files in a single folder and add its location once to this dialog. From then on, Flash simply "knows" where those classes are.

Global versus Document
If you like, you may specify classpaths on a per-FLA basis. To configure the settings of a given FLA only, select File > Publish Settings, choose the Flash tab, and click the Settings button in the ActionScript version row. You'll see the same dialog, but this time its affect does not apply to all FLAs - only the one you have open. In addition to adding paths, you may specify a frame in which to export these classes in the compiled SWF.

Components offer a similar export option. To see what I mean, drag any item from your Components panel to the Stage. Doing so will place a copy of that component into your Library panel. Right-click or Control-click it in the Library to see its Linkage... properties. You'll see a checkbox for "Export in first frame." This option, and the one similar to it in the document classpaths setting, determines which frame of the SWF should contain the associated class(es); that is, which frame should contain all that ActionScript code. Component classes are actually quite large (anywhere from 26KB to 68KB!). That much weight can actually interfere with preloader code.

Your own custom classes are not likely to be that huge. Unless they are, I would leave the export frame as 1; classes are just text files, after all.

Avoid Collisions by Using Packages
Let us get practical, to illustrate what we have discussed. Say you are interested in scripted animation. You have read Joey Lott's "Programmatic Tweening in Flash" (www.communitymx.com/abstract.cfm?cid=9B986) and are now able to move objects around the Stage with instances of the Tween class. Perhaps you are even applying naturalistic movement, thanks to the native easing classes Back, Bounce, Elastic, Regular, and Strong (of course, there's also the None class, but that's specifically for not easing). Now, wouldn't it be nice if there were additional flavors of easing in the world? You bet it would! As it happens, there are.

Author Robert Penner is famous for his easing equations, available free from his website. To use his, simply download the .as files (they're archived in a .zip file) and put them into a folder whose location is specified in your classpaths setting. Wherever you would have referenced a native easing class in your ActionScript, reference one of Penner's instead.

But wait, we already have a problem! Although his collection includes plenty of new classes - Cubic, Expo, Quad, Quart, and more - three of them have the same name as existing native classes (Back, Bounce, and Elastic). If this situation weren't managed, you'd have a class collision on your hands! If you wanted to use Penner's Easing instead of the native one, how would the compiler know which class you meant? Flash would be confused and would either output an error message or compile with unpredictable results.

Thankfully, a handy solution exists. Borrowing from Java and other OOP languages, Flash supports something called packages. Packages sidestep the abovementioned ambiguity by logically categorizing classes in a hierarchical manner. They are manifested on the hard drive by way of nested folders and are used to organize classes with a common purpose. Flash's native easing classes, for example, are located in the package mx.transitions.easing, because they're related conceptually to Flash's transition classes. If you look into the real location of $(LocalData)/Classes on your computer, you'll find an mx subfolder, and inside that (among many others), a transitions subfolder, and finally an easing folder, so you can see how this ties together. As long as packages are unique, classes will not be confused.

By convention, developers usually arrange packages based on the reverse of their Internet domain names, which are guaranteed to be unique. This means that classes written by Robert Penner, available from robertpenner.com, are organized in the package com.robertpenner (his easing classes, specifically, in com.roberpenner.easing). Classes written by CommunityMX partners are organized in the package com.communitymx . Those written by Flash guru Grant Skinner are organized in the package com.gskinner . You get the idea.

As long as your global classpaths setting includes the root folder that contains these package subfolders, you'll be fine. For example, I personally keep a folder named AS2 Classes inside my My Documents folder. The path to AS2 Classes on my computer is C:\Documents and Settings\David Stiller\My Documents\AS2 Classes - and this path is listed in my global classpaths setting. Because of that, I'm already done. I do not need to further specify \com\robertpenner\easing\, even though that's where the Cubic.as file actually resides. On a Mac, this location might be Hard Disk: Users: : AS2 Classes, and that path would likewise be enough for the global classpaths setting.

To recap, then, once your classpaths are set, all you have to remember is a class's name and optionally its package, if it has one.

Save Keystrokes by Using Import
Let's go back to the native easing classes for a moment. To invoke the Regular class, you could specify its fully qualified package and class name.


But after repeated references, all that typing does a number on your fingers. Are there any shortcuts? You bet. Enter, the import statement.

The import statement allows you to access classes without having to spell out their packages. You could shorten repeated references to the above, for example, by putting the following at the top of your script, just once:

import mx.transitions.easing.Regular;

After that line, you would only have to type Regular when referring to that class. In fact, you may even use the asterisk (*) character as a wildcard. Because you know there are several easing classes in the mx.transitions.easing package, you could import them all at once by typing this:

import mx.transitions.easing.*;

Note: The import statement must be repeated for each new frame of code you write. If you import classpaths in frame 1, all scripts in frame 1 will be able to take advantage of them, but scripts in frame 2 will not. Multiple use of the same import statement in any single frame will generate an error, so when you use it, use it at the top of each relevant frame.

The basic classes in Flash reside in a special $(LocalData)/Classes folder. Flash already knows this classpath location, so common tasks, such as instantiating a Sound object, are straightforward:

var myMusic:Sound = new Sound();

Even the more advanced classes, such as transitions, easing, and Flash 8's new BitmapData class, are located in packages within the $(LocalData)/Classes folder. Because of this, the classpath is already taken care of, but any reference to these classes requires the package's full path:

var myImage:flash.display.BitmapData = new flash.display.BitmapData(parameters here);

... Or, to save keystrokes, the import statement:

import flash.display.BitmapData;var myImageA:BitmapData = new BitmapData(parameters here);
var myImageB:BitmapData = new BitmapData(parameters here);// etc.

Custom classes, such as those you might acquire online or write yourself, may be located in the same folder as the current FLA, thanks to the dot (.) entry in the global classpaths setting. Even if your custom classes use packages (which is to say, the class files are located in subfolders), you're in good shape, provided those subfolders reside in the same folder that contains the FLA.

It is recommended, however, that you keep third-party classes in a centralized location, such as a folder under My Documents. If you go this route, make sure to add the full path of this location to your global classpaths setting. Once that's out of the way, you may refer to these classes in any new FLA by name alone - or by package and name, unless you use the import shortcut.

In this article, you learned about classpaths and their usage in Flash MX 2004 and 8. You learned where to configure global and document classpath settings, how packages organize classes, and even how to save keystrokes by using the import statement. Armed with this information, you're ready to begin using third-party classes. Have fun stepping beyond the built-in toolset!

Article courtesy of Community MX. For more quality articles such as this one, go to www.communitymx.com

More Stories By David Stiller

David Stiller is a career multimedia programmer/designer whose portfolio includes NASA, Adobe, and major US automotive and boat manufacturers. He likes anaglyph 3D photography, finely crafted wooden game boards, Library of Congress field recordings, and Turkish coffee. David is self-taught and gets a kick out of sharing "aha!" moments with others through consultation, mentoring, and regular contributions to a variety of Flash forums.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

IoT & Smart Cities Stories
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...