这不是生死攸关的问题,但我想知道这是否可行:
我从一种类型的自定义事件(FormEvent)中获得了一些事件,现在我得到了一个FormListener,它监听所有这些事件并根据事件类型处理它们.我希望一次添加所有事件,而不是添加一个eventListener.
所以现在它看起来像这样:
private function addListeners():void { addEventListener(FormEvent.SHOW_FORM, formListener); addEventListener(FormEvent.SEND_FORM, formListener); addEventListener(FormEvent.CANCEL_FORM, formListener); } private function formListener(event:formEvent):void { switch(event.type){ case "show.form": // handle show form stuff break; case "send.form": // handle send form stuff break; case "cancel.form": // handle cancel form stuff break; } }
但是,我宁愿做类似的事情,而不是每次添加一个事件
private function addListeners():void { addEventListener(FormEvent.*, formListener); }
我想知道这样的事情是否可行,我会喜欢它.我处理大量事件:)
无论如何,在这种情况下你只需要一个事件监听器.该监听器将使用表单和一个参数来监听任何更改,该参数等于事件监听器函数可用的更改.我会告诉你,但请记住,这是一个伪情况,通常我不会发送一个像方法调用这样简单的事件,因为调度是隐含的,所以没有真正需要监听它.
首先是自定义事件
package com.yourDomain.events { import flash.events.Event; public class FormEvent extends Event { //Public Properties public static const CANCEL_FORM:int = "0"; public static const SHOW_FORM:int = "1"; public static const SEND_FORM:int = "2"; public static const STATE_CHANGED:String = "stateChanged"; //Private Properties private var formState:int; public function FormEvent(formState:int):void { super(STATE_CHANGED); formState = formState; } } }
所以我们刚刚创建了我们的自定义事件类,并且我们已经设置它以便我们可以通过监听器函数捕获状态,因为我将演示一旦使用将为所述自定义事件调度的伪表单类.
请记住,这都是假设,因为我不知道您的代码是什么样的或者您的实现方式.重要的是要注意,当我发送事件时,我需要发送一个反映新状态的参数.
package com.yourDomain.ui
{
import flash.events.Event;
import flash.events.EventDispatcher;
import com.yourDomain.events.FormEvent;
public class Form extends EventDispatcher
{
public function Form():void
{
//Anything you want form to do upon instantiation goes here.
}
public function cancelForm():void
{
dispatchEvent(new Event(FormEvent.CANCEL_FORM);
}
public function showForm():void
{
dispatchEvent(new Event(FormEvent.SHOW_FORM);
}
public function sendForm():void
{
dispatchEvent(new Event(FormEvent.SEND_FORM);
}
}
}
最后,我们创建了将要监听它的文档类.请注意,我知道创建一个在调用类的方法时触发的侦听器是不合逻辑的,因为您显然知道您调用了该方法,但是对于此示例,它将到期.
package com.yourDomain.ui
{
import com.yourDomain.ui.Form;
import com.yourDomain.events.FormEvent;
//Form is in the same package so we need not import it.
public class MainDocumentClass
{
private var _theForm:Form;
public function MainDocumentClass():void
{
_theForm = new Form();
_theForm.addEventListener(FormEvent.STATE_CHANGED, onFormStateChange, false, 0, true);
/*
The following three method calls each cause the
FormEvent.STATE_CHANGE event to be dispatched.
onFormStateChange is notified and checks what
the last change actually was.
*/
_theForm.cancelForm();
_theForm.showForm();
_theForm.sendForm();
}
private function onFormStateChange(e:FormEvent):void
{
switch(e.formState)
{
case CANCEL_FORM:
trace('The form was canceled');
break;
case SHOW_FORM:
trace('The form was revealed');
break;
case SEND_FORM:
trace('The form was sent');
break;
}
}
}
}
我希望这很有用,它很晚,我可能不得不稍后修改一些东西,但这应该有助于理解如何制作自己的事件并定制工作方式.