Search code examples
actionscript-3functioncallbackevent-listenerdefault-parameters

AS3: EventListener callback overrides function's default parameters?


I discovered encountered something weird today. I have a function with a Boolean default parameter:

function f(boolean:Boolean=false) {
    trace(boolean);
}

Calling it normally gives what you would expect:

f(); //traces false

But now if I make my function the callback for an Event Listener, something weird happens:

addEventListener("test",f);
dispatchEvent(new Event("test")); //traces true

The same thing happens if I make it a callback for clicking on something:

mySprite.addEventListener(MouseEvent.CLICK,f); //Traces true on click

Can anyone explain what is going on? What is happening to my default value of false? When the event listener calls my function, it's not passing any parameters.


Solution

  • As Adobe said about the listener function :

    ... This function must accept an Event object as its only parameter and must return nothing

    So in your case, if you do :

    function f(boolean:Boolean = false) {
        trace(boolean);
    }
    
    stage.addEventListener(MouseEvent.CLICK, f);    // gives : true
    

    OR

    var event:MouseEvent = new MouseEvent(MouseEvent.CLICK);
    
    trace(Boolean(event));                      // gives : true
    
    f(event);                                   // gives : true
    

    You will get always the same result : true, because every time, your event var pass automatically to your f function and converted to Boolean and because it's not null you will get true :

    trace(Boolean(!null))                       // gives : true