ActionScript errors don't display in Flash Player 9.0.115 when using ExternalInterface

by Josh Tynjala

UPDATE: It appears that if you set ExternalInterface.marshallExceptions to true, the errors will be re-enabled.

Here’s a third ExternalInterface bug I discovered while developing the YUI Charts. When you call an ActionScript function from JavaScript, and an error is thrown by Flash Player, the standard error popup in the debug version of Flash Player will not display. This bug only appears in Flash Player 9 Update 3 (version 9.0.115), and it does not affect earlier versions.

This problem affected me on multiple occasions while I was using the beta version of Update 3 from Labs (though I only discovered it after the release) and again just a couple of days ago. I have trouble reproducing or tracking down certain bugs that others report because errors during calls from JavaScript simply fail silently on my machine like if I had the release player.

Let’s look at a simple example application below. When the constructor runs, it exposes the displayError() function to JavaScript. This function does nothing more than throw an error. The constructor then calls a flashReady() function through ExternalInterface to notify the HTML page that the SWF is finished loading.

package
{
	import flash.display.Sprite;
	import flash.external.ExternalInterface;

	public class ExternalInterfaceActionScriptError extends Sprite
	{
		public function ExternalInterfaceActionScriptError()
		{
			ExternalInterface.addCallback("displayError", displayError);
			ExternalInterface.call("flashReady");
		}

		public function displayError():void
		{
			throw new Error("This error will not display in 9.0.115!");
		}
	}
}

The flashReady() function in JavaScript appears below. The ${application} is simply the replacement token used by Flex Builder HTML templates for the object/embed id in the page.

<script type="text/javascript">
	function flashReady()
	{
		${application}.displayError();
	}
</script>

If you have Flash Player 9.0.47 debug installed, an error will be displayed. If you have 9.0.115 installed, you will see nothing. Once again, I intend to submit the bug to Adobe so that it may be fixed in an upcoming release of Flash Player. If you’ve found any Flash Player bugs, and you can reproduce them, always be sure to let Adobe know. It may not help immediately, but you’ll be thankful when they’re fixed in the future.

Some legal variable names cannot be passed from ActionScript to JavaScript

by Josh Tynjala

Let me tell you about another Flash Player ExternalInterface bug I encountered recently while working on the YUI Charts. When passing an Object from ActionScript to JavaScript, make sure your variable names don’t require quotes. Let me explain with a quick example.

This is legal ActionScript, but the variable name requires quotes because it has a hyphen:

var test:Object = { "legal-name" : "hello!" }; //just fine!

This code will throw a compiler error:

var test:Object = { legal-name: "hello!" }; //error!

Now, let’s look at a quick little class I built.

package
{
	import flash.display.Sprite;
	import flash.external.ExternalInterface;

	public class ExternalInterfaceVariableNames extends Sprite
	{
		public function ExternalInterfaceVariableNames()
		{
			var test:Object = { "legal-name": "hello!" };
			ExternalInterface.call("fromFlash", test);
		}
	}
}

The HTML document in which we’ll embed this SWF will have the following simple JavaScript function:

<script type="text/javascript">
	function fromFlash(value)
	{
		console.log(value);
	}
</script>

Note: The function console.log() is used to display text in the Firebug console a lot like trace() is used in ActionScript to debug in Flash authoring or Flex Builder.

When I try to run my simple SWF, the following error is displayed in the Firebug console:

missing : after property id
[Break on this error] try { __flash__toXML(fromFlash(({legal-name:"hello!"}))) ; } catch (e) { "

What exactly is that showing us? Basically, for ExternalInterface to work, Flash Player places some code into the document. The important part of the code in the error is this:

{legal-name:"hello!"}

Look familiar? Just like ActionScript, JavaScript requires variable names with hyphens to be quoted. Bug confirmed. Of course, I'm submitting this bug to Adobe so that it can be fixed in a future version. Make sure you always report bugs you find in Flash Player, and try to include test cases whenever possible!

ExternalInterface bug can mangle data from JavaScript

by Josh Tynjala

While developing the YUI Charts, I discovered a nasty bug with ExternalInterface that affects many versions of Flash Player 9. Basically, it involves overwriting parts of the data passed from JavaScript somewhere in the encoding or decoding process. The best way to describe this error is to explain with an example.

Consider the following Flex application. Once it is initialized, the application calls a function named flashReady() in the hosting page’s JavaScript. The function returns a complex object to display in the Flex app’s Tree control.

Screenshot of working Flex application.
Click image to run the application.

Source code for the Flex app:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" applicationComplete="getDataFromJavaScript()">
	<mx:HBox>
		<mx:Tree id="tree" width="250" height="300"/>
		<mx:TextArea id="parsedData" fontFamily="Courier New" fontSize="12" width="250" height="300"/>
	</mx:HBox>
	<mx:Label id="status" text="Loading Data..."/>
	<mx:Script>
		<![CDATA[
			import com.adobe.serialization.json.JSON;

			private function getDataFromJavaScript():void
			{
				if(ExternalInterface.available)
				{
					var result:Object = ExternalInterface.call("flashReady", []);
					this.tree.dataProvider = result;

					//we're only encoding to JSON to view the result in the TextArea
					this.parsedData.text = JSON.encode(result);

					//version displayed for easy identification
					this.status.text = "Flash Player Version: " + Capabilities.version;
				}
				else
				{
					this.status.text = "ExternalInterface is not available!";
				}
			}

		]]>
	</mx:Script>
</mx:Application>

The following structure is passed from JavaScript to ActionScript.

var dataToPass =
{
	label: "Level 1-A",
	children:
	[
		{ label: "Level 2-A" },
		{
			label: "Level 2-B",
			children:
			[
				{ label: "Level 3-A" },
				{ label: "Level 3-B" }
			]
		},
		{
			label: "Level 2-C",
			children:
			[
				{
					label: "Level 3-C",
					children:
					[
						{ label: "Level 4-A" }
					]
				},
				{ label: "Level 3-D" }
			]
		}
	]
};

As you can see, the data passed through ExternalInterface has a complex hierarchy. Many of the objects have a label variable and many have children to specify branches in the Tree.

With Flash Player 9.0.28 (it affects other builds, but that one is commonly installed), the parsed data displayed in the TextArea control looks like the following code block. I’ve manually formatted it for readability.

{
	"0" : { "label" : "Level 4-A" },
	"children" :
	[
		{ "label" : "Level 4-A" }
	],
	"1" : {"label" : "Level 3-D"},
	"2" :
	{
		"0": { "label" : "Level 4-A" },
		"children" :
		[
			{ "label" : "Level 4-A" }
		],
		"1" : { "label" : "Level 3-D" },
		"label" : "Level 3-D"
	},
	"label" : "Level 3-D"
}

You’ll notice that the label property is overwritten on many of the more shallow levels. The strange numeric variables come from the indexes of the various children Arrays. Clearly, much of the data gets completely lost. You can see the very nearly empty Tree control in the following screenshot.

Screenshot of the Flex application when in a buggy Flash Player.

Thankfully, Flash Player 9 Update 3 (build 9.0.115) properly handles this type of ExternalInterface data. However, one can hardly expect everyone to install the very newest version that isn’t even a month old yet.

For the YUI Charts, I needed to find a way to get around this problem in older versions of Flash Player 9. Using the YUI JSON Utility, I encoded the data provider and various other complex properties to simple strings before passing them through ExternalInterface from JavaScript to ActionScript. On the ActionScript side, the JSON data can be decoded with AS3 corelib to turn it back into native objects.

For public releases of Flash Player (official releases and those appearing on Adobe Labs), this bug seems to affect builds below 9.0.60 (the beta version of Update 3, mentioned above). It shouldn’t affect too many applications out there as ExternalInterface isn’t widely used, in my experience. For those out there that do make heavy use of this API, it’s definitely a concern, and you will either need to resort to encoding the data somehow or requiring FP 9.0.115 as the minimum version if you discover that you’re affected.

By the way, if you ever need to test older versions of Flash Player, Adobe provides nice zipped downloads of each major version (with multiple builds of each) back to Flash Player 2.

Thoughts on Essential ActionScript 3.0

by Josh Tynjala

Widely considered the ultimate books on programming in Flash, Colin Moock’s Essential ActionScript series recently got updated for AS3. The first thing you’ll notice when you see it on the shelf, or pick it up off a fellow developer’s desk, is that Moock’s been doing a lot of writing. Essential ActionScript 3.0 appears to be about a third bigger than the last version. With the index, it surpasses 900 pages. The size difference between this book and its predecessor is strong evidence of how much ActionScript has grown and changed in recent years.

Let me start my review with a bit of a warning. It’s possible that this book may not contain the information you’d expect in its pages. It’s a book purely about ActionScript, the language. You won’t learn about Flash’s visual drawing tools, the library, components like a List or a RadioButton, and certainly not about anything specific to Flex. The author’s intent is to show you how to use the language itself, regardless of the IDE or type of project in which you use it. Moock shows the reader how to build classes, create functions, use inheritance, and work with many of Flash Player’s native APIs. The information is applicable to both the classic Flash authoring environment and in Flex Builder.

Although the back of the book states, “if you have no prior programming knowledge, this book gently guides you on your journey toward ActionScript proficiency”, I believe that it is more suited for intermediate to advanced developers. Folks coming from AS2 with a little knowledge of OOP should have no trouble, and developers coming from another language will easily transition into AS3. People less experienced in programming may get frustrated by a lack of step-by-step guidance. I’ve heard many people complain that Moock didn’t include enough examples. Personally, I felt the “Virtual Zoo” example that was referenced throughout much of the book felt out of place. Either he should have left it out or he should have built a larger variety of examples.

Reading through Essential ActionScript 3.0 reminded me of the textbooks I had in my college computer science classes. It’s the kind of no-nonsense book a software engineer would use as a stepping stone for a new language before moving entirely to the online documentation, which I think fits well with O’Reilly‘s typical audience. While I very much enjoy the Friends of ED Flash books for their tendency to be lighter reading and more guided, EAS3 was an odd breath of fresh air for me, and I can’t quite explain it. Regardless, know that while it’s a bit more technical, it’s not boring either.

One of the ultimate tests of a programming book, for me, is whether it teaches me anything new. As the guy who always seems to have an answer when my coworkers run into something strange, that can be a bit of a challenge. Generally, it’s some little function on a core class that I simply passed over a million times while reading the documentation. For EAS3, my moment of learning was a little more obscure, but I found the chapter that covers ApplicationDomains and communication betweens SWFs very interesting and I picked up a couple tidbits that I know I will need someday.

Though not for everybody, Essential ActionScript 3.0 is a good manual for development with Flash Player’s primary programming language, ActionScript. At nearly one thousand pages, a lot of information will be at your fingertips, and I imagine this book will sit very close to many developer’s desks. Beginners may find its information a little hard to follow, but experienced developers should feel right at home.

Open Source Flex Component: TreeMap

by Josh Tynjala

For some time, I’ve been working on a component to display treemaps in Flex applications. A while back, I put the source code in a public repository, and it was set free. I’ve received a lot of great feedback since I released the code, a few helpful bug reports, and I thank everyone who’s played with it already. Today, my TreeMap component for Flex reached an important milestone. I’ve marked it version 1.0, and I created a proper zip download containing the SWC, source code, API documentation, and several examples. You can download the package on the TreeMap project page right now.

I put together several examples. Take a look at a few of them:

Screenshot of TreeMap Component Stock Market Example

Stock Market (source). A TreeMap displaying fake stock data. The weight (size) of each item corresponds to the market cap and the color is the percentage price change.

Screenshot of TreeMap Component and Tree Comparison Example

TreeMap and Tree (source). The TreeMap component side by side with a regular Flex Tree. Both are displaying from the same data provider.

Screenshot of TreeMap Component Selection Example

Selectable TreeMap Nodes (source). Demonstrates a TreeMap with selection enabled.

The TreeMap component is now available under the terms of the MIT open source license, so it may easily be used in both commercial and open source projects. Please download the component, mess around with it, read the documentation, and have fun. Be sure to submit bugs if you find any.

Some Controversy over ECMAScript 4

by Josh Tynjala

Last week, I presented a first look at ECMAScript 4, the standard that Adobe uses as a basis for ActionScript. What I hadn’t yet discovered when I posted is that ES4 has caused a bit of controversy among the wider web developer community. We developers on the Flash side don’t always stay in touch with the developers using JavaScript, so I thought I’d highlight some of the arguments and conversations.

Some prominent JavaScript developers, including Douglas Crockford (creator of JSON and a fellow Yahoo) and some folks from Microsoft, believe that the changes in ES4 are too drastic and don’t address problems that should have been fixed. Douglas points out that JavaScript is inherently unsafe, and he argues that ES4 does nothing to fix the security risks. Another common argument is that nothing proposed in ES4 adds functionality that couldn’t be done in the previous version. In short, what’s more important? New functionality that wasn’t available before or better syntax for existing functionality?

The new syntax makes ECMAScript more like traditional programming languages, but the language also aims to stay backwards compatible with the current version. In other words, you can build classes using the new class syntax or you may use prototype like JS developers do today (sort of like how AS1 and AS2 gave us these same options in Flash for a long time). It raises a question in many minds, “Why?”.

The web may face an ugly transition involving widely different coding styles, and poor support for the new syntax across browsers. After almost a decade, developers encounter many differences across implementations of the current version of JavaScript. With so many new syntax options, bugs may cause heavy incompatibilities among early implementations of the new version. While the previously-mentioned version transition in ActionScript was mostly smooth, the browser world has a very different ecosystem that could make widespread adoption of the syntax changes more difficult.

Links

An interesting discussion overall. I’ll be watching with fascination to see what happens to “the language of the web” over the next year. Do I expect major changes to ES4 that could affect the next updates to ActionScript? Not particularly, but the desire for a language that stays true to JavaScript’s current version is strong among those that oppose ES4. I can’t say whether another JS-like language will be proposed as an alternative to ES4, but it’s certainly a possibility. I’m curious to see what happens.

Update: New information about this topic is available in my article How will ECMAScript “Harmony” affect ActionScript 3.

Discover ECMAScript 4: The Future of ActionScript

by Josh Tynjala

Update: Since I wrote this article, some interesting news has surfaced. New information about this topic is available in my articles Some controversy over ECMAScript 4 and How will ECMAScript “Harmony” affect ActionScript 3.

The ECMAScript working group recently released a (PDF) work-in-progress overview of ECMAScript 4. What is ECMAScript? According to the official website, the working group calls it “the language of the web”. More specifically, it’s the basis for languages such as JavaScript and Flash’s own ActionScript.

The official release of ES4 won’t happen until Fall 2008, but the working group releases updates from time to time to keep us informed (or salivating, depending on your level of geekiness). Adobe, a member of the working group, used an earlier draft of ES4 as the basis for AS3, and they’re “publically committed to sticking to [the ES4] standard” (source). The current update to ES4 includes many changes that we will probably see in a future revision to Flash’s programming language. I read the entire document from beginning to end, and I wanted to share some of my favorite discoveries.

Core Classes

Object and Array have picked up some new friends. In particular, a class called Map works a lot like Object, but it allows you to use any value as a key (not just a String). This is very similar to flash.utils.Dictionary in AS3, but there’s one interesting addition that I’ll get to in a moment. Similar to Array, there’s a new class named Vector. Of note, it provides bounds checking, and you can optionally specify a fixed length. Using a new language feature, both Map and Vector are parameterized types. Vector is actually what some might consider a typed Array. When you create an instance, you must specify the datatype of the objects you intend to place inside the Vector. Similarly, to use Map, you must specify both the key datatype and the value datatype. An example borrowed from the PDF overview should help illustrate how these will work:

//create a Map with keys of type * (known as any type) and values of type int
var example1:Map = new Map.<*,int>;

//create a Vector to contain integers
var example2:Vector = new Vector;

Language Features

Some of the coolest additions to ES4, in my opinion, are record types and the like keyword. Think of record types as ultra-light classes. They define members, but aren’t an entire class definition. Here’s an example of a record type:

type Point = { x:Number, y:Number };

It should be no surprise that you can create new instances of these types (you’ll get a regular Object, though) like any class.

var myPoint:Object = new Point();

What’s more interesting is that you can use the like keyword with record types to produce some interesting results. In AS3, a MovieClip has x and y properties that are both instances of class Number. This makes a MovieClip like the Point type described above (don’t confuse it with flash.geom.Point).

var clip:MovieClip = new MovieClip();
clip like Point //true

Imagine being able to run a function on any object that has x and y properties without requiring a special interface or setting a parameter’s type to Object (where you’d have to do runtime checks to ensure that x and y even exist!).

Another useful class-like feature is something called a union type. To understand union types, think of a current feature of AS3: Number, uint, and int are all pretty much interchangeable. That’s because ES4 defines an internal union type AnyNumber to accept and convert all numeric values as needed (notice a few new numeric types, by the way).

type AnyNumber = (byte,int,uint,double,decimal,Number);

The new let keyword gives us a more familiar block scoping mode used by other languages. In the current incarnation of AS3, a variable in a function is always accessible from anywhere in that function, by using let instead of var, you can make a variable that is only in the scope of a for-loop or an if statement. Excellent.

A feature I see requested often is operator overloading. Thankfully, this will be made possible thanks to another new feature generic functions. These functions are outside of classes and they’re pretty close to the bare metal of the runtime. Here’s an example:

generic intrinsic function + ( a:String, b:MyCustomString )
{
    //some operation that concats a MyCustomString with a regular String
}

The docs say that you cannot override a generic operator that has been implemented already, but you can add new ones that support your own custom classes. I’m sure some folks might complain, but I’d say it’s good enough for me. I’d hate to see the messes some dumb developer could create if he changed the way the core types behave with operators.

Finally, I’d like to share iterators. Two new types, IterableType and IteratorType give you the ability to code your classes to work with for-in and for-each-in loops more easily. Previously, in AS3, developers could only iterate over dynamic properties with these loop types. Now, by implementing a couple methods, get() and next() you can give a little more power to your applications, but only if needed. Older AVM1-era Flash applications could always iterate over properties, but today, that’s been removed for a performance boost. Nice to see this feature come back, if a developer chooses to use it.

That certainly isn’t everything new that we’ll see coming in the final version of ES4. I just picked out a few particular things that caught my eye and seemed the coolest. Be sure to read the ECMAScript 4 Overview PDF for full details.

Just as I was “impatiently waiting for ActionScript 3” back in the alpha days, you can bet that I’m just as excited for the next version today. Too bad it could be years away! When? Who knows. I’d say I’m pretty safe guessing that Flash Player 10 is out of the question. Adobe has their hands full with the features they’ve shared already. Furthermore, they would be silly to introduce major language revisions in two consecutive player versions. I’m also still seeing many learning the migration path from AS2, and I don’t think that dangerous sea will calm for a while. Definitely FP11 at the earliest, and after the ES4 spec has been finalized. In other words, be patient, but smile and dream of the cool coding tricks you’ll be able to do someday.

An Open Letter to Silicon Valley Recruiters

by Josh Tynjala

Dear Recruiter,

It looks like you’re helping a hot new client that needs talented developers yesterday. That’s great! Get out there and find the best of the best! I should warn you about something, though. When you want to contact me about the next “YouTube meets Salesforce meets The Next Big Thing™” startup, I may be a little difficult to deal with. It can be boiled down to the fact that I, like many developers, simply don’t like talking to recruiters. We just want to talk tech and write great code, and a recruiter isn’t always the person with the information we need. Adding a middleman to any process sucks. Let me give you some guidelines for keeping things running smoothly when dealing with a stubborn developer like me.

  1. Get to the point. I actually don’t particularly care who’s funding your startup. Investors don’t impress me. Buzzwords force me to read between the lines, so try leave those out as best you can. Honestly, I mostly care about what sort of cool projects I’ll get to work on and if I’ll be able to face interesting challenges. Tell me that you want a Flash or Flex developer, and give me some details about what I could be working on to actually get my attention. Informing me that some company is “the hottest new video startup” doesn’t help me because half the new startups out there call themselves “the hottest new video startup”. I shouldn’t need to ask, “what do they do with video?” In short, if you can’t tell me about the awesome products or services I’ll be able to help build, I’m not interested.

  2. I have contact me links all over my blog. That’s the best means of sending me a message if I don’t know you. I set it up mainly for folks that want to send me questions about my open source projects or blog content, but it’s great for contacting me about anything else too. Messages sent from the contact page go directly to my email inbox. In fact, I’ll admit that I like getting email that isn’t from the zillion mailing lists to which I’m subscribed. Send me something there, and I’ll probably read it. The only recruiter that’s ever gotten me to change jobs started the conversation by sending me a message through my contact page.

  3. LinkedIn messages are okay too. However, I’m unlikely to add you as a connection, even if I send you a response. If I added every recruiter that contacted me, I’d have expanded my network to a useless eighteen billion people that I don’t know very well. My LinkedIn connections are almost always people I’ve worked with or met at professional developer community events. Unless you’ve had a drink with me and talked tech, you’re probably not getting on that list.

  4. Facebook messages are never okay. My profile on Facebook is for personal friends only. Your message will never get a reply on Facebook. Guaranteed.

  5. Are you an employee of the company you recruit for? That’s better than if you work for some third-party recruiting company, in my eyes. Many recruiters don’t necessarily have enough information to interest me, and if you work for the company in question, you’ll be able to put me in contact much more easily with a person who has real answers. If you only have a basic job description, do you really expect me to go out of my way to learn more? I’m already happy with my current employer, so if I’m faced with too many steps to get from a recruiter to useful information, there’s no point in trying.

  6. I’m a Flash and Flex developer. My resume has been known to list a few other technologies I’ve been capable of using, but I believe that I’ve made it extremely obvious that I dig the Adobe Flash Platform above all else. Don’t contact me about your company that wants to build AJAX RIAs. While I am proficient with some JavaScript libraries like jQuery or YUI, I’m not going to drop Flash any time soon. Definitely don’t contact me about server-side development because that’s never going to happen. I’m a front-end, client-side developer.

  7. Do you prefer to contact me by phone? Please don’t. You’re interrupting me while I’m working, and you’re using up my precious time. I will do everything in my power to say, “thank you, but I’m not interested” as soon as possible. With email, I can read your sales pitch whenever I want, but the phone requires me to put everything aside specifically for you, yet another random recruiter. If you must insist on calling me, please see the following suggestions:

    • Don’t call me at work. Do you really think I want to say, “Sure, I’d love to work somewhere else!” when my manager sits nearby? Even giving you my email address (or a better time to call) feels impolite to my current employer. Why put me in a negative situation? It will only hurt your efforts. On a related note, calling the front desk of the company I work for to get my number only impressed me once. I thought the guy was being resourceful. Then I realized that apparently every recruiter does that. Thanks for wasting my employer’s resources too.

    • Don’t leave a voicemail if I’m not here. I’ve had phones that won’t let me delete messages until they’re finished playing. As you can probably probably imagine, I’m going to zone out once I hear, “Hi Josh, I’m a recruiter from [insert some recruiting company]“. I’ll read email or something while I wait for you to finish droning on and on about the boring life stories of your startup’s founders and investors.

    • Don’t ask me for additional contact information over the phone. The spelling of my email address seems to be difficult to understand sometimes. You got my phone number already with your dark recruiter magicks. I’ll bet you can find my email address too. Of course, for best results, consider using my contact page.

In conclusion, Mister or Miss Recruiter, please keep the interruptions of my day to a minimum, get to the point as quickly as possible, and try give me the juicy details. I promise I’m not actually that difficult to deal with. All I ask is that you have respect for my time and needs as an innovative technologist. If you have a job or contract that seems fascinating and stimulating, I’ll happily listen.

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

by Josh Tynjala

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

by Josh Tynjala

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.

Pages: Prev 1 2 3 4 5 6 7 8 9 10 ... 19 20 21 Next