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).