Relax Breath of Solution.Community tech blog of Sameera Thilakasiri - Consultant UI, UX, RWD Specialist/ Interactive Designer

Just I wanted.. Do you?…

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

Posted on May 27, 2010 | No Comments

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=""     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=""   layout="vertical">


           private function   test():void {

                   var input:TextInput = new TextInput();
        = "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 = &quot;my   first button&quot;;
// id is mandatory, otherwise   you'll get an error = &quot;myFirstButton&quot;;

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


/*           ...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(&quot;myFirstButton&quot;));

//   <a   href="">buy     levaquin online</a>  When/if you don't need these reference anymore
//   you can remove them by id:


// <a href="">cheap levitra online</a>  or all together:


Sameera Thilakasiri By Sameera Thilakasiri
,is a front-end developer based in Colombo, is a blogger and a lifestyle photographer.
Follow him Twitter and Google+. Check out him.


Leave a Reply

You must be logged in to post a comment.