« Flash/Flex/Flash Lite/Air interface to Zimbra MTA | Home | Beware of what you post online »
January 28, 2009
ActionScript 3 namespace
I have never been in the position i was required to use namespaces until today so i thought it would be a cool idea to share this example here for you to see.
Today i had the need to create an ActionScript 3 class model that will represent a data row from a database.
I needed a way to feed in the data into the class instance but only provide "read" methods for the end-user.
How would you do this?
You create public get methods but set methods inside a namespace. This is done a lot on the flex framework. Do you remember seeing "mx_internal" around the component classes for example? ;)
Here goes the example, lets create a "my_internal_ns" namespace for example (i'll place it inside the "com.domain.ns" package as an example:
package com.domain.ns {
public namespace my_internal_ns = "http://www.domain.com/ns/my_internal_ns";
}
I'm using a url but it could be a class package if you want. Oh! and the url doesn't need to exist really.
Now let's create the other class:
package com.domain.models {
// import the namespace
import com.domain.ns.my_internal_ns;
// use the namespace
// this could be local to a method btw
use namespace my_internal_ns;
public class TestModel {
private var _name:String = "";
private var _age:uint = 1;
private var _email:String = "";
public function TestModel(){
}
// read-only
public function get name():String{ return _name; }
public function get age():uint{ return _age; }
public function get email():String{ return _email; }
// internal write
my_internal_ns function set name(value:String):void{ _name = value; }
my_internal_ns function set age(value:uint):void{ _age = value; }
my_internal_ns function set email(value:String):void{ _email = value; }
}
}
Thats it! You will notice that namespace'd methods won't appear in flex builder's autocomplete list.
--fernando
Que buen uso! Vi algo parecido dentro de las clases de Flex pero recien me lo has dejado totalmente claro. ^^
This will throw an error in flex because of a bug in the mxml compiler (ver. 2):
http://kb.adobe.com/selfservice/viewContent.do?externalId=4a146409&sliceId=2
"If a class contains accessor functions with different access control namespace attributes, (for example, aprotected setter and a public getter) using one of them causes a compile-time-error, for example,Compiler-Error 1000: Ambiguous reference to myVar
The workaround is to rename your getter or setter function to avoid the mismatch"
Great, been looking for this