Reputation: 385
I'm attempting to learn ActionScript 3 as my first programming language (before this I only did in past some little crap with PHP).
I have this code:
package
{
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
/**
* ...
* @author Mattia Del Franco
*/
[Frame(factoryClass="Preloader")]
public class Main extends Sprite
{
[Embed(source = "img/pgnew.png")]
internal var MyImage:Class;
// La riga embed importa l'immagine, la riga sotto la assegna ad una classe chiamata MyImage
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
trace ("Hello World!");
var myBitmap:Bitmap = new MyImage; //nuova variabile myBitmap al quale viene assegnato la creazione di un nuovo MyImage (trattato come un oggetto)
addChild( myBitmap );
var writeText:TextField = new TextField();
writeText.text = "Ciao Mondo!";
this.addEventListener(MouseEvent.CLICK, function(){
addChild(writeText);
var clicked:Boolean = true;
return clicked;
});
this.addEventListener(MouseEvent.CLICK, function() {
if (clicked == true) {
removeChild(writeText);
} else {
addChild(writeText);
}
});
}
}
}
In the second EventListener I'm trying to get the boolean value of clicked (specified in the first EventListener) but when i go to debug this program i get this error:
col: 9 Error: Access of undefined property clicked. if (clicked == true) {
Why this happens?
Upvotes: 0
Views: 471
Reputation: 499
The reason that you cannot access the "clicked" variable is because this variable is held in a different scope. When you declare a variable within a function (your first Event Listener), it is only accessible from within that function. Your second Event Listener has no access to that variable.
Here is a good way to work around the problem:
var clicked:Boolean = false; var writeText:TextField = new TextField(); writeText.text = "Ciao Mondo!"; this.addEventListener(MouseEvent.CLICK, function(){ addChild(writeText); clicked = true; return clicked; }); this.addEventListener(MouseEvent.CLICK, function() { if (clicked == true) { removeChild(writeText); } else { addChild(writeText); } });
Upvotes: 1