Binding a Flex Component to a Class Function
I have several components where I want to include buttons based on passing the username to a function. I want to dynamically bind an "on" property to a button so that when the "somethingChanged" event occurs, the button can be enabled or disabled.
But I'm not sure where to fire the "somethingChanged" event. I may need to fire the "somethingChanged" event from multiple places in the application. Is this possible with a bound static function?
Am I following this correct path 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")}" />
source to share
Something like this will 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 will be used like this:
<?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 this approach is good. This type of functionality will probably be better served within a proper MVC framework. This essentially creates a singleton. To implement it as you describe, you probably need some sort of user instance. However, you won't be able to bind to a static function.
source to share