07Apr FlashMVC Update: addResultListeners
I have just finished up making another addition to my framework FlashMVC. The update effectively removes the need to use ActionBinder as I will indicate below. ActionBinder was a neat utility, but ultimately I wanted solution that was just as simplistic but could be usable for both Flash and Flex. I couldn’t find any easy solutions until I thought about retrofitting addEventListener with an alternate form to allow callback functions to fire for specific commands on the SuperModel. Hence, I have added these three new methods to SuperModel:
.addResultListeners(actionName:String, onSuccess:Function, onFail:Function)
.addStatusListeners(actionName:String, enabled:Function, disabled:Function)
.addHasActionListeners(actionName:String, added:Function, removed:Function)
Now in your view, you can do something like this in your view:
app.addResultListeners(MySuperApplication.Login, onSuccess, onFail);
// SuperModel.perform(name of the action, optional onComplete function, ...Rest for the parameters of the action class)
app.perform(MySuperApplication.Login, null, "test@invalidemail@.com");
function onSuccess(result:*):void {
trace("Login was successful");
}
function onFail(result:*):void {
if(result==MySuperApplication.RESULT_INVALID_EMAIL)
trace("invalid email used");
}
Aside from this addition, I added in some safeguards like throwing an error if a command tries to call ActionHelper.complete() more than once as well as some other fixes. ActionBinder is still useful in the Flex world as it can help increase readability in some cases, but SuperModel now has most of the nice features built into it.
Please let me know if you have any comments! I am still working on adding in the replay feature to the framework which hopefully I will have done soon.
27Mar Further Reading on Design Patterns
As a followup on my Wednesday lecture on design patterns, I wanted to post some informative resources for learning more about design patterns outside the next lecture on the topic. Also, I wanted to say thanks for everyone who showed up to hear me rant about code structure (not the most exciting topic in the world mind you)!
Design Pattern Definition
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that can be used in many different situations. Object-oriented design patterns typically show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.
- read more at WikiPedia
MVC Definition (the most common principle of Design Patterns)

“Model–View–Controller (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages the communication of data and the business rules used to manipulate the data to and from the model.”
- read more at WikiPedia
Books:
- Gang of Four’s original Design Patterns
- Advanced ActionScript 3 with Design Patterns (highly recommended)
- ActionScript 3.0 Design Patterns: Object Oriented Programming Techniques
AS3 Design Pattern Informational Websites:
- www.as3dp.com – ActionScript 3 Design Pattern Blog (Principles Category)
- ntt.cc posts on of porting GoF design patterns to AS3
Flash Design Pattern Frameworks:
(for now, it’s best to avoid these until you understand the fundamentals of MVC)
Good Design Priniciples:
- ALWAYS type your variables (not really design principle but I too often see people doing this still)
- An object/MovieClip should contain the actions that it performs (as oppose to objects outside the class forcing it to perform actions)
- A class should never be able to “break” if the user sets a property or calls a function on it when they are not suppose to. Keep preventive logic in the class that’s doing the work.
- A good chosen design pattern for a problem will not take any longer to implement than not using it with spaghetti code.
Feel free to leave comments or email me about any further questions you have about Design Patterns or where to find additional materials on it. Have a great weekend everyone!
25Mar Detroit Design Pattern Seminar

On Thursday 3/26/2009, I will be giving an open seminar on design patterns for the Detroit Adobe User Group. I should have blogged about this much earlier but my free time has been spread thin of late unfortunately. It will be hosted at ePrize starting at 7:00pm and ending about 9:00pm. I will be covering just some introductory topics of good programming practices with AS3 while diving into some design pattern concepts. There is also a good chance that I will do a more advanced seminar on design patterns in the near future at the user group meetings. This conference will be free to the public so please leave a comment or shoot me an email for directions or more information.
-[ Jonathan_Dunlap::email="jonathan AT jadbox.com" ]-
21Feb FlashMVC API Update
While having time this weekend to review a few of the Flash projects I’ve been working on, I became aware of the idea that every software “action” has the anticipated state of failing. Login will fail if the user enters incorrect credentials or leaves a field empty; A user cancels a file copy operation; A reg form may fail if the user is not permitted to enter the site based off their information. It’s not that the application is failing because it can’t reach a web service or something unexpected happened, but rather a planned reaction was developed to give the user a negitive response to their action. In light of this, I have updated FlashMVC to allow actions to designate that it’s result is negitive/failed. Then on the SuperModel side, the view can optionally supply a fail callback function for when the action designates that it failed.
public class Login {
public function Login(helper:ActionHelper, name:String, password:String) {
if(name=="user" && password=="pw") {
SuperSimpleApp.getInstance().userFirstName = "John Doe";
helper.complete();
} else {
if(name=="" || password=="") helper.result = SuperSimpleApp.RESULT_EMPTY_FIELDS;
helper.complete(false); // "false" tells the caller that this was not successful
}
}
}
The line “helper.complete(false)” tells the SuperModel that the action completed but it was a negative response. In this example, it was failing the login action. So we have the action created, now we need to create the SuperModel that its attached to and the SuperModel will also service as its model.
public class SuperSimpleApp extends SuperModel {
public static const LOGIN:String = "Login"; // String reference to the class name for the view to call
// Flag a response to use in special situations where the view needs to know more about the result
public static const RESULT_EMPTY_FIELDS:String = "emptyFields";
public var userFirstName:String;
public function SuperSimpleApp() {
// Register the class to the SuperModel for use.
// Note: once the action is added, use the string name of the class to reference it
actionAdd(Login);
}
public static const getInstance():SuperSimpleApp = new SuperSimpleApp();
}
Now in Flash or in your Flex MXML you can run your Login action like this:
// loginAction will hold the action class we want to call and setup the onSuccess and onFail callbacks.
var loginAction:Performance = new Performance(SuperSimpleApp.LOGIN, onSuccess, onFail)
// ...
// Now later in the code, run the action now on the SuperModel with a test username and password
function onSubmitButtonClick(e:Event) {
superModel.process(loginAction, "user", "pw");
}
// If the user is logged in successfully
private function onSuccess(result:*):void {
trace("Hello "+ superModel.userFirstName);
}
// If the login action designated a negative response to the request:
private function onFail(result:*):void {
// Check the result against known responses flagged in the super model... otherwise give generic message.
if(result==SuperSimpleApp.RESULT_EMPTY_FIELDS) trace("Please fill out all fields");
else trace("Invalid username or password");
}
This should help having to deal with common success and fail responses from actions. Let me know what your thoughts are!
13Feb AS3 Best Practice for Callback Evals

UPDATED: Thanks to my readers- there is an even easier way to evaluate a function as being not null without a compiler warning. One suggested a method using a type check (functionName is Function) however this is process intensive task for the compiler especially if this has to be done within a game loop. I believe the most efficient solution was suggested by Mije for doing a strict comparison by !== against null. This is better than != as the previous evaluation executes faster.
One of the techniques I am fond of is callback functions when using a custom event may be overkill for the situation. However, trying to actually explain callbacks verbally is almost impossible. In a nutshell, it’s a method (lets say A) that accepts another a method (lets say B) as a property. Method A will perform its action and then call method B. This allows the class that uses Method A to have one of its methods called once Method A completed.
Here is an example; however, in practice, callbacks are only useful when the method that uses it is in a different class otherwise you could just call the method directly instead of using the callback.
private function gameEnded():void {
saveScore(10, onSave);
}
private function saveScore(score:int, onSaveCallback:Function):void {
// saving score...
// once done:
onSaveCallback();
}
// This is the function that gets past into saveScore
private function onSave():void {}
Okay okay, now here is the problem at hand. What if the callback function was optional? You could write it like this:
Not so fast! If the callback function is not specified and gets set to null, Flash will throw an error since you cannot call null as a function like this: null().
Well, you could do a conditional check:
This way we can check to see if onSaveCallback does not equal null. Well, this angers the Flash compiler and it will throw the below message:
Warning: 3553: Function value used where type Boolean was expected. Possibly the parentheses () are missing after this function reference.
This is because Flash is confused that you are trying to evaluate a function as a Boolean instead of using it normally as a function. So, how can we evaluate if the function is not null without throwing a Flash warning? Well, I scowered the internet and could not find a best practice for Flash. After a discussion with my readers, the best solution here is to do a strict type check to null as shown below:
Well there you have it- let me know if this works for you!
01Feb ActionScript Reference for Android!
After seeing that someone wrote an ActionScript reference application for the iPhone called ActionScript 3 API Reference for iPhone, I decided to take matters into my own hands and make the same application for the Android platform which the t-mobile G1 works on. The Android OS is a fantastic platform for a developer as I made this whole application over just two weekends. For the first release, I included a view to see all classes and a class search functionality. You can now download this from the Market on your Android phone! You can find it under the Application – Reference section, and it’s called ActionScript Reference. See the below screenshots…
Classes View:

Class Information View:

For more information on Android: http://www.android.com/
26Jan FlashVars for EVERYONE!
When building utilities that can be used with both Flash and Flex, there are two common hurdles that developers run into. The first one is that Flex does not pull FlashVars the same way that Flash does. This means for ActionScript utilities that rely on html inserted variables will need to be separated into two separate files or need to have flashvars passed into the utility from the outside. Another hurdle is that Flash does not have a global reference to Stage- instead it can only be accessed through display children of stage. This is problematic for utilities that work with Stage as they can only get there reference of stage when it’s manually passed into the utility as a parameter which can result in an ugly web of stage references being passed around.
However, I finally got the time to develop a workaround that solves both problems with classes FlashVars and StageReference. The tricky part of this implementation was building a utility that could use the class Application but not reference it when it was being built from Flash since it would cause the compiler to fail from the invalid class reference. I worked around this issue by grabbing Application by getDefinitionByName so that the Flash compiler wouldn’t fail since it was a weak reference.
With Flash, use StageReference.stage = stage in Frame 1 or in your document class’s constructor. This will give you the global reference to stage and also allow the new class FlashVars to pull flashvars automatically when compiled in a Flash project.
The custom class FlashVars is used in this fashion:
or
This usage is exactly the same from Flash and Flex! No more having to switch from loaderInfo.parameters to Application.application.parameters when porting utilities between Flash and Flex.
Download (includes StageReference): flashvars.zip
16Jan Object to URLVariables
Looking back at my last few blogs, I seem to have been neglecting to post ActionScript related stuff even though I have been more development than ever. It’s probably due to the fact that since I work with it all day that I lack the ambition to blog about about it.
One of the many great things working with Flex is being able to use HTTPService which is a very neat utility. So one day I was working with pure Flash and discovered that URLRequest data property only really allows URLVariables object (and ByteArray for those who do their homework). HTTPService on the other hand can take in raw Object and parse all its properties (including dynamic ones) into a POST payload. With a little digging into HTTPService, I extracted the code it uses to parse and object that I used to build the below function that will convert an Object into a URLVariables object so that you can send it with URLRequest.
Updated: This will work in any version of Flash AS3 now.
var paramsToSend:URLVariables = new URLVariables();
for(var i:String in parameters) {
if(i!=null) {
if(parameters[i] is Array) paramsToSend[i] = parameters[i];
else paramsToSend[i] = parameters[i].toString();
}
}
return paramsToSend;
}
18Dec Why Google Native Client is not a Flash competitor
There has been a lot of buzz around the internet about Google’s new development project called Native Client. This very ambitious project attempts to being desktop applications to the web browser. This project has a very long road ahead of them as it becomes extremely difficult to regulate an application that is able to access hardware or low level software hooks at will. However, even when this project is able to find its feet, it is NOT a competitor to online interactive mediums like Flash or Silverlight. This is because desktop applications are tailored to the desktop platform. Sure, Native Client can run the game Quake through the browser, but why wait downloading 100+ megabytes to play the game inside a small browser window when you could download it in its original form and play it on the desktop? The platform is simply not web-friendly at its core. Having said that, perhaps one day once the internet speed is as fast as desktop HDs and Native Client is able to execute code without any dependency on the operating system, that would be golden. This would allow browsers (like Chrome) to literally be the operating system for the computer. However, while Native Client may be backwards compatible, Flash, Silverlight and JavaFX are working hard to bring OpenGL acceleration and near-desktop math processing support. These platforms are much more web-friendly as they are optimized to be compact and able to stream load their code during runtime (which is highly valuable when you are considering enterprise-class applications).
I’m still very annoyed by the fact that Flash, Silverlight, and JavaFX are all roughly 10 times slower in basic math operations than pure C# or any other desktop platform.

