有没有办法捕获特定对象的所有事件?
当我使用addEventListener()
时,我必须提供事件类型。有没有办法把它们全部抓住?
谢谢!
答案 0 :(得分:2)
您可以使用describeType
获取所有已声明事件的列表。您需要查看父类以获取继承的事件,并且您可能希望避免使用frameConstructed
,enterFrame
和exitFrame
。
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script><![CDATA[
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
private function init():void {
var eventNames:Array = new Array();
findEventsRecursive(btn, eventNames);
for each(var eventName:String in eventNames) {
if (eventName != "frameConstructed" &&
eventName != "exitFrame" &&
eventName != "enterFrame") {
btn.addEventListener(eventName, genericHandler);
}
}
}
private function genericHandler(event:Event) {
trace(event.type + " triggered");
}
private function findEventsRecursive(instance:Object, eventNames:Array) {
var description:XML = describeType(instance);
findEvents(description, eventNames);
for each(var parentType:String in description.extendsClass.@type) {
var parentClass:Object = getDefinitionByName(parentType);
var parentDescription:XML = describeType(parentClass);
findEvents(parentDescription, eventNames);
}
}
private function findEvents(description:XML, eventNames:Array) {
for each(var eventName:XML in description.factory.metadata.(@name=='Event').arg.(@key=='name')) {
eventNames.push(eventName.@value);
}
}
]]></mx:Script>
<mx:Button id="btn" />
</mx:Application>
但不必宣布事件。任何类都可以使用字符串名称发送事件,而这些事件不会被describeType
(或通过任何其他机制)接收。