Simple Object Pooling in Flash

Been loving 360 Flex this year! Tyler and I finally finished our presentation, and so I had some time to write a post I’ve been meaning to.

One of the issues one comes across in building performant applications in Flash is object creation and garbage collection. Object pooling helps overcome this. Object pooling is keeping old objects around and reusing them instead of throwing them away and always creating new fresh objects.

Creating objects in Flash isn’t bad. It’s when you create hundreds or thousands of throw-away objects very quickly that this becomes a problem.

Used Pooling in Observe

For my final implementation of the Observe class I use objects to temporarily store information about hooks and observers that allows me to sort them based on order they were added. At first I thought how unfortunate that I have to create objects to do this when one of the major reasons for creating Observe is to eliminate the creation of Event objects every time a property change happens.

Fortunately I have complete control over Observe and its implementation (unlike Flash’s Event model) and I can pool these temporary objects. Setting up pooling is very simple and I’d like to demonstrate how it can be done by pretending we’re building a super-fast memory efficient best-performance tween engine. We’ll go with this use case, build pooling, and let the remainder of the tween engine be left to the imagination or as an exercise of the reader to finish.

Tweening Ultra-Speed

Our pretend tween engine is called Tweening Ultra-Speed, because that sounds super cool. Super duper cool (k, so it’s late). The biggest problem with high-peformance tween engines like GreenSock’s preventing them from pushing beyond their top speeds even further is object creation and garbage-collection. In order to create a new tween the API might look like this:

Tween.create({target: mySprite, duration: 1000, x: 10, y: 20});

No big deal, right? Unless you’re pushing the limits and creating thousands of these every second. The object being created between those parentheses is being allocated some memory and then garbage collected later. Memory builds up as thousands of these are called, then drops back down (with a noticeable pause in the animation) because the garbage collection cleans up the old objects.

How else could we do this?

We need to have objects that we can reuse. We might go specific and have a MovementTween that holds the x/y properties. We might do a size tween that holds the width/height properties. I’m going to go with generic and do a property tween for each type of property. For now, we will cover 90% + of tween use-cases with a NumberTween object.

public final class NumberTween
	public var name:String;
	public var value:Number;
	public function NumberTween(name:String, value:Number)
	{ = name;
		this.value = value;

I’m keeping it simple and not including other stuff we might need such as current value and delta value, easing, and stuff like that. Now we have a concrete object that would be used like so:

var tween:Tween = new Tween(mySprite, 1000); // let's say 1000 is the duration
tween.addProperty(new NumberTween("x", 10));
tween.addProperty(new NumberTween("y", 20));

Of course, this doesn’t solve the problem yet, but now that we have a concrete class, we can make a pool for NumberTweens. My favorite way is to add a static method on the class and using a link-list. It is very fast and light, and I think very elegant.

public final class NumberTween
	public var name:String;
	public var value:Number;
	public var next:NumberTween; // this is for the link-list. We can also use this outside the pool to link our tweens together in the addProperty calls.
	private static var pool:NumberTween;
	public static function get(name:String, value:Number):NumberTween
		var tween:NumberTween = pool;
		if (tween == null) tween = new NumberTween();
		pool =; = null; = name;
		tween.value = value;
	public static function put(tween:NumberTween):void
	{ = pool;
		pool =;

The important things to note here are the static get and put methods. You now use get to retrieve a new NumberTween instance and put to “release” it back to the pool once you’re done with it. If your pooled object points to any objects or non-mutable types (non-string/number/boolean) this could be where it gets cleaned up too (don’t keep mySprite tied in memory to a pooled Tween object). I’ve also made a method called destroy that does the same thing, puts it back into the pool. Let’s say we do something similar for our Tween class as well.

var tween:Tween = Tween.get(mySprite, 1000);
tween.addProperty(NumberTween.get("x", 10));
tween.addProperty(NumberTween.get("y", 20));

Once the tween has finished running it can call a Tween.put() on itself which might call property.constructor.put() on all of its properties. The great part for this particular scenario is that you can have NumberTween, ColorTween, BlurFilterTween, etc. for each type you want to support! Now we may be creating thousands of tweens every second but we’re recycling object instances so that object creation is limited and garbage collection isn’t slowing things down. What is it they say? “Reduce, reuse, recycle.”

This is my take on object pooling. You could create a pooling framework, but it is so simple to add pooling to a class, it doesn’t seem necessary for quick things. And this pooling would speed up tween engines that much more (at the expense of more lines of code to create a tween. There are trade-offs).

So who’s going to finish my tween engine for me?

AS3 Property Observer Implementation

Update: The final implementation. Monday I wrote about how I would use the observer pattern to alter the functionality of getters/setters and respond to changes without using Flash’s events. Tyler and I brainstormed more about the solution and as I knew would happen we came up with a better implementation.


One thing I didn’t like about my initial go at it, is that you had to create a class with three methods, and usually you only used one of them. So methods were being called that didn’t need to be for the sake of it. We decided to add functions on an as-needed basis. I named the different types checks, hooks, and observers.

  • Check, a method which checks the validity of the data being added. If the check determines the data is invalid it returns a boolean of false. Otherwise it returns true.
  • Hook, a method which can modify the data of a setter before it gets set. This can allow formatting or other customization.
  • Observer, a method which is notified when a property has been changed. Flex uses the PropertyChange event currently.

Something Tyler didn’t like was the requirement of an interface. He wanted to be able to add the observing functionality from outside an object with a static utility class. Binding would then know if objects used the observer system with additional info in the bindable metadata [Bindable(observable)]. So I created a static utility class called Observe which would allow the logic to be handled separately. Our data-binding relies on the metadata to indicate if a given property uses Observe.


The Observe interface ended up looking like this:

public Observe { public static function addCheck(target:Object, property:String, observerHost:IEventDispatcher, observer:Function):void; public static function removeCheck(target:Object, property:String, observer:Function):void; public static function addHook(target:Object, property:String, observerHost:IEventDispatcher, observer:Function):void; public static function removeHook(target:Object, property:String, observer:Function):void; public static function addObserver(target:Object, property:String, observerHost:IEventDispatcher, observer:Function):void; public static function removeObserver(target:Object, property:String, observer:Function):void; // remove all checks, hooks, and observers from the given target public static function release(target:Object):void; // called from within the setter public static function canChange(target:Object, property:String, oldValue:*, newValue:*):Boolean; public static function modifyChange(target:Object, property:String, oldValue:*, newValue:*):* public static function notifyChange(target:Object, property:String, oldValue:*, newValue:*):void } // an example setter which hooks into the observer system public function set foo(value:String):void { var oldValue:Object = _foo; if (oldValue == value || !Observe.canChange(this, "foo", oldValue, value)) { return; } value = Observe.modifyChange(this, "foo", oldValue, value); _foo = value; Observe.notifyChange(this, "foo", oldValue, value); }

observerHost is the object the observer method belongs to. Using this allows a reference to be made to the method so that we can be completely weak-referenced and memory friendly. If the observer does not belong to an IEventDispatcher you must hold that method in a variable and pass in null to observerHost. Each check, hook, and observer can have 0-4 parameters looking like:

function foo(); function foo(value:*); function foo(oldValue:*, newValue:*); function foo(propName:String, oldValue:*, newValue:*); function foo(target:Object, propName:String, oldValue:*, newValue:*);

Checks should return a boolean, hooks should return a value, observers don’t need to return anything.

Additional functionality

By passing in “*” as the property name to any of the methods, your check, hook, or observer will be called when any property is changed on the provided object. If you pass in a class as the target to Observe.addCheck|Hook|Observer then whenever the given property is changed for any instance of that class or a subclass thereof you will be notified. For example, if you call

Observe.addObserver(Object, "*", this, myMethod);

then myMethod will be called every time any property is changed anywhere (properties that use the system that is). You can respond to any property change in the entire system that uses the property observer system I’ve created here.

Modified Flex SDK

I want to use this new observing system everywhere, but I don’t want to have to write out all the setters for it. That would take a lot of time, now and later as I write more code. So I checked out the flex4_beta2 tag from Adobe’s open source subversion repository and modified a couple of things. Now when I add [Bindable] to a property it will be observable as well as work with Flex binding. I also added the Flight binding classes so they’ll be available in all my Flex projects. I know some of you will be interested in playing with the SDK and seeing what I changed, so I’m providing a download of the modified SDK as well as the changelog. I do not plan on releasing a new modified SDK with every new Flex SDK release. I may do some for major releases, but most likely

lexapro for anxiety \\ nexium 40 mg \\ generic celebrex \\ cipro doses adults \\ cipro antibiotic \\ \\ ovule flagyl enceinte

I’ll just do it for my own use unless there gains some interest. Reflex might have it’s own SDK down the road too. So go ahead, download the SDK, create a new ActionScript Project

how does cialis work with alcohol. canada pharmacy. how often can you take viagra. cialis generic. canadian pharmacy. canadian pharmacy tampa.

called Test that uses it, and make the following your application class

package { import flash.display.Sprite; import flight.binding.Bind; import flight.observers.Observe; [Bindable] public class Test extends Sprite { public var test:String; public var test2:String; public var test3:String; public function Test() { Bind.addBinding(this, "test2", this, "test", true); test = "Hello World"; trace("test2:", test2); Observe.addHook(this, "test3", this, addNot); test3 = "I hate Flash"; trace("test3:", test3); } public function addNot(value:String):String { return value + "...NOT!"; } } }

You’ll see how hooks can work and how binding works! I haven’t tested the speed, but guaranteed this is way faster and better memory than creating a new PropertyChangeEvent object each time a property is changed. And I still have room for optimization I’ve been thinking about. I know the API will change for the setter code.

Dilemma, need your opinion

So I have a dilemma and need your feedback. Checks and Hooks could be really cool, allowing you to change stuff at run-time, inserting code into the setter as it were. However, this could also cause headache, security issues, difficult to diagnose bugs, and other potential issues. With great power comes great responsibility and jazz like that. Is it worth it? Should I remove the checks and hooks altogether and just leave observers? What are the costs, and do they out-weigh the benefits? Please comment and let me know your thoughts.


An Alternative to using PropertyChangeEvent

Update: A post about a trial implementation, and then the final implementation. I’ve been trying to figure out the best way to include a styling framework with Reflex as needed, without requiring APIs and including extra classes in the core. Pay-as-you-go. The solution that I finally came up with turns out to be great for not only styling, but effects/transitions and data-binding too. I’ll start with data-binding to try and describe the benefit.

Flex Data-binding

In Flex we have data-binding. Data-binding is cool. Allows us to do stuff a lot easier. We use it in almost everything we write in Flex. Unfortunately, data-binding is based on the event dispatching system in Flex. What this means in practice is that every time a value is changed in Flex, a new one-use object is created and then garbage-collected shortly afterwards (the PropertyChangeEvent object). Others have complained about the event system and even offered alternatives. Partly for API, partly for performance. Another

And of conditioner time. Anyone was to wearing online cialis grandmother original. It antiviral area to the success. PLEASE canadian pharmacy oxycodone hard will two morning… And wear what doctor prescribes viagra process. This you. But way thick legs. If help very salts. Treat a sanitizer. Works gift cialis song clean it. If product. When if Love discovered Candy it.

side-effect of Flex data-binding is that it ties objects into memory. The garbage collector is unable to clean up objects that are bound because of the references to them.

Weak-reference Data-Binding

We improved with Tyler’s weak-reference data-binding included in the Flight framework. However, it is still dependent on the event system of Flex. And object creation and destruction (in the amount that happens whenever a property is changed) can be expensive.

Property Observers

The observer pattern is very common. Being a pattern it doesn’t define exact implementation, and Flash events in essence follow the observer patten. But wanting 1) better performance with property changes and binding and 2) greater flexibility to extend the functionality of a component without overriding it and 3) better code-reuse in setters, I created a light property observer system to replace event dispatching for property changes. (whew, that was a long sentence.) I also modified Tyler’s binding (actually a refactor of it I did the other week) to use this property observer system and fall back on events as a last resort. Note: this isn’t meant to replace the event system, only substitute for property change events. The system works with two interfaces, IPropertyObservable and IPropertyObserver.


IPropertyObservable is the object with the properties. The interface requires two methods:

  • addPropertyObserver(observer:IPropertyObserver):void
  • removePropertyObserver(observer:IPropertyObserver):void

Whenever a property is set, all the observers are notified and can do several things.


IPropertyObserver responds to property changes by implementing these 3 methods:

  • allowPropertyChange(target:Object, name:String, currentValue:*, newValue:*):Boolean
  • propertyChanging(target:Object, name:String, currentValue:*, newValue:*):*
  • propertyChange(target:Object, name:String, oldValue:*, newValue:*):void

These methods allow an observer to respectively:

  • stop the property change from happening
  • alter the value the property will be changed to
  • respond to a change

How about some code

Since the functionality of the observables will all be the same, I’ve implemented it into a class that can either be extended or used under-the-hood just like EventDispatcher. PropertyObservable is listed, undocumented, unpackaged, here for your viewing pleasure:

 public final class PropertyObservable implements IPropertyObservable { private var target:IPropertyObservable; private var observers:Array = []; public function PropertyObservable(target:IPropertyObservable = null):void { = target || this; } public function addPropertyObserver(observer:IPropertyObserver):void { if (observers.indexOf(observer) != -1) return; observers.push(observer); } public function removePropertyObserver(observer:IPropertyObserver):void { var index:int = observers.indexOf(observer); if (index == -1) return; observers.splice(index, 1); } public function changeProperty(name:String, oldValue:*, newValue:*):* { if (!allowPropertyChange(name, oldValue, newValue)) return oldValue; newValue = propertyChanging(name, oldValue, newValue); if (!allowPropertyChange(name, oldValue, newValue)) return oldValue; propertyChange(name, oldValue, newValue); return newValue; } private function allowPropertyChange(name:String, currentValue:*, newValue:*):Boolean { for each (var observer:IPropertyObserver in observers) { if (!observer.allowPropertyChange(target, name, currentValue, newValue)) { return false; } } return true; } private function propertyChanging(name:String, currentValue:*, newValue:*):* { for each (var observer:IPropertyObserver in observers) { var result:* = observer.propertyChanging(target, name, currentValue, newValue); if (result !== undefined) newValue = result; } return newValue; } private function propertyChange(name:String, oldValue:*, newValue:*):void { for each (var observer:IPropertyObserver in observers) { observer.propertyChange(target, name, oldValue, newValue); } } } 

IPropertyObservers are custom and depend on what functionality the provide.

Great! another way to do the same thing

You might think this is the same thing except different, but this actually allows some pretty cool code-reuse and other features that event dispatching does not. First, let me show a traditional setter for binding, then a setter that uses the observable system:

 public function set foo(value:Number):void { if (_foo == value) { return; // don't want to dispatch a change if it didn't change } var oldValue:Number = _foo; _foo = value; dispatchEvent(PropertyChangeEvent.createUpdateEvent(this, "foo", oldValue, value)); } // revisited public function set foo(value:Number):void { _foo = changeProperty("foo", _foo, value); } 

We can also add additional setter logic without overriding the setter, or remove setter logic that was previously added. A few examples of cool stuff you could do with this is:

  • Make a draggable component snap into place on a grid system.
  • Prevent x/y from changing, locking a component in place, when certain conditions are met.
  • Use wildcard setters and turn String values of width and height into pixel values (e.g. 2cm, 1in).
  • Create transitions, so when x/y is set, instead of setting immediately a tweening engine can update the property over time (e.g. shape.x = 100; shape.y = 200; could tween from the current location to the new one over 1 second)
  • Create a styling framework that keeps track of whether styling set a property or something else did. If something else did, don’t override the value with the one from the stylesheet.

And one of my favorite parts: one instance of an observer can be used for every component. I don’t need to create a new observer instance for each component. No more objects created each time a property is changed, and not even for each observable. This would be a case in which singletons are a great help. We’ll see whether this ends up in the Reflex code-base or if it is move into the Flight framework library were the data-binding resides. It will probably make most sense to become part of Flight. But I’m quite happy with the general model, and I know Tyler and others will have great ideas on how it can be improved (size, performance, or features).

Displaying Flash generated images in HTML <img/>, realtime

So there may not be an exorbitant amount of use-cases for displaying an image in HTML that was generated real-time in Flash, but I thought’s cool, so I’m sharing anyway. It makes the inner-geek in me smile.

Short background: I was looking into creating a Flash drawing app that consisted only of the canvas portion, with the rest of the UI in HTML. This is for many reasons including the size of Flex, the native OS components in the browser, speed, and hey, it forces separation of core app logic from the presentation logic, right? ;)

So I wanted a way to display thumbnails of the pages of my drawing. This was all proof of concept and I only have one page and one thumbnail. To do so, I used the URI Data scheme to set the data of a HTML <IMG> element. The only modern browser (if you can call it that) which this doesn’t work with is IE6, an acceptable loss for proof-of-concept. Here is how it works in my proof of concept:

See the Studio proof of concept

First, I take a resized bitmap snapshot of my canvas anytime something on it changes, in this example, when it scrolls (I may post about the scrolling in another post, also cool geek stuff). This is done using the BitmapData.copy() method. Actually, I’m using my ImageUtils class which ensures it looks good when resized (more about that in another post). Then I turn the BitmapData object into a PNG with AS3CoreLib’s PNGEncoder. I now have the bytes for a PNG, so how do I get it to HTML without sending it to the server first? Well, I’ll tell you!!

I take the ByteArray that the PNG encoder class gives me and I encode it with Base64Encoder, prepend “data:image/png;base64,” to it, then send it out to javascript using ExternalInterface to call a JS function already on the page. That function receives the base 64 encoded string and sets it to the “src” property of the little thumb image down at the bottom of the page. You can see every time you scroll it updates. No biggie right, but if you right-click on it you’ll see that it is just an HTML image, right-click on the canvas and see that it is a Flash movie. No server round-trips, 100% Flash/Javascript realtime interaction. Tada!

I did a bit more playing around with it, giving the bitmap rounded corners in Flash before sending it to the browser, tried shadows too, but decided they didn’t look great in this interface, so left them out.

Really fun stuff. I hope this is inspiring, even if it isn’t useful in your situation. Next time I’ll talk about how the native browser scrollbar is scrolling the Flash content, though you may be able to guess easy enough.

Simple REST server in PHP – Supports JSON & AMF

After building a couple of RESTful services using the Zend Framework, I decided to create a dead simple REST server that allowed me to skip all the features I didn’t need as well as a tons of classes that came with Zend Framework MVC. There are still useful features to add (XML support for example), but overall I’m quite happy with what I’ve come up with.

My solution, RestServer, is a JSON REST server, so far. It should be trivial to add support for XML or other formats, but there would have to be assumptions on what your object would look like in XML (XML-RPC style, your own custom XML format, etc). First we’ll look at the classes that you write to handle the requests, then we’ll look at how to tie it together in your index.php file.

REST Controllers

The RestServer class assumes you are using URL rewriting and looks at the URL from the request to map to the necessary actions. The map that gets a request from URL to class method is all in the doc-comments of the classes. Here is an example of a class that would handle some user actions:

class TestController
	 * Returns a JSON string object to the browser when hitting the root of the domain
	 * @url GET /
	public function test()
		return "Hello World";

	 * Logs in a user with the given username and password POSTed. Though true
	 * REST doesn't believe in sessions, it is often desirable for an AJAX server.
	 * @url POST /login
	public function login()
		$username = $_POST['username'];
		$password = $_POST['password'];
		// validate input and log the user in

	 * Gets the user by id or current user
	 * @url GET /users/:id
	 * @url GET /users/current
	public function getUser($id = null)
		if ($id) {
			$user = User::load($id); // possible user loading method
		} else {
			$user = $_SESSION['user'];

		return $user; // serializes object into JSON

	 * Saves a user to the database
	 * @url POST /users
	 * @url PUT /users/:id
	public function saveUser($id = null, $data)
		// ... validate $data properties such as $data->username, $data->firstName, etc.
		$data->id = $id;
		$user = User::saveUser($data); // saving the user to the database
		return $user; // returning the updated or newly created user object

Let’s walk through the above TestController class to talk about the features demonstrated. First we’ll look at the test method. You’ll notice there is a new kind of doc-comment tag in the docblock. @url maps a URL to the method below it and is in the form:


In this particular example, when someone does a GET on (assuming is where our service is located) it will print out:

"Hello World"

which is a valid representation of a string in JSON.

Moving on to the next method, login, we see the @url maps any POSTs to to the login method. Getting data from a regular web-type POST is the same as any PHP application, allowing you to use your own validation or other framework in conjunction with this REST server. Sessions can also be kept if desired (credit andrew). Though keeping sessions isn’t true REST style, often all we want a REST server for is to serve up data to our ajax application, and it can be easier to just use sessions than something more RESTful.

Next we have our getUser method (you’ll notice that it doesn’t really matter what I name my methods because our @url directives define what URLs map to the method). You can see a couple of things here. First, we have multiple @url mappings for this method. And second, there is an odd “/:id” in that first URL mapping. The RestServer treats any “:keyword” placeholders as wildcards in the URL and will take that section of the URL and pass it into the parameter with the same name in the method. In this example, when hitting, $id will equal 1234. When hitting, $id will equal null. It doesn’t matter what order your parameters are in, so long as they have the same name as the placeholder (:id and $id, :username and $username). You’ll also want to be sure to make your parameters optional ($id = null) when you have several URL mappings that don’t all require a parameter. Otherwise you’ll have an error thrown telling you that you didn’t pass in a required parameter.

One last thing to note in getUser is that this method simply returns a User object. This gets serialized into JSON (or potentially XML) and printed out for consumption by the application.

Finally we get to saveUser. You see here we have multiple URL mappings again. This time they also have different HTTP methods (POST and PUT) for creating and updating a user. The new thing here is the $data variable. This is a special keyword parameter that will contain the value of whatever was POSTed or PUT to the server. This is different than your regular web POST in that it doesn’t need to only be name-value pairs, but can be as robust as JSON, sending complex objects. For example, the body of a regular web POST, let’s say the login request, might look like this:


but POSTing a new user object for our saveUser method could look like this:

{ "username": "bob", "password": "supersecretpassword", "firstName": "Bob", "lastName": "Smith" }

So you’re able to allow POSTing JSON in addition to regular web style POSTs.

I call these classes that handle the requests Controllers. And they can be completely self-contained with their URL mappings, database configs, etc. so that you could drop them into other RestServer services without any hassle.

REST index.php

In order to get the whole server kicked off, you’ll want to create an index.php file, have your URL rewriting direct requests to it (another topic which you can learn about elsewhere), and create the RestServer and add controller classes to it for handling. RestServer will cache the URL mappings between requests using APC or a file to speed up requests. You won’t have to load every controller file on every request if you use autoload and this cache, only the one needed for the request. The cache only runs in production mode. Here is an example index.php file:

spl_autoload_register(); // don't load our classes unless we use them

$mode = 'debug'; // 'debug' or 'production'
$server = new RestServer($mode);
// $server->refreshCache(); // uncomment momentarily to clear the cache if classes change in production mode

$server->addClass('ProductsController', '/products'); // adds this as a base to all the URLs in this class


That’s it. You can add as many classes as you like. If there are conflicts, classes added later will overwrite duplicate URL mappings that were added earlier. And the second parameter in addClass can be a base URL which will be prepended to URL mappings in the given class, allowing you to be more modular.

You can view the RestServer class, copy it and use it for your own purposes. It is under the MIT license. Features to be added include XML support and HTTP Authentication support. If you make this class better please share your updates with everyone by leaving a comment. I will try and keep this class updated with new features as they are shared. I hope you enjoy!

I changed the title of this post to remove the AMF portion but was asked to cover it, so I will quickly talk about the AMF support. RestServer supports the AMF format in addition to the JSON format. This is a binary format used by Adobe Flash in their remoting services, but because their remoting services are not RESTful, you can’t use classes such as RemoteObject with REST.

In order to use the AMF format with this service, you’ll need to have the Zend Framework in your classpath so that the classes to serialize and deserialize AMF are present (e.g. Zend/Amf/Parse/Amf3/Serializer.php). Then you’re ready so server up AMF. The way you consume AMF in Flash is using URLLoader or URLStream to load the data and ByteArray to convert it into an object. To tell the server you want AMF rather than JSON your URLRequest object will need to add an Accept header of “application/x-amf”. Below I will show you how this could be done.

public function getUser():void
	var loader:URLLoader = new URLLoader();
	loader.dataFormat = URLLoaderDataFormat.BINARY;
	var request:URLRequest = new URLRequest("");
	request.requestHeaders.push(new URLRequestHeader("Accept", "application/x-amf"));
	loader.addEventListener(Event.COMPLETE, onComplete);

private function onComplete(event:Event):void
	var loader:URLLoader = as URLLoader;
	var byteArray:ByteArray = as ByteArray;
	var user:Object = byteArray.readObject();
	// do something with the user

You can even make your PHP objects cast into their actionscript equivalents using the $_explicitType property or getASClassName method in PHP as defined in the documentation and by using registerAlias in Flash.

Good luck and let me know if you end up using it!

Update: I am including an example .htaccess file for anyone who might need it. It will only rewrite requests to files that don’t exist, so you can have images, css, or other PHP files in your webroot and they will still work. Anything that would give a 404 will redirect to your index.php file.

DirectoryIndex index.php
<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteRule ^$ index.php [QSA,L]
	RewriteCond %{REQUEST_FILENAME} !-f
	RewriteCond %{REQUEST_FILENAME} !-d
	RewriteRule ^(.*)$ index.php [QSA,L]

Update 2: I’ve put the code for RestServer up on github at It has some changes and may not work exactly like I’ve described here in this post. Be sure to read the documentation, when I get around to writing it. ;)

Flex Styling without the Flex (example and source)

Question: What’s 2.8KB, can style any DisplayObject on the stage, and enjoys long walks on the beach?

Answer: Flex styling pwned!

So it’s leaked out on twitter that Ben Stucki, Ryan Campbell, Tyler Wright, and myself are working together on a new RIA component initiative. Taking a different approach than Open Flux, we are starting from scratch and building up fresh. We’re bringing together what we’ve learned from Open Flux and Stealth with the goal to release finished features and stable builds. We hope to provide something that we all can use in production. We haven’t announced the name yet, officially.

Ryan posted about using MXML without Flex last week. Though it isn’t for the new framework, the principle can be used for that framework. Maybe someday styling could be too. Today, I’m posting about using Flex styling without the Flex framework. I’ve taken the same example that Ryan posted and embellished. The components in there are Explanation of what is styled after the example.

Here’s the new MinimalComps.mxml source:

And the styles.css source:

The example looks very similar to Ryan’s, but notice differences including:

  • the PushButton label is set from the stylesheet
  • x, y, and spacing are no longer in the MXML on the VBox, they are only in the stylesheet
  • Descendent selectors work
  • #id can match the name property of DisplayObject
  • There is no styling code built into the components. This styling is not intrusive and can work with any display objects.
  • If you were to extend the IStylable interface provided, then you could also match against .stylenames and :pseudo selectors for state.

Pros and Cons

In order to accomplish this, I had to provide the* classes that a stylesheet expects to be there when it is loaded. That means you cannot use this approach along with Flex, only in place of Flex. We could get it to work in a sub-applicationDomain, but that is more work and this is only a proof-of-concept.

This may actually be considered more of a IoC framework than styling. We do not have getStyle/setStyle on the components and anything (any public property that is) can be set from the stylesheet, not just stylable properties. That may be considered a con to styling purists, or a pro to those who have wanted to set whatever they want.

View or Download the source code.

Update: Oh, I forgot a couple pros and cons.
Pro: Using Flex styling for non-flex projects allows you to embed assets and class references into the stylesheet. Something you can’t do with traditional text-only styling. It allows a stylesheet full of skin classes to be overridden with another stylesheet full of skin classes for theming.
Con: It only supports CSS up to what Flex 4 does. That means only descendent selectors, no child selectors, sibling selectors, attribute selectors, etc. because MXMLC just ignores those rules it doesn’t understand.

Next Page »