The 'id' property does magic at compile time. When you write
<mx:Button id="b"/>
the MXML compiler autogenerates a reference var inside the class
declaration for the component you're defining
public var b:Button;
(This var gets initialized by framework code based on the "component
descriptors" that were autogenerated to describe your MXML tags as
ActionScript data structures.)
These reference vars are what allow you to write code like
b.label = "OK";
in your component's <Script> or in any event handler attributes in the
tags in your component. In other words, they allow you to "access" that
Button instance no matter how deeply it might be nested inside a
container hierarchy inside your component.
Because the 'id' property works at compile time, it doesn't really
accomplish anything to set it at runtime. It's too late to create a
reference var in the class, because component classes are typically
non-dynamic and can't have properties or methods added to them at
runtime.
The 'name' property has no compile-time magic.
If you specify the 'id' property at compile time, the 'name' property
will get set to the id. Otherwise, the 'name' property will get set to
an autogenerated string which ensures that every component has a unique
name.
Some components also set the 'name' property on some of their internal
DisplayObject.
When you call toString() on a component -- and note that it gets called
implicitly when you coerce it to a String with code like
trace(myComponent) -- you get a String formed from the 'name' property
of the component and all of its ancestors. Some code in the framework
assumes that this string uniquely identifies the component.
So, in general...
1. There's no point in setting 'id' because it doesn't do anything
interesting at runtime.
2. You shouldn't set 'name' because the framework uses it for its own
purposes.
Most of the time when developers think they need to set either 'id' or
'name', they're going about something in the wrong way. In particular,
if you're creating component instances dynamically, you DON'T want to
set their 'id' or 'name'... you want to declare individual reference
vars (or an Array or Dictionary or whatever) to keep track of them, so
that you can access them with the same kind of code that you use to
access instances declared at compile time.
Gordon Smith
Adobe Flex SDK Team
________________________________
From: [email protected] [mailto:[EMAIL PROTECTED] On
Behalf Of hoytlee2000
Sent: Wednesday, April 23, 2008 12:12 AM
To: [email protected]
Subject: [flexcoders] what's the difference between the name prop. and
the id prop for a UI component?
When should I use one over the other? Are there any differences?
Can I set a dynamically created UIComponent's id with the id property
like this:
UIObject.id = "my_id";
and then call that component using the id?
Thanks,
Hoyt