When creating the default styles on a component you need to know the name of the class you are inside. The most common way of creating default styles is to use a static initializer.
package
{
import mx.core.UIComponent;
import mx.styles.CSSStyleDeclaration;
import mx.styles.StyleManager;
public class MyFlexComponent extends UIComponent
{
public function MyFlexComponent()
{
super();
}
private static var defaultStylesSet : Boolean = setDefaultStyles();
/**
* @private
*/
private static function setDefaultStyles():Boolean
{
var style:CSSStyleDeclaration = StyleManager.getStyleDeclaration( "MyFlexComponent" );
if( !style )
{
style = new CSSStyleDeclaration();
StyleManager.setStyleDeclaration( "MyFlexComponent", style, true );
}
if( style.defaultFactory == null )
{
style.defaultFactory = function():void
{
this.style0 = "style0";
this.style1 = "style1";
};
}
return true;
}
}
}This works fine, but it can be a problem if you refactor the class and change the class name as the string that is used in the above example won’t be updated. We’ve stumbled across this a few times and so our solution has been to write a method to take care of this class name for us.
You pass the prototype of your class to the method and it uses a bit of regex to return the class name.
package
{
import mx.core.UIComponent;
import mx.styles.CSSStyleDeclaration;
import mx.styles.StyleManager;
public class MyFlexComponent extends UIComponent
{
public function MyFlexComponent()
{
super();
}
private static var defaultStylesSet : Boolean = setDefaultStyles();
/**
* @private
*/
private static function setDefaultStyles():Boolean
{
var defaultStyleName:String = StyleUtil.getDefaultStyleName( prototype );
var style:CSSStyleDeclaration = StyleManager.getStyleDeclaration( defaultStyleName );
if( !style )
{
style = new CSSStyleDeclaration();
StyleManager.setStyleDeclaration( defaultStyleName, style, true );
}
if( style.defaultFactory == null )
{
style.defaultFactory = function():void
{
this.style0 = "style0";
this.style1 = "style1";
};
}
return true;
}
}
}
thanks for this.