1.12使用代码隐藏模式分离MXML和ActionScript
发表时间:十二月. 18, 2009 | 作者: Freddie | 类别:Flex, flex cookbook
标题还真够长的, 说得通俗点,就是把原本要写在mxml里的代码写到as里面去。
其实我个人觉得就是JAVA里面的封装的思想,把代码写到AS里,加上访问限制修饰符,隐藏具体的实现细节。
看代码吧:
CodeBehindComponent.as(as代码):
package com.tub
{
import mx.containers.Canvas;
import flash.events.Event;
public class CodeBehindComponent extends Canvas
{
public function CodeBehindComponent()
{
super();
addEventListener(Event.ADDED_TO_STAGE, addedToStageListener);
}
protected function addedToStageListener(event:Event):void
{
trace(“Added to Stage from Code Behind”);
}
protected function clickHandler(event:Event):void
{
trace(“click from” + event.target);
}
}
}
CodeBehindComponent.mxml(mxml代码):
<?xml version=”1.0″ encoding=”utf-8″?>
<cookbook:CodeBehindComponent xmlns:mx=”http://www.adobe.com/2006/mxml”
width=”200″
height=”400″
xmlns:cookbook=”com.tub.*”>
<mx:Button click=”clickHandler(event)”/>
</cookbook:CodeBehindComponent>
asf.mxml(主程序,我这里随便取了个名字,这里把CodeBehindComponent组件拖进去就可以了)
<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” xmlns:ns1=”*”>
<ns1:CodeBehindComponent x=”73″ y=”38″>
</ns1:CodeBehindComponent>
</mx:Application>
这样,我们的CodeBehindComponent就封装好了,从mxml里仅仅看到一个BUTTON,并不知道点击会发生什么。
程序运行结果:
Added to Stage from Code Behind //当程序运行时
click fromasf0.CodeBehindComponent4.Button5 //点击按钮时

