FLEXYGEN

Adobe Flex and AIR development

Immutability and Binding

An application I am developing makes heavy use of date ranges. I created a a simple DateRange class containing start and end dates. Besides being stored in models, date ranges are used in events and passed around to controller and service methods. I didn’t like the idea of using a relatively heavyweight subclass of EventDispatcher for these purposes, so I chose not to make DateRange bindable. But I went a step further and made it an immutable class, with no setters. This won’t be everyone’s cup of tea, but is common in the Java world, where immutable objects can help out with thread-safety, obviously not an issue in Flex.

At first, I created a companion wrapper class BindableDateRange for use in models, but it became rather messy. In the course of re-factoring it away, I ran into the well-known warning:

warning: unable to bind to property ’start’ on class ‘DateRange’ (class is not an IEventDispatcher)

In one MXML component, I was binding to the start property:

<mx:DateField selectedDate=”{range.start}” change=”useDate(event)” />

But, but, but “range” is what changes! Why can’t I bind to “range.start”? Well, you can. Once I got rid of a few unrelated bugs, I was able to verify that the binding was working (i.e. the DateField updated when the range changed. To get rid of the warning, I had to create [Bindable] getters for “start” and “end” within the component itself, and replace the expression with {this.start}. Unfortunate, but there you have it.

Update: It appears that another way to get rid of the warning is to add [Bindable(event="startChanged"] to theĀ  getter for the “start” property, without necessarily deriving from EventDispatcher (which is unnecessary since events aren’t dispatched for this read-only property).

May 21, 2008 Posted by richard | Uncategorized | | No Comments Yet