Global Classes
To define a global class simply create your class at the root of your project within the default package as follows:
package
{
public class MySweetNewType
{
}
}
No more importing. Although this is discouraged by flex builder there are some very legitimate reasons why you might want to have a global class defined that is automatically imported into everything. Utility classes, user classes, permission classes, custom data types are some that come to mind. My rule of thumb on this is that the frequency of use justifies the means. If I find I'm using a class over and over again and I have to constantly import it, I put it in the default package and refactor.
But if you’re using a class over and over again, it’s time to think about a reusable Library. Just drop your class at the root of your library and reference the project and it works without importing as well.
Global Function
You can’t define a global function that rests at the root of the package and automatically gets imported (that works, it shows up in code hinting tho). But you can define a class with a static function that gets you close enough. If you get creative with your class name ( remember class name and file name have to be the same ) you can get close enough to a global function as is necessary. An example is below. this allows you to call echo with the simple syntax of $.echo(‘hello’). This works good for functions you find very repetitive. Using the dollar sign as my class name makes it very apparent that it’s not just any old function. I’m not sure if this has any side effects so if anyone knows or finds out let me know. So far it’ has passed the smell test.
package
{
public class $
{
public static function echo(phrase:String):String
{
trace(phrase);
return phrase;
}
}
}
Recent Comments