愚人呓语 eidiot's blog. My flapdoodles.

18七/06

AS3学习笔记(3)-Event

  做东西的时候发现AS3的EventDispatcher类好像不能传参数。请教 bogey ,答曰,写一个类继承 Event ,把参数放在构造里。试了一下,果然好用。有个牛×同事就是好 [haha]
  做个演示:(查看类代码

  页面生成部分就不介绍了,唯一值得注意的是 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
  • 白骷髅争气宝宝

    天哪~发快一年沙发都没人坐?
    我们的队伍需要壮大啊~

  • kita

    能不能把Event 发到其他地方让人在类外面也能 抓到 Event

  • http://eidiot.net eidiot

    事件本来就是用来在不同的类之间通讯的,不明白你要问什么
    中文帮助出来了,建议好好看看关于事件机制的部分
    ActionScript 3.0 编程 > 处理事件

  • wodesign

    Good!

  • http://www.ifolk.com.cn/protal ts

    受益匪浅

  • richards

    楼主牛x,多多贡献交流哈

  • DSLL

    为什么我下载下来你的源文件,打开会报错:
    5006: ActionScript 文件不能有多个外部可见的定义: Test, TestEvent

  • http://hi.baidu.com/wwwanq Michael

    有收获,谢谢!

  • Gogo

    看了受益匪浅,谢谢!
    我有个想法!用单例模式实现TestEventDispatcher,这样子就可以随意跨类发出事件通知.
    TestEvent实现可变参数的传递,所有自定义事件名称用静态String变量统一管理!
    刚学AS几个月,请多多指教,你的博客我会经常关注! [adore]