Recently, I was caught by a special characters vs. html entities issue in Flex 4. For reference, you can read more about special characters in the text
property of a text component in the official docs. And also here on Flex Examples. Unfortunately, neither of these was exactly what I was looking for.
The Problem
I had an array of names in ActionScript that potentially contained special characters, and I wanted to output them in a spark List
component. Nothing magical required, just get them on the screen.
Solution #1
One option, which I’ve NEVER seen in anyone’s code ever, is to move the definition of the array into its own Script
tag without the CDATA
block. For example:
<fx:Script> [Bindable] private var nuggets:Array = [ 'Carmelo Anthony', 'Chauncey Billups', 'Nenê', 'Kenyon Martin']; </fx:Script>
Now, it doesn’t matter if we use single quotes ('
) or double quotes ("
), because outside of the CDATA
block all numeric html entities are processed. The fact that Flash Builder 4 automatically inserts the CDATA
block when you open a Script
tag probably means that almost no one has ever even heard of this possible solution. It’s so weird, I can’t recommend this solution.
Digging Deeper: The official docs will tell you that only a few named html entities work (
<
,>
,&
,"
,'
), and after that you must use numeric html entities (&#NNN;
).
Solution #2
Another option, that I actually thought of first, is to process the numeric html entities via a regular expression to output the correct special character. For example:
private function makeSpecialChars(item:Object):String { return item.toString().replace(/&#\d+;/g, replaceFunc); } private function replaceFunc():String { var s:String = arguments[0]; s = s.substring(2, s.length - 1); s = String.fromCharCode(parseInt(s)); return s; }
We use a simple regular expression to match any numeric html entity, and then call a replacement function to do the work of converting the entity into a special character. The static method String.fromCharCode
does the actual conversion.
Putting the converter code together with a List
‘s labelFunction
property and we get this:
<fx:Script> <![CDATA[ [Bindable] private var nuggets2:Array = [ 'Carmelo Anthony', 'Chauncey Billups', 'Nenê', 'Kenyon Martin']; private function makeSpecialChars(item:Object):String { ...same as above... } ]]> </fx:Script> <s:List dataProvider="{new ArrayList(nuggets2)}" labelFunction="makeSpecialChars" />
For each element in the array, the labelFunction
gets called and any numeric html entity is converted into the corresponding special character. No magic.
The Result
Here is the final result with both Solution #1 and Solution #2 together (view source enabled):
If you view the source, you can see that I’m using two separate Script
tags, one with a CDATA
block and one without. Who does that?
Files
Comments are closed