上图反应了flex组件的层次关系,其中EventDispathcer排在第二位,这使其及其子类均可以使用事件机制。AS用事件广播触发事件句柄执行方法。event在AS编程中的地位如同燃料对于汽车。
不要在事件句柄中直接引用上下文对象,而应该通过其event.currentTarget获其属性、方法。如下所示:
private function tiHandler(e:Event):void {
e.currentTarget.setSelection(0,3);
}默认event.currentTarget是动态的Object,即其可以拥有任何动态属性和方法。在上面例码中,e.currentTarget.id在编辑时并不会得到编辑器的提示,编译时也不会检测其有没有setSelection这个方法。如果不小心小属性或方法名称写错了,比如写成了e.currentTarget.setSelect或其它,运行时将抛出异常。这即说明,即使在AS这种非强类型语言中,也需要强类型支持。编程时也应该这样的习惯。以上代码按这个原则,应该如下:
private function tiHandler(e:Event):void {
/* The following enforces type checking: */
TextInput(e.currentTarget).setSelection(0,3);
/* The following throws a run-time error but not a compile-time error:
e.currentTarget.tmesis = 4;
*/
/*
... unless you cast it to the expected type like the following. Then
the compiler throws an error.
TextInput(e.currentTarget).tmesis = 4;
*/
}很遗憾AS3目前其event不支持+=操作,我们用如下方法在as中注册一个事件句柄:
b1.addEventListener(MouseEvent.CLICK, myClickListener); 如果能够b1.click += myClickListener该有多么美好。
admin#flashas.net (#为@) 联系QQ:
:40777822
浙ICP备06033001号