YouTube iframe API - 从onPlayerStateChange事件处理程序中引用Javascript对象

时间:2016-06-11 17:44:27

标签: javascript iframe youtube

这是我的HTML文件中的工作播放器。我希望YT.PlayerState.ENDED a.k.a。event.data == 0的处理程序能够引用存储videoID的客户端Javascript对象(booth),但booth未定义。做这样的事情的正确方法是什么?

function onPlayerStateChange(event) {
  if (event.data == -1) {
    player.playVideo();
  }
  if (event.data == 0) {
    alert("This alert pops up");
    alert(window.booth);
    // Undefined -- even though "booth" is already instantiated in linked JS file

    /*
    window.booth.cue.index++;
    event.target.loadVideoById(window.booth.cue.list[booth.cue.index].id);
    */
  }
}

以下是整个Javascript file - 第16行socket.on('boothCreated'...booth实例化的处理程序,只有在此之后才是玩家创建的 - 所以在我看来,玩家应该可以参考这个。

1 个答案:

答案 0 :(得分:1)

我不需要再看了,链接的JS文件的开头说明了所有内容:

window.onload = function () { // beginning of function closure
    var user = null; // these are private variables inside the function
    var booth = null; // these are private variables inside the function
    // etc...

如果您希望从window.booth等可以看到这些变量,那么您需要这样做:

window.onload = function () { // beginning of function closure
    window.user = null; // these are now public
    window.booth = null; // these are now public
    // etc...

你只是把它们变成了私人的,因此从“外部世界”看不到它。

或者如果你想在保密的同时使用它们,那么你需要以某种方式加入文件并将onPlayerStateChange函数放在window.onload = function() { ...内。