Created
December 21, 2010 15:53
-
-
Save jayproulx/750097 to your computer and use it in GitHub Desktop.
Creating MXML Singletons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* User: jproulx | |
* Date: 12/21/10 | |
* Time: 10:15 AM | |
*/ | |
package | |
{ | |
import flash.utils.Dictionary; | |
import flash.utils.getDefinitionByName; | |
import flash.utils.getQualifiedClassName; | |
public class MXMLSingleton | |
{ | |
private static var instances:Dictionary = new Dictionary(); | |
protected var instanceClass:Class; | |
public function MXMLSingleton() | |
{ | |
var clsName:String = getQualifiedClassName( this ); | |
instanceClass = getDefinitionByName( clsName ) as Class; | |
if( instances[instanceClass] ) | |
{ | |
throw new Error( "MXMLSingleton: Call the instance getter for " + clsName + "!" ); | |
} | |
else | |
{ | |
instances[instanceClass] = this; | |
} | |
} | |
protected static function getInstanceFor( cls:Class ):* | |
{ | |
if( !instances[cls] ) | |
{ | |
instances[cls] = new cls(); | |
} | |
return instances[cls]; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<local:MXMLSingleton xmlns:fx="http://ns.adobe.com/mxml/2009" | |
xmlns:s="library://ns.adobe.com/flex/spark" | |
xmlns:mx="library://ns.adobe.com/flex/mx" | |
xmlns:local="*"> | |
<fx:Script> | |
<![CDATA[ | |
public static function get instance():MySingletonModel | |
{ | |
return getInstanceFor(MySingletonModel) as MySingletonModel; | |
} | |
]]> | |
</fx:Script> | |
</local:MXMLSingleton> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment