binding


Read-only bindable getter

It's fairly easy to setup data binding with setters/getters, but quite often you don't want to give the developer write-access to your properties. Flex Builder will throw a warning if you don't have both a setter and a getter and you're specifying the property to be bindable.
The solution is to manually fire an event when the property changes. This event then causes Flex to fire the binding event that causes a property update.
private var _myProperty:String = "";
 
[Bindable (event="myPropertyChange")]
public function get myProperty():String {
return _myProperty;
}
 
public function doSomething() {
_myProperty = "New string";
dispatchEvent(new Event("myPropertyChange"));
}
Generally, doSomething() will get called from somewhere else in your code, and your view (or whatever) will bind to the read-only getter.

Data binding with setters/getters

There are a few gotchas when trying to get setters and getters to data bind. The first one has been covered elsewhere, basically it's essential that you have both set and get methods in order for Flex to bind to setter/getter changes.
The other is less documented. It's pretty obvious when you think about it but took me a while to figure out what was going on. Generaly, most setter/getter functions are public accessors to private variables, for example:
private _myString:String = "";
 
[Bindable]
public function get myString():string { return _myString; }
public function set myString(s:string):void { _myString = s; }
In my previous work with this structure, when I change the value from within the class itself, I always modify the private _myString variable directly rather than going via the setter function. This is slightly more efficient as less code is run, and in some circumstances I do not want the setter to run if it includes additional logic. However, this method will not fire the data binding event, you must call the setter explicitly, for example:
private function changeString():void {
_myString = "hello"; // This will NOT fire the event and data binding won't work
myString = "goodbye"; // This WILL fire the event and data binding will work as expected.
}
Hopefully this information may save someone a bit of time!!!

About the author

Matthew Butt is an experienced developer, software architect and development manager. For more information, review the About page.