PDA

View Full Version : AS3 function call from multiple locations.



worthington747
January 19th, 2008, 10:38 AM
I am new to AS3 and have noticed that calling a function from a mouse event requires just that event as a parameter in the function declaration
function doSomething (evt:MouseEvent):void{}
I would like to call the same function from different places like so
function doSomething ():void{
trace("doSomething")
}
box.addEventListener(MouseEvent.CLICK,doSomething) ;
doSomething();
//
Without getting the output
ArgumentError: Error #1063: Argument count mismatch on doSomething_fla::MainTimeline/doSomething(). Expected 0, got 1.
When the box is clicked.

Thanks in advanced.

neznein9
January 19th, 2008, 11:08 AM
The 'correct' way to do it:



box.addEventListener(MouseEvent.CLICK,doSomethingH elper) ;

function doSomethingHelper(e:MouseEvent):void{
doSomething();
}

doSomething();

The hack:
Take advantage of the fact that you're not doing anything with that event (so it might as well be null) and put in a default value.



function doSomething(e:Event = null):void{}

Dazzer
January 19th, 2008, 12:05 PM
Or you could write another function with zero parameters, and then call it from within the event handler.

Felixz
January 19th, 2008, 02:15 PM
well he wanted:
addEventListener(MouseEvent.CLICK,doSomething) ;
function doSomething(event:MouseEvent):void
doSomething(null);or:
addEventListener(MouseEvent.CLICK,doSomething) ;
function doSomething(event:MouseEvent=null):void
doSomething();

worthington747
January 19th, 2008, 02:20 PM
I never expected so many responses to quickly.

You've all done a superb job answering my question.

dail
January 19th, 2008, 03:59 PM
You can use the ...rest parameter for this as well, or a wildcard for your params, args:*

Eg;
function doSomething (...args):void{
trace("doSomething")
}
box.addEventListener(MouseEvent.CLICK,doSomething) ;
doSomething();

OKtrust
June 23rd, 2010, 10:28 AM
Yeah !
by this way, I can do something went current frame enter a frame

for example

I write this on a frame

function close_pop(e:Event=null)
{
//do something
}
close_pop();

if I dont write =null it will fail
Many thanks