Most Flex developers are aware that mxml files are essentially declarative representations of ActionScript classes, that is, during compilation the mxmlc compiler generates ActionScript 3.0 classes from mxml files before being converted into bytecode that runs in Flash Player. This can be seen by setting the compiler argument -keep-generated-actionscript to true.
You may be thinking “yeah I know this, and…”, however in the past week I have had two talented Flex developers say to me: “but you can’t implement interfaces in mxml… Can you?”
Now if you think about that statement a bit more you will probably realize that you most certainly can, however it mat not seem so obvious at first as developers tend to think of mxml for what it is, a markup language and not necessarily from a compilation perspective.
So in case you are not aware how interfaces can be implemented in mxml I have provided a few simple examples below which demonstrate how a custom component can implement an interface, in this case mx.rpc.IResponder.
First you define the interface that the component will implement using the implements
property of the component.
1 2 3 4 5 6 | <?xml version="1.0" encoding="utf-8"?> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" implements="mx.rpc.IResponder" > </mx:VBox> |
Next you simply implement the operations defined by the interface as you normally would in a class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?xml version="1.0" encoding="utf-8"?> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" implements="mx.rpc.IResponder" > <mx:Script> <![CDATA[ public function result(data:Object) : void { // implementation } public function fault(info:Object) : void { // implementation } ]]> </mx:Script> </mx:VBox> |
Now you may be wondering how multiple interfaces are implemented in mxml? This is very easy as well, simply specify the fully qualified class path of each interface as a CSV (Comma-separated values). An example can be seen in the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?xml version="1.0" encoding="utf-8"?> <mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" implements="mx.rpc.IResponder,mx.core.IUID" > <mx:Script> <![CDATA[ public function result(data:Object) : void { // implementation... } public function fault(info:Object) : void { // implementation... } public function get uid() : String { // implementation... } public function set uid(value:String) : void { // implementation... } ]]> </mx:Script> </mx:VBox> |
And that’s all there is to it.
Nice!
🙂
I generally use them for Modules, or other components that will be developed outside my control. By using/specifying an interface, both parties can (read have to) agree on what signatures will be present whether AS or mxml.