Reintroducing – Flight Stealth!

Flight Stealth was a Flash component framework a year ago. It went away as the creators of Stealth and OpenFlux combined to create Reflex last year. But Stealth is back! Reflex is forked.

There has been some disappointment that Reflex has forked. Many people have ignorantly but understandably attributed the split to Tyler, the project lead over Flight Stealth. However, Ben Stucki was the one who wanted to fork. After deciding to fork and leave Reflex he asked Tyler if he could keep the Reflex name. Tyler graciously consented, deciding to use the old Stealth name, but since the only difference in a new fork is the projects’ names, he’s gotten the short end of the stick, losing mind share, and for those who were against the fork, getting the blame.

I believe both projects will move forward as a result of this fork. Their project leads each have a vision and direction in mind, and I’m seeing the difference in goals will lead to different products and needs addressed by the projects. Although as Flash developers who currently only have one robust component set in our tool belts, it is hard to imagine the need for more than one alternative. However I believe we will find that one-size-fits-all is not an ideal goal and a specialized framework will always win out over a generic one in its own problem domain.

Good luck to both projects and make us proud.

As an aside, I designed the flightxd.com website where Flight Stealth will be hosted. I am quite proud of what I did, not being a designer.

Please join the Stealth mailing list and find out how you can help. We have a website to put together, user docs that need to be written, components that need to be written, and much much more.

How To Build a Behavior in Reflex

Update: If you don’t know what Reflex is, I’ve just introduced Reflex.

Building a component in Reflex consists of 3 things: making the component class, building the behaviors, and creating the skin. The component class is an extension of Component with your new component’s name and a few public properties that you feel might be important to that type of component. The real logic of the component goes into its behaviors, so that is where we are starting today.

What is a Behavior?

A behavior is a well defined piece of functionality that may be used by one or more components. Behaviors do not necessarily map directly to a component type. Sometimes they are planned and sometimes they are refactored into separate pieces for reuse. For example, in Reflex the ScrollBar uses a ScrollBehavior and a StepBehavior. Because the scroll bar’s data is similar to a numeric stepper, and because the buttons on a numeric stepper and a scroll bar have the same behavior, ScrollBehavior was broken down into a ScrollBehavior which handles track clicking and dragging the thumb, and a StepBehavior which handles clicking the up/down buttons.

Behaviors are made up of a target, data, skin parts, and event listeners. The target is defined on the base Behavior class and will get set automatically. The data is any properties that a behavior needs in order to function. It maps to the properties on the component that relate to this particular behavior and are bound to the target’s equivalent data. And listeners are set up to respond to the events on the component and parts of the skin. Behaviors make heavy use of data binding to wire everything together, reducing complexity and wiring code. This is one reason why optimizing data binding has been such a big focus for us.

Note that Reflex does not follow a purist MVC approach. Behaviors consist of the controller (“C” in MVC) functionality as well as duplicating the model (“M” in MVC) data. This allows our pieces to work independently with the added benefit of allowing simple Sprite’s and MovieClip’s to become components by virtue of the behaviors that target them. They don’t need to be a scroll bar in order to work like one.

Building a Behavior

We will use an example to build our behavior. Let’s say we have a button component, and we want it to vibrate when you click on it when it is disabled. Sort of a “no no, don’t do that” thing. Guess what, we don’t need to extend Button or even ButtonBehavior to do this. Avoid extending old functionality when adding new functionality. In fact, avoid extending as much as possible in Reflex except for the base classes. We want to stay away from inheritance trees.

First we create our DisabledBuzzBehavior class, extending Behavior to give us our target property and a couple of unnecessary but nice helper methods.

Then we want to add our data. The only thing we need to know about is whether the button is enabled or disabled. We don’t care what the label is or whether the button is selected (like checkbox or radio button). So at the top of the class add a bindable disabled property.

public class DisabledBuzzBehavior extends Behavior
{
	[Bindable]
	public var disabled:Boolean;

	public function DisabledBuzzBehavior(target:InteractiveObject=null)
	{
		super(target);
	}
}

We want our disabled property to always be the same as the component’s (or target’s) disabled property, so we will start setting up our bindings. We can do this in the constructor and use the little helper methods.

public function DisabledBuzzBehavior(target:InteractiveObject=null)
{
	super(target);
	bindProperty("disabled", "target.disabled");
}

Next we want to know whenever the component is clicked. We could override the target setter to add and remove listeners whenever it is set or unset, but we have binding methods for that too which is better.

public function DisabledBuzzBehavior(target:InteractiveObject=null)
{
	super(target);
	bindProperty("disabled", "target.disabled");
	bindEventListener(MouseEvent.CLICK, onClick, "target");
}

private function onClick(event:MouseEvent):void
{
}

Note that in Reflex we don’t worry so much about making everything “protected” because instead of subclassing everything you can simply replace it with your own version. Logic is broken up enough that you don’t have to make everything protected unless you know someone will want to subclass your behavior.

Now all we have to do is add the logic to our onClick method. This is stuff that isn’t Reflex specific and you will be determining on your own for your behaviors.

private var count:int;
private var originalX:Number;
private var intensity:Number = 4;

private function onClick(event:MouseEvent):void
{
	if (!disabled) return; // only react if we're disabled

	count = 0;
	originalX = target.x; // assuming if we got a click that target isn't null
	target.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}

private function onEnterFrame(event:Event):void
{
	if (target == null) {
		// the behavior was removed in the middle of it's thing
		event.target.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
	} else if (count >= 12) {
		target.x = originalX;
		target.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
	} else if (count++ % 2) {
		target.x = originalX + intensity;
	} else {
		target.x = originalX - intensity;
	}
}

You can see that we may need to store additional information other than the component data in order to get our job done. But this doesn’t need to be public API or bindable. You can also see that I’m trying to account for any situations that might break the code to make my behavior as solid as possible (e.g. checking to see if target is still set on each enter frame).

The whole behavior looks like this:

public class DisabledBuzzBehavior extends Behavior
{
	[Bindable]
	public var disabled:Boolean;

	private var count:int;
	private var originalX:Number;
	private var intensity:Number = 4;

	public function DisabledBuzzBehavior(target:InteractiveObject=null)
	{
		super(target);
		bindProperty("disabled", "target.disabled");
		bindEventListener(MouseEvent.CLICK, onClick, "target");
	}

	private function onClick(event:MouseEvent):void
	{
		if (!disabled) return; // only react if we're disabled

		count = 0;
		originalX = target.x; // assuming if we got a click that target isn't null
		target.addEventListener(Event.ENTER_FRAME, onEnterFrame);
	}

	private function onEnterFrame(event:Event):void
	{
		if (target == null) {
			// the behavior was removed in the middle of it's thing
			event.target.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		} else if (count >= 12) {
			target.x = originalX;
			target.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		} else if (count++ % 2) {
			target.x = originalX + intensity;
		} else {
			target.x = originalX - intensity;
		}
	}
}

Update: The following is how you would do the same with metadata.

public class DisabledBuzzBehavior extends Behavior
{
	[Bindable]
	[Binding(target="target.disabled")]
	public var disabled:Boolean;

	private var count:int;
	private var originalX:Number;
	private var intensity:Number = 4;

	[EventListener(type="click", target="target")]
	public function onClick(event:MouseEvent):void
	{
		if (!disabled) return; // only react if we're disabled

		count = 0;
		originalX = target.x; // assuming if we got a click that target isn't null
		target.addEventListener(Event.ENTER_FRAME, onEnterFrame);
	}

	private function onEnterFrame(event:Event):void
	{
		if (target == null) {
			// the behavior was removed in the middle of it's thing
			event.target.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		} else if (count >= 12) {
			target.x = originalX;
			target.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		} else if (count++ % 2) {
			target.x = originalX + intensity;
		} else {
			target.x = originalX - intensity;
		}
	}
}

and can be added at runtime to a certain button or to all buttons by adding it to the stylesheet.

<rx:Button>
	<rx:behaviors>
		<rx:ButtonBehavior/>
		<behaviors:DisabledBuzzBehavior/>
	</rx:behaviors>
</rx:Button>

or

Button behaviors {
	button: ClassReference("reflex.skins.ButtonBehavior");
	disabledBuzz: ClassReference("my.behaviors.DisabledBuzzBehavior");
}

More about the weird CSS in a later post. And the skin parts hookup is still under review, so I didn’t include an example with that workflow yet until we have it solidified.

So now you can start building out behaviors without any skins or components. You have everything you need right inside a behavior.

Reflex Demos

At 360|Flex we showed some pretty cool demos. The coolest one Tyler made and is on his blog, so go check out the Phases of the Moon there. Here are some you can right-click to view the source.

We have some examples of how skins and behaviors can be swapped out:

And a demonstration of how behaviors can work with any Flash display objects (including Flex ones in this case):

Enjoy!

Update: Oh, and here are the slides.

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.

Changes

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.

API

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 \\ http://lipitoronline-generic.net/ \\ 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. http://viagracanadian-online.com/. canadian pharmacy tampa. http://pharmacyincanada-onlineon.com/. http://viagracanadian-online.com/

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.

Downloads

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 http://viagrabuy-online24.com/ 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.

PropertyObserverable

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

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 { this.target = 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).