Utility functions in Flex

I wanted to use some functions that do not belong to any visual component. I did not want to use the Java-style syntax in ActionScript (with classes and interfaces). Since ActionScript is closely related to JavaScript, I created a JavaScript-like object and put the utility functions there. The file is in src/com/mycompany/util/MYCO.as:

package com.myco.util {

	import flash.events.Event;

	public function MYCO():Object {

		this.safeNull=function(instr:String):String {
	    	return instr==null?'':instr;
	    }
}

I can reference methods in this object from other files like this:

 var blah:Function= com.myco.util.MYCO().safeNull;
 var ret:String=blah.apply(this, ['hello']);

Suppose I need access to other functions in the MYCO object, I define a locally visible variable called Myco and assign it to this:

package com.myco.util {

	import flash.events.Event;

	public function MYCO():Object {
		var Myco:Object=this;
		this.safeNull=function(instr:String):String {
                Myco.sayHelloFirst();
	    	return instr==null?'':instr;
	    },

	    this.sayHelloFirst=function():void {
	    	// saying hello
	    }
    };
}

This is because I can not just use ‘this’. ‘this’ could point to some other object, according to the rules of JavaScript.

One Response to “Utility functions in Flex”

  1. Jasmine says:

    Very interesting use of the function object.
    I was just wondering:
    If you are thinking about encapsulating the properties in this package by using this top level component: public function MYCO():Object {…}, so the properties can not clash with properties of other components, could the class definition( such as: public class MYCOextends {…} ) serve this purpose?

Leave a Reply