May
05
2008

Using an anonymous inline function when adding an event listener

I show here how to use an inline event handler function when creating an event listener and how to remove it later.

This is a real timesaver when you want to add small function as a handler for an event.

myButton_btn.addEventListener(MouseEvent.CLICK, 
       function(e:MouseEvent){trace(e.currentTarget.name+" was just clicked!");});


If you want to remove that listener later, you can only do that when the listener has been called:

myButton_btn.addEventListener(MouseEvent.CLICK, 
   function(e:MouseEvent)
   {
      trace(e.currentTarget.name+" was just clicked!");
      //removing anonymous listener
      e.currentTarget.removeEventListener(e.type, arguments.callee);
   });

AS3 Tips

Follow me on Twitter