我想根据具有一个或多个参数的函数的返回值,在按钮上设置 启用 属性。我怎么能这样做?
private function isUserAllowed (userName:Boolean):Boolean {
if (userName == 'Tom')
return true;
if (userName == 'Bill')
return false;
}
<mx:Button label="Create PO" id="createPOButton"
enabled="<I want to call isUserAllowed ('Bill') or isUserAllowed ('Tom') here>"
click="createPOButton_Click()" />
答案 0 :(得分:10)
According to the Flex docs,只要该属性是可绑定的,您就可以这样做(我已经包含了两个额外的按钮来演示):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
[Bindable]
private var currentUser:String = "Bill";
private function isUserAllowed(user:String):Boolean
{
if (user == "Bill")
{
return true;
}
return false;
}
]]>
</mx:Script>
<mx:VBox>
<mx:Button label="My Button" enabled="{isUserAllowed(currentUser)}" />
<mx:HBox>
<mx:Button label="Try Tom" click="{currentUser = 'Tom'}" />
<mx:Button label="Try Bill" click="{currentUser = 'Bill'}" />
</mx:HBox>
</mx:VBox>
</mx:Application>
如果没有标记为[Bindable]的currentUser,它将无效。
另一种方法,如果你想更多地按字母顺序绑定到函数(这也在文档中表示),那就是让函数响应当前用户更改时发送的事件,如下所示: / p>
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="init()">
<mx:Script>
<![CDATA[
private var _currentUser:String = "Bill";
public function set currentUser(value:String):void
{
if (_currentUser != value)
{
_currentUser = value;
dispatchEvent(new Event("userChanged"));
}
}
[Bindable(event="userChanged")]
private function isUserEnabled():Boolean
{
if (_currentUser == "Bill")
{
return true;
}
return false;
}
]]>
</mx:Script>
<mx:VBox>
<mx:Button label="My Button" enabled="{isUserEnabled()}" />
<mx:HBox>
<mx:Button label="Try Tom" click="{currentUser = 'Tom'}" />
<mx:Button label="Try Bill" click="{currentUser = 'Bill'}" />
</mx:HBox>
</mx:VBox>
</mx:Application>
所以有两种方法。 IMO,第二个似乎更合适,但第一个肯定没有错。祝你好运!
答案 1 :(得分:7)
<mx:Button
enabled = "{this.myFunction(this.myVariable)}"
>
或内联:
<mx:Button
enabled = "{(function(arg:Object):Boolean{ ... })(this.myVariable)}"
>
答案 2 :(得分:2)
以下是我在类似情况下做过几次的事情:
<mx:Script>
<![CDATA[
[Bindable] var _username : String;
private function isUserAllowed (userName:Boolean):Boolean {
if (userName == 'Tom')
return true;
if (userName == 'Bill')
return false;
}
]]>
</mx:Script>
<mx:Button label="Create PO"
id="createPOButton"
enabled="{isUserAllowed(_username)}"
click="createPOButton_Click()" />
这样,当Bindable _username
发生变化时,它会触发更改通知。由于标签正在监听_username
更改(即使它只是另一个函数的参数),因此将重新评估enabled
属性。
答案 3 :(得分:0)
<mx:Script>
<![CDATA[
[Bindable]
private var userName : String = "Tom"; // or whatever ...
[Bindable]
private var userAllowed : Boolean;
private function isUserAllowed ():Boolean {
if (userName == 'Tom')
return false;
if (userName == 'Bill')
return false;
return false;
}
]]>
</mx:Script>
<mx:Button label="Create PO" id="createPOButton" enabled="{userAllowed}" addedToStage="isUserAllowed()"/>