28 Aug in binding, flex

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.

Comments

Perhaps another approach...

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

Hi Greg,

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

All content © 2009-2011 Matthew Butt. All views expressed herein are my own and do not represent the views of my employer, AREA203 Digital.