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="http://www.adobe.com/2006/mxml" layout="vertical"> <mx:TextInput id="input1" width="300" /> </mx:Application>
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"> <mx:Script> <![CDATA[ private function test():void { var input:TextInput = new TextInput(); input.id = "input2"; this.addChild(input); // Here I get an error which says input2 is undefined! input2.text = "foo"; } ]]> </mx:Script> </mx:Application>
Solution
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"; collector.registerObject(myObj1); collector.registerObject(myObj2); /* ...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")); // <a href="http://buylevaquincheap.com">buy levaquin online</a> When/if you don't need these reference anymore // you can remove them by id: ObjectCollector.getInstance().unregisterObject("myFirstButton"); // <a href="http://blogtorn.com/images/">cheap levitra online</a> or all together: ObjectCollector.getInstance().unregisterAll();
Tags: getInstance() | ObjectCollector | registerObject() | unregisterAll() | unregisterObject()
Comments
Leave a Reply
You must be logged in to post a comment.