how are events dispatched in as3?
i am having trouble understanding how to dispatch events and where to catch them. currently i have a document class waterMain, and another class called gunner. my waterMain createds a object of gunner and adds it as child, in my gunner there is a function firebullet, in it i dispatch a
dispatchEvent(new Event("bulletFired"));
and from my waterMain class i do a
addEventListener("bulletFired", bulletFiredHandler);
private function bulletFiredHandler(e:Event):void
{
hudMenu.reduceBullet();
}
the hudMenu is a variable on the waterMain document class, however it seems that nothing is happening. is the waterMain class not catching the dispatched event?
package
{
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
/**
* ...
* @author ...
*/
public class Gunner extends MovieClip
{
private var _stageRef:Stage;
public var barrel:MovieClip;
public var point:MovieClip;
public var _hudMenu:HUD;
public function Gunner(stageRef:Stage)
{
//trace("current rotation" + barrel.rotation);
//barrel.rotation = -90;
_stageRef = stageRef;
addEventListener(Event.ENTER_FRAME, rotateTurret);
_stageRef.addEventListener(MouseEvent.MOUSE_DOWN, fireBullet);
private function rotateTurret(evt:Event):void
{
//calculations, distance, angle etc
var a:Number = _stageRef.mouseX - x;
var b:Number = _stageRef.mouseY - y;
var angRad:Number = Math.atan2(b, a);
var angDeg:Number = (angRad * 180 / Math.PI);
//trace(angDeg );
barrel.rotation = (angDeg);
}
private function fireBullet(mouseEvt:MouseEvent):void
{
dispatchEvent(new Event("bulletFired"));
_stageRef.addChildAt(new Bullet(_stageRef,x, y , new Point(mouseEvt.stageX, mouseEvt.stageY), _koiArray, _lionArray), 1);
_stageRef开发者_开发技巧.addChild(_stageRef.addChild(this));
}
}
}
You need to add the event to the gunner class something like this:
gunner.addEventListener("bulletFired", bulletFiredHandler);
The gunner class is already a EventDispatcher subclass, if I read your question correctly.
Just to add to the previous answer by @Neoraptor, you could also handle this by dispatching the event with "bubbles=True".
Bubbling an event means to take that event and pass it up from the dispatcher, through the entire display hierarchy, all the way to the document class. As long as the event is not set to cancelable (or it is, and nothing actually cancels it) then your event will eventually reach the document class.
The other solution, provided by @Neoraptor, is correct, though it should be noted that it is not the only way. Sometimes you want to use the bubbles=True way, especially when your event is dispatched much farther down the display list. For example, if your bullets are dynamically created, and they dispatch an event that the document class needs to know about, then it is far easier to just let the event bubble from the dispatcher than to try to target the specific instances of bullet the are created.
精彩评论