Here’s a little class I wrote to easily bind keys to a specific function. It is a class with two static functions, bind and unbind, for obvious purposes. It takes care of the whole listener deal for you, all you need to do to bind a key to a specific function is:
Binder.bind("g", gotoAndPlay, _root, [6]);
That will execute _root.gotoAndPlay(6) when you hit g. The syntax for the function to apply is the same as the Function.apply syntax:
**Usage:
**[color=Purple]myFunction[/color].apply([color=Purple]thisObject[/color], [color=Purple]argumentsObject[/color]);
**
Parameters:
[color=Purple]thisObject[/color] The object that myFunction is applied to.[color=Purple]
argumentsObject**[/color] An array whose elements are passed to myFunction as parameters.
So in the example above, the function call would render as
gotoAndPlay.apply(_root, [6])
which is the same as
_root.gotoAndPlay(6);
Or, for any other function that takes more arguments:
theSum = sum.apply(null, [5,4,3,6,7]);
The sum function would then count up 5+4+3+6+7, and return the result to be stored in theSum. Because sum is a regular function and not a method, [color=Purple]**thisObject **[/color]is null.
Here’s the class code:
class Binder {
static var count:Number = 0;
static var objects:Array = new Array();
function Binder(){
}
static function bind(key:String, applyFunction:Function, applyObject:Object, applyParams:Array) {
for(var i=0;i<count;i++){
if(objects*.hitkey == key.toLowerCase()){
trace("Could not bind key "+key+": key already bound.");
return false;
}
}
var newListener = new Object();
newListener.hitkey = key.toLowerCase();
newListener.applyFunction = applyFunction;
newListener.applyObject = applyObject;
newListener.applyParams = applyParams;
Key.addListener(newListener);
newListener.onKeyDown = function(){
var pressedKey:String = String.fromCharCode(Key.getCode()).toLowerCase();
if(pressedKey == this.hitkey){
this.applyFunction.apply(this.applyObject, this.applyParams);
}
}
objects[count++] = newListener;
}
static function unbind(key:String):Void {
for(var i=0;i<count;i++){
var curListener:Object = objects*;
if(curListener.hitkey.toLowerCase() == key.toLowerCase()){
Key.removeListener(curListener);
objects.splice(i,1);
count--;
}
}
}
}
I’ve attached the .as file