做东西的时候发现AS3的EventDispatcher类好像不能传参数。请教 bogey ,答曰,写一个类继承 Event ,把参数放在构造里。试了一下,果然好用。
实例演示(查看类代码)
页面生成部分就不介绍了,唯一值得注意的是 TextField 类增加了一个 appendText 方法。以前的
myTxt.text += "your text";
应该写成:
myTxt.appendText("your text");
如果使用老的方法编译器会提示:这招太慢了,试试新的吧。(Appending text to a TextField using += is many times slower than using the TextField.appendText() method.) EventDispatcher 类的 dispatchEvent 方法只接受一个参数:event:Event。为了在广播事件的同时传递参数,写一个继承Event的类:TestEvent
internal class TestEvent extends Event{ //code here }
将事件类型声明为一个字符串常量:
public static const TRACE_INOF:String = "traceInfo";
将要传递的参数和事件类型一起放在构造函数里
private var _who:String; private var _info:String; public function TestEvent(type:String,who:String,info:String){ super(type);//调用父类 Event 的构造函数 _who = who; _info = info; }
广播事件的代码:
public function dispatch(who:String,info:String):void{ dispatchEvent(new TestEvent(TestEvent.TRACE_INOF,who,info)); }
注册监听器:
dispatcher.addEventListener(TestEvent.TRACE_INOF,onTraceInfo);
接收事件和参数:
public function onTraceInfo(event:TestEvent):void{ var traceTxt:TextField = getChildByName("traceTxt") as TextField; traceTxt.appendText(event.who+"dispatch:"+event.info); }
这里需要注意的是 as ,新的类型转换操作符,将 getChildByName() 返回的 DisplayObject 转换为前面声明的类型 TextField 。如果转换失败将返回 null 。官方给的例子:
public var myArray:Array = ["one", "two", "three"]; trace(myArray as Array); // one,two,three trace(myArray as Number); // null trace(myArray as int); // null
源文件: event.rar
出处:蓝色理想
责任编辑:moby
上一页 Timer 下一页 Function
◎进入论坛Flash专栏版块参加讨论
|