Avg. Rating 4.5

Problem

Event Listeners are a little "static-y" for my liking.

Solution

I found a way to recycle functions by passing variables. The key is to have a Function return a MouseEvent Function.

Detailed explanation

b1_btn.addEventListener(MouseEvent.CLICK, myHandler("zero"));
b2_btn.addEventListener(MouseEvent.CLICK, myHandler("one"));
b3_btn.addEventListener(MouseEvent.CLICK, myHandler("two"));

function myHandler(myString:String):Function {
    var myHandlerReturn:Function = function(evt:MouseEvent){
         trace(myString)
    };
    return myHandlerReturn;
}

///////////////////////////////////////////////////////////////////////////
// Practical Example ( URL links )
///////////////////////////////////////////////////////////////////////////

btn1.addEventListener(MouseEvent.CLICK, myLink('www.ImCool.com'));
btn2.addEventListener(MouseEvent.CLICK, myLink('www.ThisIsAwesome.com'));
btn3.addEventListener(MouseEvent.CLICK, myLink('www.kickAss.com'));

function myLink(link:String):Function {
    var myLinkReturn:Function = function(evt:MouseEvent){
        navigateToURL(new URLRequest(link)) };
    return myLinkReturn;
}


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes