flash as3仅在定义函数内的实例时才运行函数

时间:2011-03-03 21:11:38

标签: flash actionscript-3 actionscript load undefined

我有一种情况,在加载我的swf时,我向舞台添加一个事件监听器来监听键盘命令。其中一个是听空格键,如果按下它,它应该播放一个电影。问题是,该影片直到后来才被加载,这取决于其他用户的交互,因此,在加载之前,对它的引用将是未定义的。但是如果我等待并且仅在加载电影时添加关键命令的监听器,那么我就不能将监听器用于其他键盘命令,例如RIGHT或LEFT,这些按钮可以让你首先进入电影。有没有办法添加条件或某些东西,以防止如果尚未定义视频执行该代码?这是我的代码:

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);

function togglePause(event:MouseEvent):void {
     video.videoPaused = !video.videoPaused; //video is undefined initially so this throws errors.
}

function keyPressedDown(event:KeyboardEvent):void {
     switch (key) {
        case 32: //Spacebar
        //togglePause();
     }
}

function loadVideo(){ //called based on user interactions which happen later on
    var video:VideoLoader = new VideoLoader(project_array[cp].project_display_files[0], {name:"myVideo", container:this, bgColor:0x000000, autoPlay:false, volume:1,onComplete:vidLoaded});
    video.load(); //currently set up for only one video ([0])-->
}

2 个答案:

答案 0 :(得分:1)

要检查变量是否已定义,只需使用if(typeof myVar == 'undefined')if(myVar === undefined)

要检查变量是否已定义但未分配值,请使用以下命令:

var myVar:MyClass;
if(myVar === null)
    ...

现在转到您的特定情况,如果在video函数/方法中声明loadVideo变量,它将永远不会在该范围之外可用。因此,您需要在更高级别声明它才能使用它。

其他错误:
- 在togglePause中,参数应该是可选的,以允许手动调用功能
- 在keyPressedDown中,未定义变量key

尝试此更改:

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);

var video:VideoLoader;

function togglePause(event:MouseEvent = null):void {
    if(video)
        video.videoPaused = !video.videoPaused; //video is undefined initially so this throws errors.
}

function keyPressedDown(event:KeyboardEvent):void {
     switch (event.charCode) {
        case 32: //Spacebar
            togglePause();
            break; // not necesary here, but good practice to add it!
     }
}

function loadVideo(){ //called based on user interactions which happen later on
    video = new VideoLoader(project_array[cp].project_display_files[0], {name:"myVideo", container:this, bgColor:0x000000, autoPlay:false, volume:1,onComplete:vidLoaded});
    video.load(); //currently set up for only one video ([0])-->
}

免责声明:未经测试,但它可能会起作用,或至少接近工作。

的问候,
艾琳

答案 1 :(得分:0)

你可以在那里扔一个try / catch来照顾它。效率不高,但在这种情况下,它不会造成任何伤害:

try {
 switch (key) {
    case 32: //Spacebar
    //togglePause();
 }
} catch (e:Error){
    // trace(e.message) // if it's needed, otherwise just fail silently
}

或者,你可以定义一个布尔变量,如:

var isLoaded:Boolean = false;

然后,有一个加载监听器,当它触发时,更改isLoaded = true,然后:

switch (key) {
    case 32: //Spacebar
    if (isLoaded){
      //togglePause();
    }
}