Zachary Vance
Zachary Vance

Reputation: 892

Dependencies in data binding

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.

Upvotes: 0

Views: 140

Answers (3)

Ryan Frishberg
Ryan Frishberg

Reputation: 86

I felt like this was a common problem, so I wrote some code to help out with it. You can add what your getter is dependent on in the Bindable metadata. So:

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

It's custom code, written to use Parsley's metadata processing, but you could use it without Parsley--it just would be a normal method call and wouldn't look as nice.

Check it out: http://frishy.blogspot.com/2011/06/binding-dependencies.html

-Ryan

Upvotes: 0

sharvey
sharvey

Reputation: 8165

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.

Upvotes: 1

JeffryHouser
JeffryHouser

Reputation: 39408

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.

Upvotes: 2

Related Questions