»
S
I
D
E
B
A
R
«
AS3: The ‘as’ operator
12月 27th, 2008 by admin

One of my FYP partner (not in the same group but we sometime share what we learnt about FLEX) encountered a problem that caught my eyesight. She tried to receive a user input value and assign it to a component’s width attribute so as to resize that component. Her application save that value from a form in FLEX to database, and somehow the application need to retrieve that piece of data from the database to the application for rendering the layout of a component. The problem is that she can load that data value but the application does not change a particular component’s size.

For a certain moment, she and I know that the problem is occured due to the mis-match data type. The data retrieve from database is a “String” while the attribute’s data type is “Number”. Well she tried to use the AS3 new ‘as’ operator for achieving her goal: converting the string number value to number value. Sadly, it does not work. And I tried to use ’setStyle’ component’s operation to work it out but I found that setStyle does not work for all layout constraints.

With several trials, I fount that simply using Number() to convert ‘String’ to ‘Number’ type is able to achieve the purpose. This raise my attendtion on how the new  AS3 ‘as’ operator with the different of type(Object) type casting method.

[X]: this.canvas1.width=this.textinput.text as Number;
[O] this.canvas1.width=Number(this.textinput.text);

Basically “type([object])” and “[object] as type” actually do the same thing as long as casting between compatible types. If casting is fail, for “type([object])”, exception will be thrown, while “[object] as type” will return NULL. So then, if appropriate action is taken, no Run Time Error will be occur or the thrown exception does not need to be caught.
Reference: AS3 typechecking

However, why does my friend’s code not work?
The ‘as’ operator does not work for Top Level Class. What ‘Top Level Class’ is? See:
Reference: Top Level package

As ‘Number’ is top level class, her statement does not work. I hope this can be a good reference for others who encountered similar problem.

»  Substance: WordPress   »  Style: Ahren Ahimsa