Posts Tagged ‘mxml’

Flex and logical AND (&&) operator usage inside mxml code

// August 29th, 2007 // 2 Comments » // Tips & Tricks

While developing Flex applications you may need to use logical AND operator (&&) inside mxml code, as in the following code example:

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
  xmlns:mx="http://www.adobe.com/2006/mxml"
  layout="vertical">
    <mx:CheckBox label="Check me" id="cb1" click="{}" />
    <mx:CheckBox label="Check me" id="cb2" click="{}"/>
    <mx:Button label="Now you can click me" id="bt1"
      enabled="{cb1.selected && cb2.selected}" />
</mx:Application>

Actually the Flex compiler won’t compile this code blaming that the entity name must immediately follow the ‘&’ in the entity reference that is trying to interpret the first & as the starting name of an entity.

You can find a couple of solutions here. The one I prefer consists of replacing the & character into its equivalent html entity & but you can also implement the solution below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
  xmlns:mx="http://www.adobe.com/2006/mxml"
  layout="vertical">
    <mx:Script>
    <![CDATA[
      private function and(p1:Boolean, p2:Boolean):Boolean {
        return p1 && p2;
      }
    ]]>
    </mx:Script>
    <mx:CheckBox label="Check me" id="cb1" click="{}" />
    <mx:CheckBox label="Check me" id="cb2" click="{}"/>
    <mx:Button label="Now you can click me" id="bt1"
      enabled="{and(cb1.selected, cb2.selected)}" />
</mx:Application>