PDA

View Full Version : accessing member variables from event handlers in AS2


mrand01
07-25-2005, 04:54 PM
class myClass extends MovieClip
{
private var btnButton:Button;
private var numTotal:Number = 0;

function myClass()
{

}

private function setButtonActions()
{
btnButton.onRelease = function()
{
trace (numTotal); //I get undefined
}
}
}


it seems that inside any event handler in my class, i can't access variables. Any ideas why?

csdstudio
07-25-2005, 05:00 PM
it seems that inside any event handler in my class, i can't access variables. Any ideas why?

Your event handler needs a reference to the instance. Seems to be one thing that is missing from most AS documentation. Try this...


class myClass extends MovieClip
{
private var btnButton:Button;
private var numTotal:Number = 0;

function myClass()
{

}

private function setButtonActions()
{
var _objReferece = this;
btnButton.onRelease = function()
{
trace (_objReferece.numTotal); //I get undefined
}
}
}

Mortimer Jazz
07-25-2005, 07:47 PM
As long as you're running version 7.2 you can use the Delegate class, which allows you to specify which scope you want the handler to run in.

import mx.utils.Delegate;

class MyClass extends MovieClip
{
private var btnButton:Button;
private var numTotal:Number = 2;

function MyClass()
{
btnButton.onRelease = Delegate.create(this, setButtonActions);
}

private function setButtonActions()
{
trace (numTotal); //now runs in the scope of the class
}
}

csdstudio
07-26-2005, 12:17 AM
Smart, now I learned something new too. :D