AS3-自定义事件攻略
这个Demo讲的是一个Customer去Barbershop消费,而Barbershop提供2种ServerEvent,CUT_HAIR和SPECIAL。
具体代码,先来文档类Barbershop.as:
具体代码,先来文档类Barbershop.as:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
package { import Customer; import Waiter; import flash.display.Sprite; import flash.text.TextField; import flash.events.MouseEvent; public class Barbershop extends Sprite { var customDF:Customer=new Customer("DFdou"); var waiter:Waiter=new Waiter("路人A"); public function Barbershop () { addChild (waiter); btnCutHair.addEventListener (MouseEvent.CLICK,cutHair); btnSpecial.addEventListener (MouseEvent.CLICK,special); } function cutHair (_evt:MouseEvent) { customDF.addEventListener (ServerEvent.CUT_HAIR,waiter.serve); customDF.callServe (ServerEvent.CUT_HAIR,"MM1"); customDF.removeEventListener (ServerEvent.CUT_HAIR,waiter.serve); } function special (_evt:MouseEvent) { customDF.addEventListener (ServerEvent.SPECIAL,waiter.serve); customDF.callServe (ServerEvent.SPECIAL,"MM2"); customDF.removeEventListener (ServerEvent.SPECIAL,waiter.serve); } public function showInfo (_str:String) { txtInfo.appendText (_str+"\n"); } }} |
自定义事件类ServerEvent.as:
|
1
2
3
4
5
6
7
8
9
10
11
|
package { import flash.events.Event; public class ServerEvent extends Event{ public static const CUT_HAIR:String="cut_hair"; public static const SPECIAL:String="special"; public var _server:String;//指定个变量来存放服务人员 public function ServerEvent (eventType:String):void { super(eventType); } }} |
Customer顾客类Customer.as:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package { import flash.events.EventDispatcher; public class Customer extends EventDispatcher { public var _name:String; public function Customer (name:String):void { _name=name; } public function callServe(eventType:String,server:String){ var serverEvent:ServerEvent=new ServerEvent(eventType); serverEvent._server=server;//指定服务的人 dispatchEvent(serverEvent);//发送事件 } }} |
Waiter类Waiter.as:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package { import flash.display.Sprite; public class Waiter extends Sprite{ public var _name:String; public function Waiter (name:String) { _name=name; } public function serve (_evt:ServerEvent) { //调用root里的函数,这里是用来做Demo用到~ Object(root).showInfo("你需要"+_evt._server+"服务,服务类型为:"+_evt.type); } }} |
自定义事件的具体流程:
1.自定义好事件类;
2.注册事件侦听器;例子中为Custom callServe
3.发送dispatch事件;
4.侦听事件,处理;例子中为Waiter serve
5.移除侦听。

浙公网安备 33010602011771号