ActionScript: A Global Utilities Class

I created a global utilities class as part of my gpAS3Library. This ActionScript class is essentially a Singleton class that can be used throughout my Flash application without being instantiated.

The global utility class contains a variety of functions that do no belong to any particular class. The key to creating a global utility class is creating static functions within the class.

As an example, the gpAS3Libary contains a class named gpGlobalUtils. Within this class, I have a method that replaces characters in a string.

?View Code ACTIONSCRIPT
package com.grasshopper.utils {
 
	public class gpGlobalUtils {
 
		public static function stripChars(str:String, searchFor:String, replaceWith:String):String {
			var sub:String;
			var index:Number;
			var len:Number = searchFor.length;
			while (str.indexOf(searchFor) != -1) {
				index = str.indexOf(searchFor);
				sub = str.substring(0, index) + replaceWith;
				str = sub + str.substr(index+len, str.length);
			}
			return str;
		}
        }
}

Notice that my class does not have a constructor:

?View Code ACTIONSCRIPT
package com.grasshopper.utils {
 
	public class gpGlobalUtils {
 
		public function gpGlobalUtils() {
 
		}
        }
}

I can call the stripChars method from anywhere within my flash application.

?View Code ACTIONSCRIPT
package {
        import com.grasshopper.utils.gpGlobalUtils;
        // or import com.grasshopper.utils.*;
 
        public class portfolio extends MovieClip {
                init();
        }
 
        private function init():void {
                var str:String = 'http://grasshopperpebbles.com';
                var dName:String = gpGlobalUtils.stripChars(str, 'http://', '');
                trace(dName);
                // output - grasshopperpebbles.com
        }
}

Notice that I do not have to instantiate the class:

?View Code ACTIONSCRIPT
var gp:gpGlobalUtils = new gpGlobalUtils();
var str:String = 'http://grasshopperpebbles.com';
var dName:String = gp.stripChars(str, 'http://', '');

As long as I import the package (or class), I can call all methods with within the class as long as I set the method as public static. This makes it easy to create a global utilities class.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks