Search code examples
apache-flexactionscript-3mxml

Watching a bindable property


In my flex app I have a public bindable property. I want it so that every time the value of that property changes, a function gets triggered. I tried using ChangeWatchers, but it seems those only apply to built-in components like a text box change. I would like to do that same behavior with a property that changes at runtime.


Solution

  • One option is to use BindingUtils.bindSetter (which incidentally returns a ChangeWatcher):

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="this_creationComplete()">
    
        <mx:Script>
            <![CDATA[
    
                import mx.binding.utils.BindingUtils;
                import mx.binding.utils.ChangeWatcher;
    
                [Bindable]
                public var myValue:int = 0;
    
                private function this_creationComplete():void
                {
                    var cw:ChangeWatcher = BindingUtils.bindSetter(myValueChanged, this, "myValue");
                }
    
                private function setValue():void
                {
                    myValue = getTimer();
                }
    
                private function myValueChanged(o:Object):void
                {
                    trace("myValue: " + myValue.toString());
    
                    // You can also use o.toString() -- the new value will be passed into the function
                }
    
            ]]>
        </mx:Script>
    
    
        <mx:Button label="Click Me" click="setValue()" />
    
    </mx:Application>
    

    Here, myValueChanged gets called whenever the myValue property changes. There are other ways, of course, but I often use this approach with good results. Hope it helps! Post back with questions and I'll keep an eye out.