How to reuse event functions

This is just a quick tip I picked up while working with a teamate.

I often came across the case that I would have to make a function exactly the same as the function that was called from an event listener because the function called from the listener would have an event as argument but the same function that I wanted to call but not from an event didn’t.

I had found multiple ways around that problem; I would make another function that both previous function would call or I would create only the listener function and when I wanted to call it from elswhere I would pass it an empty event that I would create just for it. Both these solution appeared unelegant to me.

That’s when I saw this in my teamate code:

// let say your listener is this
myButton.addEventListener(Event.COMPLETE, _activateElement, false, 0, true);
 
//your function looks like this
private function _activateElement(event:Event = null):void{
  //do something that doesn't require the event
}
 
//so from anywhere you can just call the same function like this
_activateElement();

By simply giving a default value of null to the argument, you can now reuse this function both in the context of an event listener and anywhere else.

, ,

  1. #1 by Eric Cancil - January 15th, 2009 at 17:53

    It is generally better practice to have eventhandlers be exactly that, event handlers, not methods that you could use alternatively. You then write utility methods that both your event handlers and other things can call. Just parametrize the utility methods! This also makes a lot of sense when it comes to unit testing so you can test methods without having the events triggered.

  2. #2 by zedia.net - January 16th, 2009 at 15:45

    I see your point, but I find this useful in a lot of case. Most projects I deal with won’t even go throught unit testing so that not one of my concern. I just find this solution more elegant.

  3. #3 by 5566 - January 19th, 2009 at 02:38

    I do that too, :) .

    Alternatively, you can fake an event.
    myButton.dispatchEvent(new Event(Event.COMPLETE));

  4. #4 by Ryan - March 23rd, 2009 at 16:48

    Awesome… Just the answer I was looking for.

  5. #5 by Sekler - December 14th, 2009 at 21:26

    I was looking for this. Thank you very much for sharing it!

  6. #6 by Locotes - March 22nd, 2010 at 06:54

    Thanks. Could have come up with it myself, but somehow I didn’t. :) Already knew the faking event option, but it’s just not that elegant.

  7. #7 by reido113 - July 28th, 2010 at 11:49

    Very Nice. I Thank You for this.
    …just null the event… Duhhhhh :)

(will not be published)
Subscribe to comments feed
  1. No trackbacks yet.