Search Flex Samples

Multi-line strings in Actionscript 3





Posted by: Doug, in Actionscript

Jesus, this took me a bazillion hours to figure out.


OK, so I wanted to set a String variable in Actionscript. The actual value I wanted was a block of Javascript code (more on why in a second). In PHP we're allowed to use something called heredoc syntax. So I could write my code like this:


$str = <<<EOD

Example of string

spanning multiple lines

using heredoc syntax.

EOD;


and then my variable would contain the multi-line string with line breaks and all. Sweet, that's what I wanted to do. Turns out AS3 doesn't support heredoc syntax. So that sucks.


I spent the next few hours banging my head on a wall trying to figure out how to cut and paste my long block of code that I wanted to get into a String to work correctly in my AS code. Googling “actionscript heredoc” gave me nothing. Googling “actionscript multi-line string” gave me nothing. The golden nugget was finally realizing that AS3 is basically Javascript 2, so maybe some JS guys had figured this one out. Turns out they did. Here's the JS nugget that led me to my solution.


You can use the same method in Actionscript 3. So your AS code would look like:


private var myString:String = ( <![CDATA[ Here is my string that spans multiple lines. ]]> ).toString();

It's easier in MXML, in that case all you need to do is something like:


<mx:String id="myString"> <![CDATA[ Here is my string that spans multiple lines. ]]> </mx:String>

So that's how you simulate the heredoc syntax in AS3.


And a quick note: when I was trying to figure this out I was making a class that injected Javascript code into the HTML wrapper for a component to execute. See Abdul Qabiz's post here for a description of this method and a utility class to help you do this. Basically this let me write a component that used both Actionscript and Javascript and I could keep all my AS code and my JS code within the Actionscript component (as opposed to putting in the HTML wrapper). That's pretty frickin cool.


Delicious.BlogBadge.writeBadge('delicious-blogbadge-post-'+Math.random(), 'http://dougmccune.com/blog/2007/05/15/multi-line-strings-in-actionscript-3/', 'Multi-line strings in Actionscript 3', {}, 'delicious-blogbadge-line');

0 comments:

Related Flex Samples

Learn Flex: Flex Samples | Flex Video Tutorials Flex Examples