/* * Copyright(c) 2007 Yuki KODAMA [endflow.net] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ /** * KeyIfクラス * * @description キーイベントハンドラを生成してくれるクラス。 * @author Yuki KODAMA [endflow.net] * @since Flash Player 8 (ActionScript 2.0) * @version 0.2.0 * @link http://snippets.libspark.org/trac/wiki/kuy/KeyIf * @history [0.0.0] 200?-??-??: 初版 * [0.1.0] 2007-05-27: 改良。Snippets Projectに公開。 * [0.1.1] 2007-09-14: ちょっとリファクタリング&コメント追加。 * [0.2.0] 2007-09-15: Keyクラスで定義されていないキーもキーコードで指定可能にした。 */ class net.endflow.util.KeyIf { /** * インスタンス化することはできません。 */ private function KeyIf() {} /** * @param info : Object - キーイベントハンドラを生成するためのObject * @return Function - 生成されたキーイベントハンドラ * @usage * Key.addListener(this); * this.onKeyDown = KeyIf.f({ * HOME: function(){trace('HOME')}, * UP: {PGUP: function(){trace('UP/PGUP')}}, * DOWN: {PGDN: function(){trace('DOWN/PGDN')}}, * LEFT: [function(){trace('LEFT#1')}, function(){trace('LEFT#2')}], * RIGHT: [function(){trace('RIGHT#1')}, function(){trace('RIGHT#2')}, function(){trace('RIGHT#3')}] * SPACE: {CONTROL: function(){trace('SPACE/CTRL')}}, * _90: function(){trace('Z')} * }); * */ public static function f(info:Object):Function { // 複数割り当て指定のオブジェクトを展開 for(var k in info) { if((typeof(info[k]) == 'object') && !(info[k] instanceof Array)) { // 再帰(一番奥の関数リテラルまで) info[k] = (function(root, info){ for(var k in info) { if(typeof(info[k]) == 'function') { return (root[k] = info[k]); } else if(typeof(info[k]) == 'object') { return (root[k] = arguments.callee(root, info[k])); } } }).call(null, info, info[k]); } } // 並列実行指定の配列を単一関数に置き換え for(var k in info) { if(info[k] instanceof Array) { info[k] = function(){ for(var i = 0; i < info[k].length; i++) { info[k][i](); } } }; } // ハンドラ関数の生成 return function() { for(var k in info) { if((k.charAt(0) == "_" && parseInt(k.substr(1)) == Key.getCode()) || (Key[k] == Key.getCode())) { info[k](); } } }; } }