Read-only bindable getter


Matt - Posted on 28 August 2008

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.

"...but quite often you don't want to give the developer write-access to your properties..."

Well, another way is to simply make your setter "private," not cool maybe, but...

private var _currentPrice:Number = 0;
 
[Bindable]
public function get currentPrice():Number
{ return _currentPrice; }
private function set currentPrice( value:Number ):void
{ _currentPrice = value; }
 
public function doSomething( price:Number ):void {
    currentPrice = price;  // ...use 'private' setter to invoke binding event.
}

Greg

Hi Greg,

Thanks for pointing that out, that's another good way of achieving this but without the hassle of manually firing events.

About the author

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