apscience
apscience

Reputation: 7273

AS3 Events and passing parameters

I want to pass parameters when an event is triggered. My function:

private function keyChange(e:KeyboardEvent, setValue:Boolean):void

so that I can use the same function to set if a key is up or down. How would I write the event listener? I tried:

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyChange(,true));

however that didn't work. Is this possible? Thanks

Upvotes: 0

Views: 2825

Answers (4)

user1837285
user1837285

Reputation:

Totally possible. Easy and simple:

private function keyChange(setValue:Boolean):Function {
  return function(e:KeyboardEvent):void {
    // Now you have both "e" and "setValue" here
  }
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyChange(true));

What if you want to remove the listener later? Just take keyChange() out:

var functionKeyChange:Function = keyChange(true);
stage.addEventListener(KeyboardEvent.KEY_DOWN, functionKeyChange);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, functionKeyChange);

If you find this solution interesting, see this answer.

Upvotes: 0

Swati Singh
Swati Singh

Reputation: 1863

This is the simplest way to find your solution,

 stage.addEventListener(KeyboardEvent.KEY_DOWN,function(e:MouseEvent):void{keyChange(e,true)});

Upvotes: 0

fenomas
fenomas

Reputation: 11139

The straightforward way is to examine the events inside your event handler.

stage.addEventListener(KeyboardEvent.KEY_UP, keyChange);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyChange);

private function keyChange(e:KeyboardEvent) {
    if (e.type == KeyboardEvent.KEY_DOWN) {
         // ... handle key down, etc...
    }
}

You could also do it by passing addEventListener an inline function that passes the parameter you want, or maybe do something tricky with closures, but it wouldn't gain you anything over the above way.

Upvotes: 2

Joe
Joe

Reputation: 82654

Like so:

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyChangeHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyChangeHandler);

...

private function keyChangeHandler(e:KeyBoardEvent):void
{
    var keyDown:Boolean = e.type == KeyBoardEvent.KEY_DOWN;

    ...
    // Do stuff
}

However if you want to pass parameters, you need to use a custom event:

public class KeyBoardActionEvent extends KeyBoardEvent
{
    public var shouldSetValue:Boolean;
    public function KeyBoardActionEvent(setValue:Boolean, type:String, bubbles:Boolean = false, cancelable:Boolean = false):void
    {
        shouldSetValue = setValue;
        super(type, bubbles, cancleable);
    }
}

Upvotes: 1

Related Questions