一:目的
问:为什么要自定义事件?
答:系统提供事件不能满足。
举例:需要传递参数。
二:背景
事件不是鼓励存在的,事件始终是和一个对象相关联的,否则,单独说事件毫无意义。
举例:当英雄血为0时,死亡。
1:英雄血为0-》2:触发死亡事件-》英雄死亡。
所以:
事件:死亡事件;
对象:英雄;
英雄对应死亡事件,英雄触发引起死亡事件,无对象,不事件。
三:实例
1:初始化
hero=龙骑士
hp=3
2:攻击
-hp
3:死亡
四:代码
1:
对象类 ===英雄类:
触发事件的对象需要继承EventDispatcher
package event
{
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
public class Hero extends EventDispatcher
{
public var hp:int = 0;
public function Hero(target:IEventDispatcher=null)
{
super(target);
}
public function hpdown(name:String):void{
hp--;
if(hp==0){
sayDead(name);
}
}
private function sayDead(name:String):void{
this.dispatchEvent(new DeadEvent(DeadEvent.DEAD,name));
}
}
}
2:
事件类==死亡事件
自定义事件需要继承Event
package event
{
import flash.events.Event;
public class DeadEvent extends Event
{
public static const DEAD:String = "dead";
public var name:String;
public function DeadEvent(type:String,name:String)
{
super(type, bubbles, cancelable);
this.name = name;
}
}
}
3:页面
给对象增加事件监听,并处理监听回调方法。
对象触发了事件后,要执行某方法。
触发事件
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import event.DeadEvent;
import event.Hero;
import event.Man;
import event.MyEvent;
private var hero:Hero = new Hero();
function init():void{
hero.hp=3;
hp.text=hero.hp.toString();
heroname.text="龙骑士";
hero.addEventListener(DeadEvent.DEAD,DeadHandler);
}
function DeadHandler(e:DeadEvent):void{
ds.text = e.name+"已经被杀死!";
}
function attack():void{
if(hero.hp==0){
Alert.show("已经死亡,不能攻击");
}else {
hero.hpdown(heroname.text);
hp.text = hero.hp.toString();
}
}
]]>
</mx:Script>
<mx:TextInput x="210" y="149" fontSize="14" id="heroname"/>
<mx:TextInput x="210" y="209" id="hp" fontSize="14"/>
<mx:Button x="210" y="264" label="攻击" click="attack()" fontSize="14"/>
<mx:Label x="131" y="151" text="名称" fontSize="14"/>
<mx:Label x="131" y="211" text="血量" fontSize="14"/>
<mx:Label x="131" y="308" text="是否死亡" fontSize="14"/>
<mx:TextInput x="210" y="306" text="否" id="ds" fontSize="14"/>
</mx:Application>
PS:CSDN的图片上传,一直失败,也不知怎么解决
如下图:
我的图片是通过URL直接访问的