removeEventListener that was defined with an inline function

Removing an event Listener in ActionScript 3 or Flex that was defined with an inline function is a snap!

I love Event Listeners….”They’re the best”, as Nacho Libre would say. One thing I hated about them was that I always had to create a separate function for the function call. I tried to stay away from inline functions because it is important to clean up after yourself, so when you don’t need the function any longer, you should remove it. Until I stumbled upon this very simple technique, I was always disheartened every time I searched on Google, only to find, “Stay away from inline function in event listeners because there is No Way to remove them.”

Here is the solution:

this.addEventListener(Event.ENTER_FRAME, function cool(e:Event):void{
   this.removeEventListener(Event.ENTER_FRAME, cool);

That’s it! Just give your inline function a name. Then you can reference it later to remove the event listener in ActionScript 3


10 Comments (+add yours?)

  1. marcus
    Mar 15, 2010 @ 18:57:10

    Helped me out. Thanks.

  2. Vitor Cunha
    Jul 05, 2010 @ 18:38:24

    Thanks man!

  3. Alexander
    Nov 27, 2010 @ 01:53:45

    Sure, but often the so-called inline functions are anonymous. Yours in the example is not anonymous; it’s called “cool”.

  4. Anonymous
    Jun 24, 2011 @ 18:57:40

    I Did this in AS3 (Flash Builder)
    var onClick:Function = new Function();
    btnDel.addEventListener(MouseEvent.CLICK, onClick = function(event:MouseEvent):void
    e.currentTarget.removeEventListener(MouseEvent.CLICK, onClick);

    Thanks, Hope find this usefull.

  5. Anonymous
    Apr 27, 2012 @ 05:50:23

    Wow so handy! Thank you 🙂

  6. Tumiso
    May 29, 2013 @ 05:55:24

    Thanks man, this was quite helpful..thank you!!

  7. Anonymous
    Nov 21, 2013 @ 07:21:17

    Nice, worked like a charm

  8. Anonymous
    Feb 19, 2014 @ 18:37:22


  9. Anonymous
    Nov 18, 2014 @ 21:06:24


  10. Amer Mahdi
    Apr 26, 2018 @ 06:07:56

    thank you soooooooooooooooo much

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: