Welcome!

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
Mac OSX
  • 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.

mx.transitions.easing.Regular

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.

Summary
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.

Conclusion
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
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, will discuss how they bu...
SYS-CON Events announced today that Dasher Technologies will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Dasher Technologies, Inc. ® is a premier IT solution provider that delivers expert technical resources along with trusted account executives to architect and deliver complete IT solutions and services to help our clients execute their goals, plans and objectives. Since 1999, we'v...
SYS-CON Events announced today that TidalScale, a leading provider of systems and services, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. TidalScale has been involved in shaping the computing landscape. They've designed, developed and deployed some of the most important and successful systems and services in the history of the computing industry - internet, Ethernet, operating s...
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. As a result, many firms employ new business models that place enormous impor...
Coca-Cola’s Google powered digital signage system lays the groundwork for a more valuable connection between Coke and its customers. Digital signs pair software with high-resolution displays so that a message can be changed instantly based on what the operator wants to communicate or sell. In their Day 3 Keynote at 21st Cloud Expo, Greg Chambers, Global Group Director, Digital Innovation, Coca-Cola, and Vidya Nagarajan, a Senior Product Manager at Google, will discuss how from store operations...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, will discuss some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he’ll go over some of the best practices for structured team migrat...
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
As hybrid cloud becomes the de-facto standard mode of operation for most enterprises, new challenges arise on how to efficiently and economically share data across environments. In his session at 21st Cloud Expo, Dr. Allon Cohen, VP of Product at Elastifile, will explore new techniques and best practices that help enterprise IT benefit from the advantages of hybrid cloud environments by enabling data availability for both legacy enterprise and cloud-native mission critical applications. By rev...
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that Datera will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera offers a radically new approach to data management, where innovative software makes data infrastructure invisible, elastic and able to perform at the highest level. It eliminates hardware lock-in and gives IT organizations the choice to source x86 server nodes, with business model option...
Infoblox delivers Actionable Network Intelligence to enterprise, government, and service provider customers around the world. They are the industry leader in DNS, DHCP, and IP address management, the category known as DDI. We empower thousands of organizations to control and secure their networks from the core-enabling them to increase efficiency and visibility, improve customer service, and meet compliance requirements.
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
SYS-CON Events announced today that IBM has been named “Diamond Sponsor” of SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California.