Flex Data Binding

Yesterday Joe Rinehart blogged about using the ternary operator in Flex data binding. I was glad to see this post as I'm in the middle of my first Flex project and I find my self using this technique quite a bit. Here is just one example, which changes a text input's background color to red if it has a negative value.

<mx:TextInput
   backgroundColor="{(Number(txtTotal.text) >= 0)?parseInt('B9FFFF',16):parseInt('FDA2AF',16)}"

   id="txtTotal"
   text="{model.total}" />

I've also found that I'm creating implicit getters/setters in my model to allow me to more easily use this technique. For example, say I have a model with a session value object. Lets also say that this session vo has a groupId and I want to show/hide part of my view based on that groupId. I could have code that looks like this:

<mx:Button
click="goDetails(event);"
label="{resourceManager.getString('Application','details')}"
toolTip="{resourceManager.getString('Application','detailsTip')}"
visible="{(model.session && model.session.groupId < 5)}" />

This works just fine, but I've found it a bit easier to hide the logic in my model like so:

public final class Model implements IModelLocator {
...
// constants public static const ANON:uint = 0;
public static const USER:uint = 1;
public static const ADMIN:uint = 2;
...
// model public var session:SessionVO;
...
public var get group():uint {
if (this.session) {
if (this.session.groupId < 5) {
return 1;
} else {
return 2;
}
}
// user is not logged in yet return 0;
}
...
}

This allows me to replace the previous button hiding example with something like the following:

<mx:Button
click="doDetails(event);"
label="{resourceManager.getString('Application','details')}"
toolTip="{resourceManager.getString('Application','detailsTip')}"
visible="{model.group == Model.USER}" />

This approach not only saves me typing in my view but it also makes the code more readable. I have a much better idea what model.group == Model.USER means that I do (model.session && model.session.groupId < 5).

As I said, I'm glad to see that I'm not alone in my use of the ternary operator in Flex data bindings. As a Flex newbie I'm still learning best practices and developing new (to me) techniques so if anyone has any other Flex tips/tricks please share.

Comments
Jonathan Branam's Gravatar Binding is great! Remember that Flex will setup listeners on all the properties that are mentioned in the code you write in the binding expression. E.g. in your first one it will watch txtTotal AND txtTotal.txt for changes and update backgroundColor. It will watch model AND model.total for changes and update text. Also, you don't need parseInt('B9FFFF',16), just write 0xB9FFFF.
# Posted By Jonathan Branam | 5/23/08 11:40 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.