解决子对象和父函数之间的1069错误

时间:2011-07-01 03:46:57

标签: actionscript-3

我缩短了下面的代码示例,以便它更具可读性。这就是问题:我创建了一大堆包含字母a-z的MovieClip。这些MovieClip是名为“levelTwo”的父MovieClip的子节点,其中levelTwo是该级别的一种逻辑管理器。

当点击它们时,它们会将一些数据发送到levelTwo进行评估(它是Hangman)。问题是点击后我得到1069错误。在我添加LetterButton中的event.target.parent位之前,它是一个1061错误。

以下是相关代码:

package  {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;

public class LetterButton extends MovieClip {

    var buttonText:String;

    public function LetterButton(lText:String,objX:int,objY:int) 
    {
        trace ("Creating new button");
        x = objX;
        y = objY;
        buttonText = lText;
        letterText.text = buttonText;
        this.stop();
        addEventListener(MouseEvent.MOUSE_OVER,onMouseOver);
        addEventListener(MouseEvent.MOUSE_OUT,onMouseOut);
        this.addEventListener(MouseEvent.CLICK,onMouseClick);
    }

    private function onMouseOver(event:Event):void
    {
        gotoAndStop(2);
        letterText.text = buttonText;
        //trace ("You're over me and my text is " + buttonText);
    }

    private function onMouseOut(event:Event):void
    {
        gotoAndStop(1);
        letterText.text = buttonText;
        //trace ("You're out of me and my text is " + buttonText);
    }

    private function onMouseClick(event:Event):void
    {
        trace ("I am clicked and I am " + buttonText);
        event.target.parent.checkGuess(buttonText);

    }

}

} 而且来自levelTwo的相关位:

public function checkGuess(guess:String):void
    { //Check to see if the guess matches the string


        trace ("Guess: "+guess);
        for(var i:int=0;i<answer.length;i++)
            {
                if(guess == answer.charAt(i))
                {
                    censoredAnswer[i] = guess;
                    trace ("Got one right");
                    answerField.text = answerRedisplay(); //Do it now or it won't update for the check
                }
            }   
        if (answerField.text == answer)
            {
                setWin(); 
            }
    }

1 个答案:

答案 0 :(得分:0)

我觉得这里没有魔法。您订阅了LetterButton实例,因此您获得指向它的event.target引用。

我认为更好的方法是订阅包含所有LetterButton实例的父剪辑。 MouseEvent.CLICK是一个冒泡事件,因此每次在其中单击某些内容时,您将在父级触发处理程序。

请参阅示例代码。

// inside level two class
addEventListener(MouseEvent.CLICK,onMouseClick);

private function onMouseClick(event:MouseEvent):void
{
    var target:LetterButton = event.target as LetterButton;
    if (target == null) {
        return;
    }
    // here we know, that some LetterButton instance was clicked
    // and target var holds it's reference

    // either make buttonText public, or create a getter/accessor
    // var text:String = target.buttonText;
    var text:String = target.getButtonTextSomehow();

    checkGuess(text);
}