Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 referencing current function

I just came across a curious scenario where I want to use removeEventListener() within a function that doesn't have a name. By this I mean, I've created the function within addEventListener(), instead of making reference to one:

addEventListener(
    Event.ENTER_FRAME, 
    function(e:Event):void
    {
        if(getTimer() > 8000)
        {
            // removeEventListener(Event.ENTER_FRAME, <<this function>>);
            // Other stuff
        }
    }
);

Is it possible to make a reference to the current function (ie the function I'm working within)? Or do I just need to structure the above the standard way?

Please not that I am fully aware that you can use many of the standardized methods available to achieve the above, it was purely an example snippet.

like image 722
Marty Avatar asked Jul 19 '26 08:07

Marty


1 Answers

There are two options, you can either give it a name (and there are three ways to do that) or you can use arguments.callee.

In the case of the former, the three ways to name a function in AS3:

class Foo
{
    // class (static or member) level
    public function bar():void
    {
       // use a variable (technically, this function is anonymous, but we can
       // still use the variable to reference the function itself.
       var inVariable:Function = function():void
       {
          // declare it in a local scope
          function local():void
          {

          }
       }
    }
}

To use a named function:

function callback(e:Event):void {
    trace("tick");
    removeEventListener(Event.ENTER_FRAME, callback);
}
addEventListener(Event.ENTER_FRAME, callback);

To use arguments.callee:

addEventListener(
    Event.ENTER_FRAME, 
    function(e:Event):void
    {
        if(getTimer() > 8000)
        {
            // I get superstitious and I use a local variable.
            var callee:Function = arguments.callee
            removeEventListener(event.type, callee);
            // Other stuff
        }
    }
);
like image 79
cwallenpoole Avatar answered Jul 21 '26 01:07

cwallenpoole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!