R – Binding a Flex component to a class function

actionscriptapache-flexflex3

I have several components where I want to enable buttons based on passing a username to a function. I want to dynamically bind the "enabled" property on a button so that if the "somethingChanged" event fires, a button may become enabled or disabled.

But, I'm not sure where to fire the "somethingChanged" event. It's possible that I may need to fire the "somethingChanged" event from several places in the application. Is this possible with a bound static function?

Am I going about this the right way or is there a better solution?

EventManager.as

public class EventManager():void
{
    [Bindable(event="somethingChanged")]
    public static function hasAccess(myVal:String):Boolean
    {
    }
}

testform1.mxml

<s:Button id="testButton1" enabled="{EventFunction.hasAccess("john")}" />
<s:Button id="testButton2" enabled="{EventFunction.hasAccess("mary")}" />
<s:Button id="testButton3" enabled="{EventFunction.hasAccess("beth")}" />

testform2.mxml

<s:Button id="testButton4" enabled="{EventFunction.hasAccess("tom")}" />
<s:Button id="testButton5" enabled="{EventFunction.hasAccess("bill")}" />
<s:Button id="testButton6" enabled="{EventFunction.hasAccess("jerry")}" />

Best Answer

Something like this would work.

package
{
    import flash.events.Event;
    import flash.events.EventDispatcher;

    public class EventManager extends EventDispatcher
    {
        [Bindable(event="somethingChanged")]
        public var hasAccess:Boolean = true;

        public static var instance:EventManager = new EventManager();

        public static function setHasAccess(hasAccess:Boolean):void
        {
            instance.hasAccess = hasAccess;
            instance.dispatchEvent(new Event("somethingChanged"));
        }
    }
}

Which would be used like so:

<?xml version='1.0' encoding='UTF-8'?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark"
        xmlns:mx="library://ns.adobe.com/flex/halo">

    <fx:Script>
        <![CDATA[

            protected function button1_clickHandler(event:MouseEvent):void
            {
                EventManager.setHasAccess( false );
            }

        ]]>
    </fx:Script>

    <mx:Button click="button1_clickHandler(event)" enabled="{EventManager.instance.hasAccess}"/>
</s:Application>

I don't know that this approach is a good one. This type of functionality would probably be better served inside a proper MVC structure. This is essentially creating a singleton. To implement it as you describe, you'd probably want some sort of instance per user I suppose. You aren't going to be able to bind to a static function though.