在类中使用stage.addEventListener在运行时期间返回空对象引用

时间:2013-08-17 21:23:59

标签: actionscript-3 flash oop

我想在名为“ChoiceBtn”的类中向舞台添加一个事件监听器。

我收到错误“1009:无法访问空对象引用的属性或方法”。我知道这是因为该对象尚未实例化。

这是我的代码:

我的主要文件代码:

    import ChoiceBtn;

var op1:ChoiceBtn = new ChoiceBtn("display meee", answer, 1, "a)", "4.jpg");
op1.x = 250;
op1.y = 60;
stage.addChild(op1);

我的班级档案:

package  {

import AnswerEvent;
import flash.display.Loader;
import flash.display.Sprite;
import flash.display.SimpleButton;
import flash.events.*;
import flash.ui.Mouse;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.net.URLRequest;
import flash.display.Stage;

public class ChoiceBtn extends Sprite{
    public var path:String;
    public var choiceText:String;
    public var choiceLabel:String;

    private var answer:Answer;
    private var choiceNum:uint;
    private var textFormat:TextFormat = new TextFormat();
    private var choiceLabelHwd:TextField = new TextField();
    private var choiceTextHwd:TextField = new TextField();
    private var boundingRect:Sprite = new Sprite;
    private var hitAreaWidth = 255;
    private var hitAreaHeight = 45;
    private var pic:Loader = new Loader;

    public function ChoiceBtn(choiceText:String, answer:Answer, choiceNum:uint, choiceLabel:String = "a)", picPath:String = null) {
        //path - must be the path to a picture
        //choiceText - the text to be displayed
        //choiceLabel - the prefix selector such as answers '1' or 'a)' etc.

        // constructor code
        this.answer = answer;
        this.choiceNum = choiceNum;
        this.choiceLabel = choiceLabel;
        this.choiceText = choiceText;

        //add childs
        addChild(this.choiceTextHwd);
        addChild(this.choiceLabelHwd);
        addChild(this.boundingRect);    //must be added last so is on top of everything else

        //add Listeners
        //stage.addEventListener(AnswerEvent.EVENT_ANSWERED, update); //doesn't work
        stage.addEventListener(AnswerEvent.EVENT_ANSWERED, this.update); //doesn't work either
    }

    public function update(e:Event):void {
        trace("in choice fired");
    }
}
}

我不明白为什么即使我在函数之前使用this它也不起作用。如何在此类构造函数代码中在舞台上创建eventlistener并引用此类中的函数。

1 个答案:

答案 0 :(得分:1)

等待首先触发ADDED_TO_STAGE事件:

public function ChoiceButton():void
{
    // your code.. etc..    
    addEventListener(Event.ADDED_TO_STAGE,addListeners);
}

private function addListeners(event:Event):void
{
    stage.addEventListener(AnswerEvent.EVENT_ANSWERED, update);             
}