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
In his session at @ThingsExpo, Dr. Robert Cohen, an economist and senior fellow at the Economic Strategy Institute, presented the findings of a series of six detailed case studies of how large corporations are implementing IoT. The session explored how IoT has improved their economic performance, had major impacts on business models and resulted in impressive ROIs. The companies covered span manufacturing and services firms. He also explored servicification, how manufacturing firms shift from se...
WebRTC is the future of browser-to-browser communications, and continues to make inroads into the traditional, difficult, plug-in web communications world. The 6th WebRTC Summit continues our tradition of delivering the latest and greatest presentations within the world of WebRTC. Topics include voice calling, video chat, P2P file sharing, and use cases that have already leveraged the power and convenience of WebRTC.
SYS-CON Events announced today that CA Technologies has been named “Platinum Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business – from apparel to energy – is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
An increasing number of companies are creating products that combine data with analytical capabilities. Running interactive queries on Big Data requires complex architectures to store and query data effectively, typically involving data streams, an choosing efficient file format/database and multiple independent systems that are tied together through custom-engineered pipelines. In his session at @BigDataExpo at @ThingsExpo, Tomer Levi, a senior software engineer at Intel’s Advanced Analytics ...
SYS-CON Events announced today that Secure Channels, a cybersecurity firm, 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. Secure Channels, Inc. offers several products and solutions to its many clients, helping them protect critical data from being compromised and access to computer networks from the unauthorized. The company develops comprehensive data encryption security strategie...
Internet-of-Things discussions can end up either going down the consumer gadget rabbit hole or focused on the sort of data logging that industrial manufacturers have been doing forever. However, in fact, companies today are already using IoT data both to optimize their operational technology and to improve the experience of customer interactions in novel ways. In his session at @ThingsExpo, Gordon Haff, Red Hat Technology Evangelist, shared examples from a wide range of industries – including en...
Detecting internal user threats in the Big Data eco-system is challenging and cumbersome. Many organizations monitor internal usage of the Big Data eco-system using a set of alerts. This is not a scalable process given the increase in the number of alerts with the accelerating growth in data volume and user base. Organizations are increasingly leveraging machine learning to monitor only those data elements that are sensitive and critical, autonomously establish monitoring policies, and to detect...
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, will provide a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to ...
SYS-CON Events announced today that Massive Networks 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. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
WebRTC is great technology to build your own communication tools. It will be even more exciting experience it with advanced devices, such as a 360 Camera, 360 microphone, and a depth sensor camera. In his session at @ThingsExpo, Masashi Ganeko, a manager at INFOCOM Corporation, will introduce two experimental projects from his team and what they learned from them. "Shotoku Tamago" uses the robot audition software HARK to track speakers in 360 video of a remote party. "Virtual Teleport" uses a...