Monthly Archives: September 2007

Create a pseudo-class from a runtime-loaded image in AS3

Recently, I’ve been hacking at low-level AS3 features to try to find a way to load an external image and make a class out of it. Basically, I want to create multiple instances of that image using only the new operator. The image path isn’t known until runtime, so I’d like to make a special Loader subclass that knows the correct image path to load before it gets instantiated. As you can imagine, that’s not the easiest requirement to meet.

Screenshot of application built with the method described below Example Application (View Source Enabled)

A short time ago, Ben Stucki created a class to load external images as icons for Flex components. It’s a very clever solution. He uses a Dictionary to associate the image path with the intended parent. I wish I could have used it, but the class I’m trying to create needs to be instantiated somewhere that I can’t access the parent. Like I said, the class itself really needs to know the correct image URL to load. In AS2, it wouldn’t be too difficult to accomplish. You can hack __proto__ in AS2 to do some interesting runtime subclassing to make a unique class for every URL. Unfortunately, Adobe locked things down a bit in AS3 (for performance reasons, mostly), and __proto__ is no longer accessible to developers.

That said, let’s try to remember back even further, to our AS1 days, when true classes didn’t exist. Classes were function objects, and we added member variables and methods through prototype. Thankfully, class-like functions through prototype are still possible in AS3. Consider the following code:

var MyImageClass:Function = function():Loader
{
	//we need a Loader that automatically loads our image
	var loader:Loader = new Loader();

	//the URL will come from the prototype
	loader.load(new URLRequest(this.url));

	//our "constructor" returns the Loader!
	return loader;
};

//the image to load in our dynamically created "class"
MyImageClass.prototype.url = "yahoo_logo.gif";

This creates a constructor-like function that returns an instance of Loader. This loader automatically loads an image URL that we place in the function’s prototype. If you’re using Flex, you could easily modify this function to make it return a SWFLoader instead.

Usage is surprisingly simple. We pretend MyImageClass is a real class, and our friend the new operator takes care of everything.

//add two images to the display list
var image1:Loader = new MyImageClass();
this.addChild(image1);

var image2:Loader = new MyImageClass();
this.addChild(image2);

Two images will automatically load. That’s perfect!

…well, sadly, it’s not perfect. There’s some bad news. I had hoped this would be able to replace Ben’s code in Flex too, but I quickly discovered that while this special pseudo-class (as I now call it) behaves like a real class, Flash Player knows that it isn’t a real Class. For example, the icon style on the Button component in Flex expects a Class object. Our pseudo-class is actually a Function object, and these two types are not compatible. Flash Player will throw a runtime error if I try to set this style to a Function.

Thankfully, I need these pseudo-classes for a component that I built myself. I can ensure that I type my variables correctly (or at least branch depending on the type) so that both Class and Function can be used. As much as I’d like to be able to use these pseudo-classes for icon and skin styles in Flex, that’s just not in the cards.

If you’re interested, I built a utility class called LoaderUtil with a function createAutoLoader() that encapsulates this functionality into a simple function where you pass an image URL, and an optional LoaderContext (for tweaking cross-domain options and other stuff on the Loader), and you receive one of these pseudo-classes back.

"ActionScript 3.0 Design Patterns" a good place to start for Flash developers

If you’re looking to improve your coding practices, and earn that “Engineer” part of your title, design patterns are a good thing to know. I recently picked up a copy of ActionScript 3.0 Design Patterns by William Sanders and Chandima Cumaranatunge. With Flash 9 bringing more developer-friendly improvements to ActionScript, and Flex making waves in the technology world, now’s a great time to become a better developer. I know a few design patterns well, but I know that I have many more to learn. If you’re unfamiliar, design patterns offer recognized and accepted solutions to the common project requirements. This book, we’ll call it AS3DP for short, gives a good foundation for a growing developer.

AS3DP is divided into several sections based on a basic categorization of design patterns. These categories have been defined previously in other important texts about design patterns, and I’m glad that the authors chose to stick with the precedent. They appear as follows.

  1. Creational patterns

  2. Structural patterns

  3. Behavioral patterns

  4. Multiple patterns (more than one pattern combined into one)

The section on Creational patterns starts with the Factory Method pattern. This pattern is explained very well with two interesting examples. The first example, a Print Shop, helped me understand the problem and solution very easily, and the second example, a shooter game, was a fun way to reinforce the knowledge. Next, the Singleton pattern is introduced. This pattern is an obvious choice, as one of the more common ones I’ve seen mentioned by ActionScript developers, and the section includes good material.

We go next into Structural patterns. I found the Decorator pattern, again, very easy to understand. The examples in this section illustrated the purpose well, but they didn’t quite catch my interest as the ones in previous chapters. Paper dolls probably won’t appeal to the average target reader of AS3DP. Decorating with “Deadly Sins and Heavenly Virtues” seemed weird too. I would have preferred the focus to have been closer to real-world projects as much as possible. The Adapter pattern is another well-explained pattern. The example of easily controlling a car in different ways (such as through code or the mouse) brought my interest back a bit. This section ends with the Composite pattern which is explained through the Flash display list (an excellent choice to help the reader’s understanding) and inverse kinematics, another interesting topic.

The third category of patterns features Behavioral patterns. We start with the Command pattern. One example implements undo, and another sets up controls for a podcast media player. Much to my annoyance, the authors decided to include the Observer pattern. Considering that they don’t have an exhaustive list of the classic patterns in this book as it is, I don’t understand why they decided this one is important to include. One of the native classes in Flash Player, EventDispatcher, already uses this pattern. To be blunt, very few developers will ever implement the Observer pattern in AS3. The Template Method pattern was easy to understand, and the examples summed it up well. Overall, he State pattern was introduced very well and I found it understandable. The video player example could have used a little more work, I think. I understand that simplicity is important for examples, but something felt strange about a video player that couldn’t go directly from a paused state to a stopped state. Behavioral patterns end with a look at the Strategy pattern.

The final category of design patterns introduced in AS3DP is the set of patterns that combine multiple patterns into one. The first is Model-View-Controller, or MVC for short. Along with Singleton, this is one of the most common patterns that seems to appear in ActionScript code. The examples for this one were generally interesting, and it was a good review for me. The finally pattern is Symmetric Proxy. It seemed to be explained pretty well, and the authors warned the reader that it has some minor changes from the traditional implementation which was thought-provoking, and I think it will act as a subtle suggestion to help readers explore design patterns a bit more. The requirement of Flash Media Server and its AS1-style code to create the example was a bit of a turn-off for me, though.

I found ActionScript 3.0 Design Patterns to be a book that I could read from start to finish. Often I will skip sections in books that cover material I already know, but design patterns are generally pretty flexible, and it was nice to see the authors’ perspectives on them. I also had motivation to continue on because there were several patterns I haven’t yet used in my projects, and I love to learn new things. Some examples were very good and kept me interested; others felt completely out of place. In general, all of them helped me to understand how the patterns should be implemented.

If you want to learn design patterns, I think AS3DP is a good place to start if you’re most familiar with ActionScript over other languages. You may want to pick up a more general book about developing with design patterns later, though. The authors didn’t include all of the classic design patterns introduced in the original source, Design Patterns: Elements of Reusable Object-Oriented Software, and it’s probably a good idea to go beyond what’s presented in AS3DP. I’ve also heard good things about the book Head First Design Patterns, but I haven’t read it myself.

Open Source Flex Components: AdvancedList and CheckBoxList

The ZoomFrame component for Flex that I released last month got some good buzz. Today, I’m ready to release two more Flex components. Both are simple, but useful. The AdvancedList component adds a bit of functionality to the basic List. The CheckBoxList component adds a special item renderer with a CheckBox, and its selection changes hook into the standard List selection system. Have a look at the demo of AdvancedList and the demo for CheckBoxList to get an idea of how each works.

Screenshot of AdvancedList Component Example

The AdvancedList adds two nice things. First, you have the ability to disable specific items in the List through the data provider. They won’t be selectable through user interaction. This is achieved through the enabledField and enabledFunction properties. They work very much like the standard labelField and labelFunction properties. Additionally, AdvancedList gives you more control over drag-and-drop operations. By default, items that are dragged from a List get the drag format type “items” and any List will accept these items if dropEnabled is set to true. However, what if you have several List on screen, all are able to accept dropped items, but you want to restrict drag-and-drop between certain specific Lists? With the ability to change the dragFormat from “items” to something more specific like “shoppingCartItems”, you have more options and control.

Screenshot of CheckBoxList Component Example

CheckBoxList, as I mentioned, creates a List where selected items are shown with CheckBoxes. Multiple selection is enabled by default, and pressing the Ctrl key is not required. This component has a couple advantages. First, a collection of related CheckBoxes is now enclosed in a scrolling List. This saves on space, and we all know many apps need all the extra space they can get. Plus, the frame helps to visually associate the CheckBoxes as a set. Secondly, this component can replace a regular multi-select list. If you’ve ever seen a web form where one of these lists is used, you’ll know that they must always have instructions to tell you to press the Ctrl or Command key to select multiple items. That’s barely usable. In fact, I’d be afraid to watch my grandma if she had to enter data into that form. Instead, the CheckBoxList offers a familiar concept, standard CheckBoxes, and it puts them within another familiar concept, a scrolling List. No instructions needed.

Of course, just like the ZoomFrame component, the source code for the AdvancedList and CheckBoxList components are available under the terms of an MIT-style license. Please feel free to use them in both commercial and open source projects. There are a few other components I intend to release after some polishing, so be sure to check back soon.

Speaking at Adobe MAX 2007

It seems that I convinced the powers-that-be to let me go to Adobe MAX again, and this year I’ll be speaking and representing Yahoo! We’ve got an Inspire session all lined up to talk about integration. Integration of what? Flash, JavaScript, Yahoo! web services, AIR, and more.

For my part of the session, I’ll be talking about the integration of Flash visualizations with the ever-popular YUI library. I’ll be pushing the power and advantages of Flash visualizations into the hands of frontend developers who normally work with other technologies. I can’t wait to share more details about this one. We’re cooking up some cool stuff.

Session Outline

About a year ago Yahoo! has launched the very successful Yahoo Developer Network around tools, services, examples, and developer support. Yahoo! has also been working internally on Flash and Flex for a long time and released Web-Service APIs and most recently component libraries around Flash with a similar approach as YUI has done for JavaScript. In this session we are going to show examples on how we use those technologies as well as how you can create your own applications and use Yahoo! services and components. Examples shown range from AIR and Search, Flash and Ajax, over to Yahoo! Badging, WebAPIs and developer tools.

When is it?

Tuesday, October 2nd, 2007. 9:15 am – 10:15 am.

More Information

Yahoo! Presents Examples of Integration

If you’ll be at MAX, be sure to say hi if you see me. If you attend our session, I’d love to chat if you afterwards if you want to share some of cool ways you’re planning to use our components and libraries, or if you have suggestions for how we can improve our open source Flash efforts at Yahoo! Got an interesting component for Flash or Flex that you need? We might think it’s useful and cool too. Let us know at MAX!