Adding Parameters to addEventListener

February 20, 2009 by jared 

Here’s how you can easily add parameters to an event listener in AS3.

stage.addEventListener(MouseEvent.CLICK,
	function(e : MouseEvent) : void
	{
		fMyFunction(e, "hello world")
	},
	false , 0 , false);

function fMyFunction(e : MouseEvent, vMsg:String) : void
{
	trace(vMsg);
}

flash file logo Click here to download the sample.

Comments

5 Responses to “Adding Parameters to addEventListener”

  1. Evan M on March 20th, 2009 12:51 pm

    Yes! This answered my question perfectly! When I implemented the technique I got all my parameters and arguments back perfectly!
    Thanks!

  2. gary on April 7th, 2009 2:51 pm

    This script works great! I have been looking for a simple solution to do this and all the other posts i found involved creating custom classes or other overly complex approaches.

    Thanks for this simple solution.

    One question, though – can you tell me what last three values ‘false, 0, false’ represent?

  3. jared on April 7th, 2009 4:55 pm
  4. corfix on August 5th, 2009 11:54 pm

    While this solves problem of passing parameters to handler functions (which, imo, should be resolved within handler body!) it also rise quite an issue when you actually wants to remove this handler… Since you passed anonymous function there is no reference that could be passed to removeEventHandler method.

  5. Dave Bleeker on November 6th, 2009 9:01 am

    This is indeed one way to solve this, can be specially useful when tweening a filter.

    However, like corfix already mentioned, is that with function closures, there is (as far as I know) no way to remove the listener. This means that it might keep references to objects that will never be garbage collected, resulting in a memory leak, specially when you call a dynamic class more than once in your application. In worst case scenario this can even crash your browser.

    Nevertheless, with that in mind, it can be the best solution and save you a lot of time.

Feel free to leave a comment...
and oh, if you want a pic to show with your comment, go get a gravatar!