Category Archives: coding trick of the day

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:

     function(e:Event):void {
          if(condition) {

This will make the event listener remove itself.


Coding Trick of the Day: The Comment Swapper

On many occasion when I am programming, I want to test out a piece of code, then try another one, and go back and forth between the two. Sometimes, it’s to compare performance, other times I just want to compare the behaviors (It happens very often when testing animation).

It can be tedious to constantly comment/uncomment code. But thanks to the “Comment Swapper”, I can do this in one keystroke!

1   //*******
2   object.foobar1();
3   /*/
4   object.foobar2();
5   //*/

Try it out: by deleting/adding the slash (/) character at the beginning of line 1, you can instantly swap between the two chunks of code.