2013-08-17 39 views
0

我想從名爲「ChoiceBtn」的類內部向舞臺添加事件偵聽器。在類內部使用stage.addEventListener在運行時返回空對象引用

我收到錯誤「1009:無法訪問空對象引用的屬性或方法」。我明白這是因爲該對象尚未實例化。

這裏是我的代碼:

我的主文檔代碼:

import ChoiceBtn; 

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

我的.class文件:

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

等待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);    
} 
+1

只是爲了擴大Nuthman的回答了一下,你不能訪問顯示對象的stage屬性之後該對象已被添加到舞臺上,直到。 – Andreas

+0

這可以完美地修復一切。謝謝 :)。 – Klik

+0

我剛剛意識到我不小心添加了兩次事件監聽器。我修好了它 :) – Nuthman

相關問題