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.

@ThingsExpo Stories
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
DXWorldEXPO | CloudEXPO 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.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
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 ...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...