Grant Skinner

The "g" in gskinner. Also the "skinner".

@gskinner

A Complete Guide to Using Namespaces In AS3

I need to define a custom namespace in AS3 a couple times a year at most, and nearly every time, I forget how to do it. The docs tell you to use the “namespace” keyword (which I remember), but not where or how to use it (which is what I forget), and google isn’t much help. I always wind up opening mx_internal.as in the Flex SDK as a reference.

With that in mind, here’s a complete guide to using namespaces in AS3. Note that it is about access namespaces, not XML namespaces. Hopefully it saves other devs a few minutes of searching.


What are custom namespaces?

Namespaces allow you to control the access to the members (properties and methods) of a class. You are probably familiar with native access modifiers like public, protected, internal, and private. Custom namespaces allow you to define your own access rules.


What can I use namespaces for?

While there are a range of uses for custom namespaces, three stand out to me as most common:

1. Documenting special conditions for member access. For example, in an evolving API, you may be required to expose methods that aren’t stable. You could place them in a custom namespace (ex. “transitional”), and document it to warn developers that these methods are subject to change. It’s sort of like a EULA for APIs.

2. Providing custom access domains. Namespaces cannot enforce custom access rules (only extend the native access modifiers), but they can provide a way to segregate an API for different user types. For example, you could provide a public API for a library for most users, and an extended API for plugin developers that uses a custom namespace (ex. “plugin”).

As another example of both #1 & 2, Adobe uses the mx_internal namespace to expose methods that need to be accessed widely within the Flex framework, but aren’t meant to be utilized publicly. They document that this namespace is unsupported and subject to change. It has the side benefit of providing hooks for advanced developers that require deep access to the framework and are willing to risk future compatibility problems.

3. Preventing name collisions. You can define members that have the same names in different namespaces. This is particularly handy for dynamic objects. ActionScript 3 uses this for the Proxy object, isolating it’s built in methods in the flash_proxy namespace, so that they are accessible externally, but don’t collide with any user defined methods.


Defining namespaces.

Defining namespaces is easy, just use the “namespace” keyword.

public namespace my_namespace_name;
public namespace my_other_namespace = "uri";

You can create your namespace within any existing namespace, including the built in namespaces (public, private, et al), but you will usually just make it public.

The name can be whatever you want (except reserved words). The naming convention for namespaces is all-lowercase, with words separated by underscores.

The uri is optional, but helps prevent naming conflicts in the case that someone else uses the same namespace name. This should point to a relevant uri, which ideally hosts some brief information on the namespace (though this is unnecessary). For example, Adobe points to http://www.adobe.com/2006/flex/mx/internal for mx_internal, but doesn’t actually host any content there.


Where do you define namespaces?

You can define namespaces in two places – within a class, or in a separate file. I haven’t been able to come up with a real use case for the former, so we’ll focus on the latter. Simply create a new file with the same name as your namespace inside the appropriate package path, and define the namespace in a package declaration:

// in com/gskinner/utils/my_namespace.as
package com.gskinner.utils {
public namespace my_namespace = "http://gskinner.com/as/namespaces/utils/my_namespace";
}


Using namespaces.

First, you need to import your namespace.

import com.gskinner.utils.my_namespace;

You can now use your namespace in the same way as the built-in namespaces. So instead of specifying a var or function as public or protected, you use your namespace.

my_namespace var myProperty:Number=-1;

To access class members within a namespace, you import the namespace, and then you use the whacky double-colon namespace syntax to access properties inside it.

import com.gskinner.utils.my_namespace;
trace(myDemo.my_namespace::myProperty); // traces -1.

You can also “use” a namespace, which opens it within the current scope (class or method), and provides access without the namespace qualifier. This approach requires less typing when accessing a number of members in a namespace, but it makes the code more ambiguous (are you accessing a public method, or one in the open namespace?).

import com.gskinner.utils.my_namespace;
use namespace my_namespace;
trace(myDemo.myProperty); // traces -1.

Got anything to add? Let me know in the comments.

Comment Blocks That Are Easy to Toggle On/Off

Sometimes when you’re coding, you find yourself toggling a block of code on or off by commenting it. Most development environments make this pretty easy with a button or shortcut that will comment or uncomment a selected block.

However, it can be handy to know that there’s a way to achieve the same thing by setting up your block comments in such a way that they can be enabled or disabled by adding or removing a single “/”.

Here’s how it looks with the code commented out:

/*
thisIsCodeIWant.toToggle(onOff);
andMoreCodeHere();
//*/

You can uncomment the code block by adding a “/” at the start of the block comment like so:

//*
thisIsCodeIWant.toToggle(onOff);
andMoreCodeHere();
//*/

After I posted this, hbb reminded me of a related commenting trick. With the following set-up you can toggle between two code blocks by adding a “/”.

//*
thisIsCodeBlock(1);
moreCode();
/*/
thisIsCodeBlock(2);
andMore();
//*/

Just remove the “/” at the beginning of the first block comment to swap code blocks.

/*
thisIsCodeBlock(1);
moreCode();
/*/
thisIsCodeBlock(2);
andMore();
//*/

This is a pretty basic tip, but I’ve found that not all developers are aware of it, so I thought it couldn’t hurt to share it.

ASDocr: Simple ASDoc UI, AS3 Documentation Tool

I’m a big fan of ASDoc! I use it to document all of my major library releases (ex. GTween, SPL, Wander, etc).

ASDoc allows you to write simple comments in your AS3 classes, then generate HTML documentation from them. This is great in that it allows developers to maintain source code and documentation simultaneously, and it reduces the overall burden in writing documentation by reading the core API information from the code directly. Unfortunately, the ASDoc tool is command line based, and can be a bit of a pain to work with. There are ant integration tools available, but they don’t suit every need or scenario.

That’s where ASDocr comes in. Building on the new nativeProcess APIs in AIR 2.0, it provides a simple graphical interface to ASDoc. It walks you through all of the common params ASDoc supports, with help for each of them. You can save configurations for multiple projects, and clone configurations to act as a starting point for new projects.

It only takes a couple of minutes to set up a basic configuration (only 2 settings required) and start generating documentation. ASDocr will display the output from the ASDoc executable, and notify you if an error occurs. You can even use CMD/CTRL-ENTER as a shortcut to run (muscle memory FTW!).

Here are a couple of screen shots showing it in action:

Continue reading →

GTween v2.01 Released

GTween V2.01 is a minor update that adds support for AS3 events, allows multiple callbacks at the same position on a timeline, introduces a version property, and fixes a number of bugs reported by users. It also includes a SWC file with the distribution.

Here’s the full list of changes:

  • added GTween.version property. (thanks to Colin Moock for the request)

  • added .dispatchEvents and GTween.defaultDispatchEvents properties, so you can enable AS3 events. (thanks to Colin Moock for the request)

  • fixed a problem with tweens in a timeline initing at the wrong time, and added support for position values less than -delay. (thanks to Erik Blankinship for the bug report)

  • fixed a problem with tween values being set to NaN before the controlling timeline started playing. (thanks to Erik for the bug report)

  • added support for multiple callbacks at a single position to GTweenTimeline. (thanks to sharvey, edzis for the feature request)

  • fixed issue with callbacks being called again when a timeline completes. (thanks to edzis for the bug report)

Go to gskinner.com/libraries/gtween to get all the information and download the new release.

I’m planning to migrate the source code to a public repository early in the new year.

Indispensable Plugin for FlashBuilder: Flex Formatter

Flex Formatter is an extremely useful plugin for FlexBuilder / FlashBuilder that formats your ActionScript code (AS3) and MXML according to a broad range of settings, and helps you to generate ASDoc comments automatically. It is free, and open source.

It’s code formatting is quite robust and configurable, handling things like brace settings (cuddling versus next line), white space around parameters and operators, sorting imports, and a ton more. Thankfully, you can export your settings to a file and share it with your whole team. You can also have it automatically update settings from a file that you can share over the network or via SVN / GIT.

Unfortunately, it’s ASDoc features are much more rudimentary, and do not have any configuration options. They serve as an acceptable starting point, and save some time, but I would love to see some additional support here (for example, an option to mark private and or protected members as @private, which is a very common requirement).

Regrettably, Flex Formatter does not seem to come with installation instructions. If you are not familiar with installing Eclipse plugins, it can take a lot of work to figure it out, but it’s very simple if you know how to do it:

  1. Start up FlexBuilder / FlashBuilder.

  2. From the Help menu, select ‘Software Updates > Find and Install…’

  3. Select ‘Search for new features to install’ and click ‘Next >’

  4. Click ‘New Remote Site…’

  5. Use name: ‘Flex Formatter’ and url: ‘http://flexformatter.googlecode.com/svn/trunk/FlexFormatter/FlexPrettyPrintCommandUpdateSite/’

  6. Click OK

  7. Make sure only ‘Flex Formatter’ is selected in the ‘Sites to search’ list, and click ‘Finish’

  8. Follow the prompts to install Flex Formatter, and restart the IDE

Once you’ve restarted, you should see the Flex Formatter bar with buttons to ASDoc, format, and rearrange your code. You should also have a ‘Flex Formatting’ entry in preferences.

If you’d like, you can import my settings for Flex Formatter. You can download them by clicking here, unzip them, and import them using the ‘import…’ button at the bottom of Flex Formatter’s preferences.

Flex Formatter’s project home is here and you can find documentation on it’s settings here.

Wander Motion Class Update

I just uploaded an update to the Wander motion class I released a couple weeks ago.

This version has some new features that I’ve added as I needed them, like:

  • targetObject: set the Wander to use the x/y of another display object as it’s target x/y. There are lots of possibilities with this: you can follow another wandering sprite, follow a sprite moving in a completely different way (ex. a bouncing ball), or even follow a sprite that was tweened in the timeline or via a tweening library.
  • rotationLimit: sets a limit on the maximum amount that the rotation can change in a single update of the wander. You can use this to get nice smooth arcs and more gradual responses (particularly when using targetObject).
  • update(): you can set autoUpdate (which replaces paused) to false, and call update directly if you have a central tick dispatcher.
  • getShortRotation(): exposed this helper method for general use.
  • always operates on the target’s current rotation. Now you can change the rotation between updates, and Wander will use the new rotation properly.
  • oldRotation: stores previous rotation value.
  • fixed a couple of minor issues.
  • included FLAs for the demos.

Continue reading →

AS3 ProximityManager V2

Mike Chambers recently hosted a contest to write a faster version of my AS3 ProximityManager class (which was a lazy port of my AS2 version). Many of the results were blazing fast, but not really suited to or optimized for real-world use (including my entry, that took 2nd place).

I thought it would be good to release a more optimized version of my library that was designed for real use. This version is significantly slower in Mike’s benchmarks (about 2-3X slower), but that’s because it is tuned for real use cases, concerns itself more with memory use, and includes features like list management, non-zero origins, and variable radii.

It provides a good lesson – optimization is great, but it’s necessity in context always has to be weighed against API, feature, and readability concerns.

Here’s quick demo of it in action, showing 5000 items being updated and compared to the 4 bases every frame:

Continue reading →

Flash Player 10.1 Prerelease on Labs

Adobe just released a beta / prerelease of Flash Player 10.1 on labs. Major improvements include global error handling, out of memory handling, better browser integration, support for browser privacy modes, globalization support, media streaming enhancements, additional content protection options, and a focus on mobile including multitouch.

You can download the FP 10.1 beta player here.

Get all the juicy details in the release notes.