我有两个名为Guest和Guest2的类。我想知道是否可以从Guest2类中删除Guest类中的eventlistener。以下是完整的代码。注意:两个类都具有完全相同的代码
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.*;
public class Guest extends MovieClip
{
var walkSpeed:Number = 5;
var oldPosX;
var oldPosY;
var myGlow:GlowFilter = new GlowFilter();
public function Guest()
{
addEventListener(MouseEvent.MOUSE_OVER, addGlow);
}
function addGlow(event:MouseEvent):void
{
filters = [myGlow];
addEventListener(MouseEvent.MOUSE_OUT, removeGlow);
addEventListener(MouseEvent.CLICK, ready);
}
function removeGlow(event:MouseEvent):void
{
filters = [];
}
function ready(event:MouseEvent):void
{
filters = [myGlow];
stage.addEventListener(MouseEvent.MOUSE_DOWN, walk);
removeEventListener(MouseEvent.MOUSE_OUT, removeGlow);
**MovieClip(root).Guest02.addEventListener(MouseEvent.CLICK, walkTo);**
}
function walk(event:MouseEvent):void
{
oldPosX = parent.mouseX;
oldPosY = parent.mouseY;
rotation = Math.atan2(oldPosY - y,oldPosX - x) / Math.PI * 180;
filters = [];
stage.removeEventListener(MouseEvent.MOUSE_DOWN, walk);
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function loop(event:Event):void
{
var dx:Number = oldPosX - x;
var dy:Number = oldPosY - y;
var distance:Number = Math.sqrt((dx*dx)+(dy*dy));
if (distance<walkSpeed)
{
// if you are near the target, snap to it
x = oldPosX;
y = oldPosY;
removeEventListener(Event.ENTER_FRAME, loop);
}
else
{
x = x+Math.cos(rotation/180*Math.PI)*walkSpeed;
y = y+Math.sin(rotation/180*Math.PI)*walkSpeed;
}
}
**function walkTo(event:MouseEvent):void
{
_Guest02.removeEventListener(MouseEvent.CLICK, ready);
}**
}
}
答案 0 :(得分:0)
正如Jake King已经指出的那样,您可能希望在面向对象编程方面重新审视您的代码。如果你说两个类共享完全相同的功能,为什么不设置一个类Guest并创建两个实例,例如guest1和guest2。
关于事件处理程序的问题,您需要将侦听器存储在一个公共实例变量中,然后可以从另一个实例(坏样式)访问,或者编写一个允许删除的专用公共函数监听器变量保持私有状态:
public class Guest extends MovieClip
{
private var overListener;
public function Guest()
{
overListener = addEventListener(MouseEvent.MOUSE_OVER, addGlow);
}
public function removeOverListener()
{
if (overListener) {
removeEventListener(MouseEvent.MOUSE_OVER, overListener);
}
}
...
}
如果guest1和guest2都是Guest的实例,并且guest1引用了guest2的guest2,那么您可以从guest1中删除guest2中的侦听器,如下所示:
guest2.removeOverListener();