Event.target上的removeChild出现错误#1009

时间:2011-10-04 20:47:28

标签: flash actionscript-3 events

private function bubbleFlury()
    {
        for (var i = 0; i < fluryAmount; i++)
        {
            fluryBubble = this.addChild(new bubble());
            fluryBubble.addEventListener(Event.ENTER_FRAME, fluryDisplace);
            fluryBubble.yspeed = randomRange(5, 10);

            with (fluryBubble)
            {
                x = Math.random() * sWidth;
                y = randomRange(sHeight, (sHeight+sHeight));
                width = height = 1 + Math.random() * 60;
            }
        }

        function fluryDisplace(e:Event):void
        {
            e.target.y -=  e.target.yspeed;

            if (e.target.y <= 0 - e.target.height)
            {
                var t:DisplayObject = DisplayObject(e.target);
                t.parent.removeChild(t)
            }
        }
    }

这是我无法弄清楚的功能:

function fluryDisplace(e:Event):void
    {
        e.target.y -=  e.target.yspeed;

        if (e.target.y <= 0 - e.target.height)
        {
            var t:DisplayObject = DisplayObject(e.target);
            t.parent.removeChild(t)
        }
    }

抛出

错误#1009:无法访问空对象引用的属性或方法。

我因某种原因感到很困惑。

1 个答案:

答案 0 :(得分:2)

执行removeChild()时,请务必删除EnterFrame事件监听器

function fluryDisplace(e:Event):void
{
    e.target.y -=  e.target.yspeed;

    if (e.target.y <= 0 - e.target.height)
    {
        e.target.removeEventListener(Event.ENTER_FRAME, fluryDisplace);

        var t:DisplayObject = DisplayObject(e.target);
        t.parent.removeChild(t);

    }
}

否则,事件会持续触发,但DisplayObject不再有parent,因此t.parent为空(并且令人担心1009 Error)。

希望我的解释不会太混乱。另外,我建议仔细阅读Mattias在评论中写的内容,尽量不要添加超过一个EnterFrame监听器,因为它们的性能非常昂贵。