0

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.

BladePoint
  • 632
  • 5
  • 16

3 Answers3

1

I don't think the listener will use the default parameter. You could use a small inline function to wrap the function you want to get called:

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

addEventListener("test", function(e:Event):void { f() } );
dispatchEvent(new Event("test")); //traces false
0

when u dispatch a event, your listener function would accept parameter from upstream, then the parameter convert to boolean

ssskip
  • 259
  • 1
  • 6
0

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
akmozo
  • 9,829
  • 3
  • 28
  • 44