しかしながら、
その通りにやってもエラーが出てしまうのだ!
具体的には、
未定義の可能性が高いプロパティ keyCode
というエラーが出てしまいます。
これはコンパイル時のチェックがstrictモードになっていると表示されるエラーなのですが、strictでなくても動かないモノは動かない。
このエラーの原因を修正するには、ヘルプ中で
function keyPressed(event:Event):void {
// むにゃむにゃ
}
と記述されていたところを
function keyPressed(event:KeyboardEvent):void {
// むにゃむにゃ
}
とします。
keyCodeプロパティは、KeyboardEventクラスのプロパティというわけです。
以下、修正後のスクリプト。
■helloWorld.fla
1フレーム目に
・ダイナミックテキスト「mainText」
・テキスト入力「textIn」
を配置。
1フレーム目のフレームスクリプト
mainText.border = true;
textIn.border = true;
//
var myGreeter:Greeter = new Greeter();
mainText.text = myGreeter.sayHello("");
//
textIn.addEventListener(KeyboardEvent.KEY_UP, keyPressed);
//
function keyPressed(event:KeyboardEvent):void {
if (event.keyCode == Keyboard.ENTER) {
mainText.text = myGreeter.sayHello(textIn.text);
}
}
■Greeter.as
package {
public class Greeter {
/**
* Defines the names that should receive a proper greeting.
*/
public static var validNames:Array=["Sammy","Frank","Dean"];
/**
* Builds a greeting string using the given name.
*/
public function sayHello(userName:String=""):String {
var greeting:String;
if (userName == "") {
greeting="Hello. Please type your user name, and then press the Enter key.";
} else if (validName(userName)) {
greeting="Hello, " + userName + ".";
} else {
greeting="Sorry, " + userName + ", you are not on the list.";
}
return greeting;
}
/**
* Checks whether a name is in the validNames list.
*/
public static function validName(inputName:String=""):Boolean {
if (validNames.indexOf(inputName) > -1) {
return true;
} else {
return false;
}
}
}
}
ちなみに、パブリッシュ時のエラーコード一覧はこちら。
■ この他のFlash関連TIPS