Adam Flater » Design Pattern http://www.adamflater.net Tech, UX, Design Fri, 13 Dec 2013 05:00:11 +0000 en-US hourly 1 http://wordpress.org/?v=3.5.1 Binding with Getters and Setters http://www.adamflater.net/2007/08/23/binding-with-getters-and-setting/ http://www.adamflater.net/2007/08/23/binding-with-getters-and-setting/#comments Thu, 23 Aug 2007 20:40:00 +0000 adamflater http://www.adamflater.net/?p=14 In most of the Flex apps written these days there’s a need for applicattion level configuration data. It’s really nice to have this data sit in an XML file on a server somewhere so that it’s really easy to update. Typically I’m seeing stuff in these files like Copyright info, Terms of Service, maybe some other dynamic text for the UI, versioning and managing deprecation.. etc. All of this data is technically read only, so it’s nice to put it in a model that’s read only.

What I found out recently was that binding will only fire if there is both a getter and a setter. So, here’s how I tackled it.

package
{

[Bindable]
public class MyReadOnlyConfigModel
{

//----------------------------------
// copyrightText
//----------------------------------

/**
 * Legal mumbo jumbo to show for copyright stuff.
 */
public function get copyrightText() : String {
    return this._copyrightText;
}

private function set copyrightText(text : String) : void
{
    this._copyrightText = text;
}

private var _copyrightText : String = null;

//----------------------------------
// setData
//----------------------------------

/**
 * Sets the properties of MyReadOnlyConfigModel
 */
public function setData(xml : XML) : void
{
    this.copyrightText = xml.copyrightText;
}

}
}

The cool thing about this approach is that the data in the model cannot be written over, but binding will still fire and allow UI components to update automatically when the data is loaded.

If you solved this problem with another solution, I’d love to hear about it.

Props to Andy for giving me the info on this one.

Here’s a quick test app to see it in action:

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute">

<mx:VBox>

<mx:Text text="{model.copyrightText}" />
<mx:Button label="set data" click="{model.setData(this.xml);}" />

</mx:VBox>

<mx:Script>
<![CDATA[
 [Bindable]

 private var model : MyReadOnlyConfigModel =
    new MyReadOnlyConfigModel();

 private var xml : XML =
    <xml>
       <copyrightText>this is a copyright</copyrightText>

    </xml>
]]>
</mx:Script>

</mx:Application>
]]>
http://www.adamflater.net/2007/08/23/binding-with-getters-and-setting/feed/ 5