Tuesday, November 6, 2007

adding a symbol dynamically from the library

how to add a symbol from the library?
in AS2,
this.attachMovie("square", "square", 1);

and in AS3,
var square1:square=new square();

but how do you add a symbol dynamically from the library? say if you have a shape stored in a variable:

var shape:String = "square";

and you want to add the symbol in the library with this name.
in AS2, simple! you could have written:
this.attachMovie(shape, shape, 1);

however the AS3 syntax doesn't obviously allow for dynamic references. so how is it done? (credit to kglad for assisting in this discovery)

getDefinitionByName is what you need to extract the class from the library like so:

import flash.utils.getDefinitionByName;

var classRef:Class = getDefinitionByName(shape) as Class;

var square1:* = new classRef();

Frustrating Flex problems solved #2 - addChild

This blog has moved.

this.addChild(new Sprite())

looks simple enough doesn't it? especially if you've been working solely in Flash AS3. But if you try this line within a Flex component, you'll receive the error: 'Type Coercion failed: cannot convert flash.display::Sprite@86cc0e1 to mx.core.IUIComponent.'

This is because Flex components implement a different addChild method. although addChild is described as accepting a DisplayObject as a parameter, this DisplayObject must implement the IUIComponent interface.
How to add a sprite then? You can either:
specify a UIComponent. eg:
this.addChild(new UIComponent())
This sort of works in this case as UIComponent implements the Sprite. However the additional implementation of UIComponent may at best be unnecessary and at worst cause problems with your code. Also, this alternative won't work in some cases, say if for some reason you wanted to add a MovieClip.

so an alternative is that you can add your child to the component's rawChildren, a property which contains a list of ALL of the container's children - not just the children that the container wants you to know about! (this.numChildren<=this.rawChildren.numChildren) see flex help for more info on this. this alternative looks like:
this.rawChildren.addChild(new Sprite())