Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.


AS3: E4X For Display Lists

Posted August 17, 2009 by senocular

Here's a little fun project I did to recreate E4X (ECMAScript for XML) in the context of display objects and display lists. Three classes are involved (technically 2 classes and 1 namespace); E4DisplayList, E4DisplayObject, and e4d_internal. E4DisplayList and E4DisplayObject mirror XMLList and XML respectively with the e4d_internal namespace providing a place where those objects' members are stored. Here's an example:
import com.senocular.display.E4DisplayObject;

var e4this:E4DisplayObject = new E4DisplayObject(this);

e4this.child = new MovieClip();
trace(this.getChildAt(0)); // [object MovieClip]
trace(this.getChildAt(0).name); // child

e4this.child = new MovieClip();
trace(e4this.child); // [object MovieClip], [object MovieClip]
trace(e4this.child.length()); // 2
trace(getQualifiedClassName(e4this.child)); // com.senocular.display::E4DisplayList

e4this.child.@x = 10;
trace(this.getChildAt(0).x); // 10
trace(this.getChildAt(1).x); // 10

Common XML methods such as attribute(), elements(), and descendants() are also supported (as is the descendants operator (..)), as well as a few other custom methods.

Though not used in this example, the namespace is necessary because member references from E4DisplayList and E4DisplayObject, as with XML/XMLList, are taken from the object(s) they contain. XML/XMLList get around this using methods for would-be properties, for example using the length() method instead of the length property. This works because XML contains only data and not methods. Display objects, however, may have their own methods, such as length(), so to prevent conflict, e4d_internal was used to store E4DisplayList and E4DisplayObject members. If, for example, the above instance had a length() method, the e4d_internal namespace would be used to access the length method of the E4DisplayObject instance rather than the object's own length();

import com.senocular.display.E4DisplayObject;
import com.senocular.display.e4d_internal;

var e4this:E4DisplayObject = new E4DisplayObject(this);

function length():String {
return "LEN";

trace(e4this.length()); // LEN
trace(e4this.e4d_internal::length()); // 1

A small example application with additional functionality and is included with the source files in the following download:

The class files can be viewed directly in the display folder of the ActionScript section of this site (files there will be more up to date than the download).