// 引用 http://bbs.9ria.com/thread-59337-1-1.html 八楼
自定义事件就相当于在几个毫不相干的类之间互相通讯并且传递参数。例如A类中加载完成一个图片后,需要把这个图片交给B类中做些处理,这时就可以自定一个事件。图片读取完成后从A类中dispatchEvent,把图片附在你的自定义事件中,然后在B类中对A类派发的事件进行侦听 A对象.addEventListener,这时当B类捕获到事件后,就可以把图片从事件中拿出来用了,实现了A类B类之间的通讯传值~
就是实现更方便的通讯,自定义事件类写起来感觉不是很多代码,当然可以自己再定义参数
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.ColorTransform;
import flash.geom.Rectangle;
import share.MySharedObject;
/**
* 测试
* @author wyr0924
*/
public class test extends Sprite
{
private var nullArray:Array;
/**
* 构造函数。
*
*/
public function test()
{
var bgBall:Ball = new Ball();
bgBall.name = 'bg ball';
bgBall.width = 100;
bgBall.height = 100;
bgBall.x = bgBall.y = 200;
addChild(bgBall);
bgBall.addEventListener(BallEvent.BALL_DROP,onDropBall);
bgBall.addEventListener(BallEvent.BALL_PRESS,onPressBall);
var ball:Ball = new Ball();
ball.name = 'tiny ball';
ball.transform.colorTransform = new ColorTransform(0,0,0,1);
addChild(ball);
ball.addEventListener(BallEvent.BALL_PRESS,onPressBall);
ball.addEventListener(BallEvent.BALL_DROP,onDropBall);
}
private function onPressBall(e:BallEvent):void
{
trace('press -- ' + e.source.name);
}
private function onDropBall(e:BallEvent):void
{
trace(e.source.name + 'drop on --' + e.target.name);
}
}
}
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* 球.
* @author wyr0924
*/
public class Ball extends Sprite
{
/**
* 构造函数.
* @param addEvent
*
*/
public function Ball()
{
draw();
addEventListener(MouseEvent.MOUSE_DOWN,onDown);
}
private function draw():void
{
buttonMode = true;
graphics.beginFill(0xff0000);
graphics.drawCircle(0,0,20);
}
private function onDown(e:MouseEvent):void
{
parent.setChildIndex(this,parent.numChildren - 1);
startDrag(true);
addEventListener(MouseEvent.MOUSE_UP,onUp);
var press:BallEvent = new BallEvent(BallEvent.BALL_PRESS,true);
press.source = this;
dispatchEvent(press);
}
private function onUp(e:MouseEvent):void
{
stopDrag();
addEventListener(MouseEvent.MOUSE_DOWN,onDown);
removeEventListener(MouseEvent.MOUSE_DOWN,onUp);
var drop:BallEvent = new BallEvent(BallEvent.BALL_DROP,true);
drop.source = this;
if(dropTarget)
{
dropTarget.dispatchEvent(drop);
}
}
}
}
package
{
import flash.display.DisplayObject;
import flash.events.Event;
/**
* 球类事件.
* @author 4399-0668
*
*/
public class BallEvent extends Event
{
public static const BALL_DROP:String = 'ballDrop';
public static const BALL_PRESS:String = 'ballPress';
public var source:DisplayObject;
/**
* 构造函数.
*/
public function BallEvent(type:String,bubbles:Boolean = false,cancelable:Boolean = false)
{
super(type,bubbles,cancelable);
}
}
}
dropTarget : DisplayObject
[read-only] 指定拖动 sprite 时经过的显示对象,或放置 sprite 的显示对象。
// 引用 六楼
//自己不能做的事,发出事件,请求有管辖权的对象去做,dispatchEvent
//自己能做的事自己做,放在自己的框架内自己管理,比如定义鼠标事件,自己定义