Learning ActionScript 3.0: E4X Rules!
Like a lot of Flash developers who don’t always get to work on the big-budget projects, I’ve been pretty slow to get my feet wet in ActionScript 3.0–Flash’s newest supported scripting language. Over the last few weeks, I’ve been knee deep in Packages, new native types, display lists, and to my greatest enjoyment, the ActionScript implementation of E4X.
For those who don’t know, E4X stands for EcmaScript for XML. EcmaScript as I’m sure everyone reading this already knows, is a root language that both JavaScript and ActionScript are based on. Unlike C++ or Java, Ecmascript lets you do a lot of magic with data-typing, passing functions as data, and much, much more. XML is a set of rules that governs how to mark up data in a way that describes it.
Within the scope of this post though, XML is just a way to get data into a Flash movie (and often get it back out of the Movie as well). So, let’s look at a little snippet in AS2.0.
Let’s say this is our XML:
<book>
<chapter>Cotton Ball Joint Compound</chapter>
<chapter>Rust Protector of Liberty</chapter>
<chapter>Key Board of Trustees</chapter>
</book>
In ActionScript 2.0, if we wanted to access the name of the first chapter, we’d have to write some ActionScript like this:
//Assuming we already successfully loaded the XML var chapterName = xmlObj.firstChild.childNodes[0].firstChild.nodeValue;
While it get’s the job done, it’s certainly not the most efficient or the most intuitive bit of code.
Compare that with the AS3.0 E4X version though:
var chapterName = xmlObj.chapter[0];
Ahhh, now that is a beautiful thing, isn’t it? Not only do we get to use the XML node name as a variable-style accessor, we don’t have to fumble with all the firstChildren issues of yesteryore. E4X assumes for us that we’re after the nodeValue rather than the node itself.
Whoever concepted E4X is my personal hero of the day. Whoever decided to implement it as part of AS3.0 is my personal hero of tomorrow.
Now, back to O’Reilly and the world of Essential ActionScript 3.0. Stay tuned for more code snippety goodness!