PDA

View Full Version : Paramaterizing the Name of a Class


antun
12-24-2003, 01:45 PM
If you've ever wondered how you would instantiate a class at run-time, when you had its name parameterized, here's how:


<canvas>
<class name="default_box" width="10" height="10" bgcolor="green"/>

<class name="blue_box" width="10" height="10" bgcolor="blue"/>

<class name="newthing">
<attribute name="newclass" value="default_box" type="string"/>

<button onclick="new global[parent.newclass](this.parent);"
text="${'new ' + parent.newclass}"/>
<simplelayout spacing="10"/>
</class>

<simplelayout spacing="20" axis="x"/>

<newthing/>
<newthing newclass="blue_box"/>
</canvas>


The class name gets passed to the instance of newthing as a string. The global[] array contains this class, also indexed by string. Therefore global[parent.newclass] resolves to the class definition.

Enjoy!