Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

AS3: Using custom Metadata in Flex (part 1)

I'm sure that you've already used metadata tags in your flex applications. There are several reserved keywords like [Bindable], [Embed], [Event] and so on (the full list is available here). The function of the metadata tags is to provide additional information to the flex compiler. For example information about embeding assets, dispatching events. This article doesn't explain how to use the default flex tags (you can learn that from here). It shows you how to create your own metadata tags and how to use them.

First of all, to be able to use a custom tag you should inform the flex compiler about them. You can do that by adding a parameter to the additional compiler arguments like that:

-keep-as3-metadata+=NameOfTag1,NameOfTag2

Then you can write something like:

package {
  public class MyCustomClass {
    [NameOfTag1(myVar = "test")] public
    var name: String;
    public
    function MyCustomClass() {}
  }
}

To use your tag's data you have to use flash.utils.describeType method. It returns a xml with information about your class. For example:

package lib.document {
  import flash.utils.describeType;
  public class MyCustomClass {
    [MyCustomTag(myVar = "test")] public
    var name: String;
    public
    function MyCustomClass() {
      trace(describeType(MyCustomClass));
    }
  }
}

will return:

<type name="lib.document::MyCustomClass" base="Class" isDynamic="true" isFinal="true" isStatic="true">
  <extendsClass type="Class"/>
  <extendsClass type="Object"/>
  <accessor name="prototype" access="readonly" type="*" declaredBy="Class"/>
  <factory type="lib.document::MyCustomClass">
    <extendsClass type="Object"/>
    <variable name="name" type="String">
      <metadata name="MyCustomTag">
        <arg key="myVar" value="test"/>
      </metadata>
    </variable>
  </factory>
</type>

As you can see you have information about your metadata tag. You can use it to assign a value to your class's variable, to call a private method or something else.Check part two »

AS3: Using custom metadata in flex (part 2)

If you enjoy this post, share it on Twitter, Facebook or LinkedIn. To leave a comment go here.