ErikH2000
05-13-2006, 06:00 PM
Is there a not-too-hackish way to use callbacks to class methods in ActionScript? The problem is that when the method is called, "this" no longer points to the object instance. So all variables of the object instance and even other methods in the class are undefined once execution reaches the callback. Here's example code:
class CSomeClass
{
var nSomeVar:Number;
function CSomeClass()
{
nSomeVar = 1;
setTimer(OnTimer, 3000);
}
function OnTimer()
{
if (!nSomeVar) trace("This makes me sad.");
}
}
One solution I've come up with is to have the callback call another function using an instance of the class stored in a root variable. So I do this:
class CSomeClass
{
...
function OnTimer()
{ _root.m_SomeClassInstance._OnTimer(); }
function _OnTimer()
{
//Variables and methods of the instance are available now.
}
}
That works okay for singleton objects, but if I have multiple instances of a class, I won't know which one to use in the callback. Other convoluted solutions suggest themselves, but I'm looking for something that makes it all easier. Maybe there is just some feature of the language I'm missing.
Also, it's not a solution to pass an instance as a parameter, because many callbacks I need to use are predefined in ActionScript to not accept additional parameters. If I were only using my own callbacks, then sure, I could pass "this" as a param.
-Erik
class CSomeClass
{
var nSomeVar:Number;
function CSomeClass()
{
nSomeVar = 1;
setTimer(OnTimer, 3000);
}
function OnTimer()
{
if (!nSomeVar) trace("This makes me sad.");
}
}
One solution I've come up with is to have the callback call another function using an instance of the class stored in a root variable. So I do this:
class CSomeClass
{
...
function OnTimer()
{ _root.m_SomeClassInstance._OnTimer(); }
function _OnTimer()
{
//Variables and methods of the instance are available now.
}
}
That works okay for singleton objects, but if I have multiple instances of a class, I won't know which one to use in the callback. Other convoluted solutions suggest themselves, but I'm looking for something that makes it all easier. Maybe there is just some feature of the language I'm missing.
Also, it's not a solution to pass an instance as a parameter, because many callbacks I need to use are predefined in ActionScript to not accept additional parameters. If I were only using my own callbacks, then sure, I could pass "this" as a param.
-Erik