views:

20

answers:

2

I'd like to add a derived property to flex:

 private var a:int;
 private var b:int;
 [Bindable]
 public function get derived():int
 {
     return a+b;
 }

However, derived won't update when I change a or b. Is there a better (faster) way to make derived update than giving a and b setter methods which invalidate it?

Edit: added keyword "get". This makes more sense now, I hope.

+1  A: 

Your code does not create a property, it creates a method. Methods cannot be Bindable, only properties. This approach should work for you:

 private var _a:int;
 public function get a():int{
 return _a
 }
 public function set a(value:int):void{
   _a = a; 
   dispatchEvent(new Event('derivedChanged'));
 }
 private var _b:int;
 public function get b():int{
 return _b
 }
 public function set b(value:int):void{
   _b = b; 
   dispatchEvent(new Event('derivedChanged'));
 }

 [Bindable(event="derivedChanged")]
 public function get derived():int
 {
     return a+b;
 }

I wrote code n the browser; so there may be minor syntax errors.

www.Flextras.com
Right, this is exactly my current code. I wanted to know if I can avoid adding get and set methods for a and b.
Zachary Vance
That is not the code you posted. ;) To trigger binding on a read only property something has to dispatch the binding event. It doesn't have to be the set methods for a and b, but that is the most logical place.
www.Flextras.com
A: 

You can use [Bindable(event="propertyChanged")] on your derived function.

You should also make your derived function a getter.

I should work because flex uses PropertyChangeEvent.PROPERTY_CHANGE to bind variables, by automatically creating getters and setters and dispatching a PropertyChangeEvent. The modification of either a or b will automatically invalidate the result of derived.

sharvey