Search code examples
eventsscopeactionscript-2delegatecommand

Scope for Actionscript 2.0 Event


I'm using Actionscript 2.0 for a mobile phone and can't get my head around Events.

I'm creating a class object with all my code and using a group of functions (all as direct 1st level children of the class). There's one function that creates a Movieclip with a square on it and sets the onPress event to another function called hit:

public function draw1Sqr(sName:String,pTL:Object,sSide:Number,rgb:Number){
    // create a movie clip for the Sqr
        var Sqr:MovieClip=this.canvas_mc.createEmptyMovieClip(sName,this.canvas_mc.getNextHighestDepth());
    // draw square
        Sqr.beginFill(rgb); 
        //etc  ...more lines        

    //setup properties (these are accessible in the event)
        Sqr.sSide=sSide;
        Sqr.sName=sName; 

    //setup event
        Sqr.onPress = hit; // this syntax seems to lead to 'this' within
                            // the handler function to be Sqr (movieclip)

        //Sqr.onPress = Delegate.create(this, hit); 
        //I've read a lot about Delegate but it seems to make things harder for me.
    }



Then in my event handler, I just cannot get the scope right...

public function hit(){
    for (var x in this){
        trace(x + " == " + this[x]);
    }
            //output results
                //onPress == [type Function]
                //sName == bSqr_7_4
                //sSide == 20

    trace(eval(this["._parent"])); //undefined
    trace(eval(this["._x"])); //undefined

}

For some reason, although the scope is set to the calling object (Sqr, a Movieclip) and I can access properties I defined, I can't use the 'native' properties of a Movieclip object.

Any suggestions on how I can access the _x, _y and other properties of the Movieclip object that is pressed.


Solution

  • Use the array accessor or the dot accessor, but not both. For example:

    trace(this._parent); // OR
    trace(this["_parent"]);
    

    As for the results of your iteration, I recall AS2 being screwy on this front. IIRC only dynamic properties are returned when looping with for ... in. This prevents Objects (which often serve as hash maps) from including their native properties when all you want are the key/value pairs you set yourself.

    Also - the eval() function can be easily overused. Unless you absolutely must execute a String of AS2 that you don't have at compile-time I would recommend avoiding it. Happy coding!