Programming is a wonderful mix of art and science; source code is both a poem and a math problem. It should be as simple and elegant as it is functional and fast. This blog is about that (along with whatever else I feel like writing about).

Saturday, January 05, 2008

An Awesome Flex HTML Escaper

One of the problems I frequently come across when trying to post code online is that the characters need to be escaped. For example, when entering a bunch of MXML code, the browser vainly attempts to display the code in the mistaken belief that it's actually HTML.

So one of the simple applications I like to make in any new language is an HTML escaper. Since I'm playing with Flex right now, I figured I'd make one (and hopefully it'll be useful, since I'll be using it to post the code).

It took a couple of minutes, but here's the code:

<mx:Application xmlns:mx="" backgroundColor="#f6f6f6">

public function escapeHTML(str:String):String {
str = str.replace(/&/g, "&amp;");
str = str.replace(/</g, "&lt;");
str = str.replace(/>/g, "&gt;");
return str;

public function outputClickHandler(event:Event):void {


<mx:Label text="Original" fontSize="14" fontWeight="bold" />
<mx:TextArea id="input" width="800" height="200" />

<mx:Label text="Escaped" fontSize="14" fontWeight="bold" />
<mx:TextArea id="output" text="{escapeHTML(input.text)}" click="outputClickHandler(event)" width="800" height="200" />

The cool things about this little application are:
  • The data binding
    • Note that the second TextArea's text attribute is defined as text="{escapeHTML(input.text)}". What that means is that the two text fields are bound together, with the ActionScript function between them as a sort of filter. Any change you make in the first box will immediately show up in the second box.
  • The event handler
    • The second box has an event listener set inline by the click attribute. It calls the outputClickHandler() method, which simply sets the your clipboard to be the result of the escaping. That way you don't have to manually select everything when you're ready to copy the results.
While this is a really small, simple application, it demonstrates the power of Flex pretty well. The event model is nice, clean, and simple ... but the data binding is what gives you real power. It's the best kind of magic: the kind that you very explicitly tell it what you want, and raise you eyebrows in pleasant surprise when it works better than you could have imagined.

This is by far the best HTML escaper program I've written, and it's all thanks to Flex. Awesome.

(Feel free to use the HTML Escaper Application to your heart's content.)

No comments: