ObjectCollector: Accessing Flex’s objects by id (even dynamic generated) from anywhere

Ok, let me explain my last experiment…


Flex’s components have a nice id property which can be used to easily referencing object created.
All you know, that if I get the following mxml Application file:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

    <mx:TextInput id="input1" width="300" />


I can then create a Script block into which I’ll point to TextInput in this way:

input1.text = "text dynamically added :)";

Perfect, but how can I reference dynamically created objects (components outside Application)?

The simplest example I can do is the following:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">


            private function test():void {

                var input:TextInput = new TextInput();
                input.id = "input2";

                // Here I get an error which says input2 is undefined!
                input2.text = "foo";





Define a place where to store references to desired objects, which will be accessible through id from anywhere.
So, I created a singleton class called ObjectCollector which provides a simple, elegant and secure solution to the problem. You can use it in this way:

// From anywhere you first create and register objects:

var collector:ObjectCollector = ObjectCollector.getInstance();
var myObj1:Button = new Button();

myObj1.width = 300;
myObj1.label = "my first button";
// id is mandatory, otherwise you'll get an error
myObj1.id = "myFirstButton";

var myObj2:TextInput = new TextInput();
myObj2.text = "hello world";
// id is mandatory, otherwise you'll get an error
myObj2.id = "myTextField";


/* ...then in another (or the same) place you can
get references to your desired objects
(this time by specifying the id)
When you retrieve objects from the collector you should 
always cast (upcast!) them to the right type
(Because objects are collected as generic Object classes)

var btn:Button = Button(ObjectCollector.getInstance().getObject("myFirstButton"));

// When/if you don't need these reference anymore
// you can remove them by id:


// or all together:



You can download the class here


A brief documentation is available here

  • Ray

    this is great! love it!

  • Simple and effective, admirations … !!!

  • Help! i have problem. cus i have to make many textInput like this one:

    for(int i=0; 1<10; i++)
    var input:TextInput = new TextInput();
    input.id = "input" + i;

    // how to set value with each id. here i have 9 id's?

  • Thanks man… It worked ;)

  • eklypz

    Or use the “name” property instead, access the object anywhere within your comp with getChildByName.

  • AB

    Greaaat…. thanku :)

  • Amol


  • Albert Cullen

    This is actually awesome! And so useful!
    So many thanks !!
    Thank you for sharing, you have helped me a lot!!