Creating required properties on an mxml object

In mxml, you have no access to the constructor of the component. Therefore, you have no way of requiring constructor arguments to be set.
I was thinking, it would be nice to have a way to enforce at least that certain properties get set.

So here's my solution. Feel free to improve upon it, it's just the first way I could think of to do this.
First, we add a metadata tag to all required properties of your Component.

[Required] public var requiredArgument:Object;

Then, add this to your compiler arguments so the [Required] tag gets compiled.


Download the following class to your classpath. (Preserve the packaging com/nbilyk/utils)

Then in your component, add in the preinitialize event the following:


So your whole component should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns="*" xmlns:mx="" creationComplete="ComponentUtil.checkRequired(this);">
			import com.nbilyk.utils.ComponentUtil;
			[Required] public var requiredString:String;
			[Required] public var requiredNumber:Number;
			[Required] [Bindable] public var requiredObject:Object;
			public function get requiredProp():String {}
			public function set requiredProp(value:String):void {}

Note that int, uint, and Boolean types cannot be required as they will always have a default value.