Coding Trick of the Day: Removing event listeners on naked functions

This is mainly an ActionScript coding trick. I think it works in JavaScript but I’m not sure.

Many time, you want an event listener that only gets called once, or being able to stop the listener after a particular condition. For instance, you need the ENTER_FRAME event on a bullet until it reaches its destination or goes offscreen. When that happens, you need to remove the event listener. However, if you’re lazy like me, you will not define your listener like this:

addEventListener(Event.ENTER_FRAME, functionName);

but like this:

addEventListener(Event.ENTER_FRAME, function(e:Event):void { .... } );

That’s called using a naked function. It’s just convenient and easier to do than defining a whole new function somewhere for that. Also, if your function is small and not really important, it improves readability.

The problems comes when you have to remove the listener, because you don’t have any function name to do this:

removeEventListener(Event.ENTER_FRAME, functionName);

Fortunately, there’s a trick to remove the event listener within the function itself. It goes like this:

addEventListener(Event.ENTER_FRAME,
     function(e:Event):void {
          if(condition) {
              e.currentTarget.removeEventListener(
                 e.type,arguments.callee);
          }
     });

This will make the event listener remove itself.

Advertisements

About jacklehamster

Technocraft and internet developer

Posted on June 25, 2013, in coding trick of the day, Flash and tagged , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: