Making a read only property bindable in Flex

I had a request from someone about binding a control to the flash.util.Timer’s running property. They wanted a control to enable/disable each time the Timer started or stopped. Initially it sounded very simple, extend the Timer class and mark the running property as bindable. Not so fast though, the running property is read-only. If you mark a read-only property in AS3 as bindable you get a compile warning,

[Bindable] on read-only getter is unnecessary and will be ignored.

Ok, no worries, add an equivalent setter for the getter and then everything should be a go. Nope, in the Timer class there is no public or protected method for setting the running property.

I vaguely remembered a presentation from a conference where they were attempting to optimize Flex performance in an application with a lot of databinding. They defined custom events to notify the compiler what to dispatch when a value had changed for data binding.

After a little digging I found an excellent post by Josh Tynjala that outlined exactly what I wanted to do. By defining a custom event in the [Bindable] tag you can dictate where and when to dispatch an event to make the data binding for a specific property update. In the case of the Timer class I added this bindable tag [Bindable("timerChange")] above the running getter method.

Here is what the new Timer class looks like to make the running property bindable. Since the property changes on starts/stops I override those two methods and add a line to dispatch the new timerChange event. Works like a charm.

 

package com.dgrigg.utils
{
import flash.events.Event;
import flash.utils.Timer;

public class BindableTimer extends Timer
{

public function BindableTimer(delay:Number, repeatCount:int=0)
{
super(delay, repeatCount);
}

[Bindable(event="timerChange")]
override public function get running():Boolean
{
return super.running;
}

override public function stop():void
{
super.stop();
dispatchEvent(new Event("timerChange"));
}

override public function start():void
{
super.start();
dispatchEvent(new Event("timerChange"));
}
}
}

 

Leave a comment

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Copyright © 2014 DGrigg Development Inc.