PDA

View Full Version : Calling a function used on eventListeners elsewhere.



Mistermind
June 25th, 2009, 03:42 PM
Hello there fellow wizards!

I got a pickle for you:
I have a function that is currently connected to an event listener like this:

loginButton.addEventListener(MouseEvent.CLICK, loginOnClick, false, 0, true);
function loginOnClick(event:MouseEvent):void{
// Login code.
}

Right now I'd also like to call that same function using the ENTER from a keyboard since loginOnClick doesn't use the parameter received (event:MouseEvent). So I did this:

function keyboardListener(event:KeyboardEvent):void{
if (loginButton){
if (event.keyCode == Keyboard.ENTER && loginButton.enabled) {
loginOnClick(); // Generates an error because it doesn't have a parameter.
}
}
usernameTextField.addEventListener(KeyboardEvent.K EY_DOWN,keyboardListener);

Problem is, of course, AS3 doesn't let you call a function with the incorrect number of parameters or types.
I tried following senocula's tutorials on functions and parameters but they don't seem to work on this very specific issue considering the parameter is an event reference.

Is there a solution for this or do I have to make a new function with the same code just for that?

Cheers!

BoppreH
June 25th, 2009, 03:52 PM
Both KeyboardEvent and MouseEvent extends the Event class, so just use

loginButton.addEventListener(MouseEvent.CLICK, login, false, 0, true);
usernameTextField.addEventListener(KeyboardEvent.K EY_DOWN,login);
function login(event:Event):void{
if (!(event is KeyboardEvent && KeyboardEvent(event).keyCode == Keyboard.ENTER && loginButton.enabled))
return
// Login code.
}

mikechambers
June 25th, 2009, 06:21 PM
I would move your login functionality to a separate function, and then call that function from the event handlers for the mouse and keyboard events.

mike chambers

mesh@adobe.com

999
June 25th, 2009, 06:25 PM
loginOnClick(null);

JonnyR
June 26th, 2009, 02:48 AM
Mike Chambers (Good to see you on here Mike, looing forward to your FOTB talk!) has the right approach, by moving the login code into it's own method call you will keep the code clear and consise without repeating yourself.

Felixz
June 26th, 2009, 04:42 AM
loginOnClick(null);or
function loginOnClick(event:MouseEvent = null):void {