setter


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.