vendredi 21 octobre 2011

Creating an object in actionscript

The creation of a visual component is an operation that requires many steps.
First, we start by constructing the component, either using the default constructor or any constructor you have defined on your own

var imDaButton:Button = new Button(); 

Now the component needs some properties, "hey, I'm like all the other buttons out there, give me some properties so that I feel a little bit different", said imDaButton
Here you go

imDaButton.label="warrior";

imDaButton.setStyle("cornerRadius", 2);

imDaButton.addEventListener(MouseEvent.CLICK, doStuff);



Ok, now our button is happy, it has some properties of its own. A label to be proud of, some weird corners, and it does stuff when it's clicked.

Once you've got your button all ready to hit the road, you can add it to a parent.


someParent.addChild(imDaButton); 

The method initialize() is called automatically when we call addChild(). This method is used to initialize the internal structure of the component.
It first dispatches a preinitialize event which could be used for example to load some external resources, like loading styles dynamically or loading resource bundles. Be careful when you use a listener for this event in your container and try to access children for the container. For example, if you have:


someParent.addEventListener(FlexEvent.PREINITIALIZE, parentPre); 


private function parentPre(event:FlexEvent):void

{
    imDaButton.enabled=false; 
}


In this case you'll have an error #1009 null has no properties since imDaButton wasn't created yet. So, when is it created?

That's simple, the method createChildren() is going to do that for you. That's where the component internal structure is created. It could be the class managing the button's label, which is UITextField in this case. This method can be overriden in custom components so that you create the children you want, and place them where you want once this method gets called


Now that your button was created, along with any other component in your container, the initialize event is dispatched, and you can now play with the children of your container using the listener to this event. 


After that, creationComplete event is dispatched to notify us that the children, and their children were created. Note that many other steps happen during the creation of the internal structure of a component: property processing, measuring, layout, and drawing.


Aucun commentaire:

Enregistrer un commentaire