2016-04-28 74 views
0

我有一個YouTube播放器API的問題。Youtube javascript api,pjax,如何重載onYouTubeIframeAPIReady();

我把這個JS代碼:

function onYouTubeIframeAPIReady() { 
    var podcast = document.getElementById('podcast') 
    var player = new YT.Player(document.getElementById('podcast')); 
    player.addEventListener('onStateChange', function(e) { 
    if (e.data === 1) { 
     alert("play"); 
    } 
    }); 
}; 

這個HTML代碼:

<iframe id="podcast" type="text/html" width="720" height="405" 
src="https://www.youtube.com/embed/XXXXXX?cc_load_policy=1&enablejsapi=1&theme=light" 
frameborder="0" allowfullscreen> 

的問題是,我用的是pjax系統,所以全球性的javascript代碼,當我瀏覽不重裝。 因此,當pjax:成功時,我重新加載了我的JavaScript代碼的一部分。我試過這樣的:

$(document).on('pjax:success', function() { 
    onYouTubeIframeAPIReady(); 
} 

但它不起作用。我的問題是如何重載onYouTubeIframeAPIReady();當它必須被定義爲全球時,因爲它有onYouTubeIframeAPIReady function is not calling

回答

0

當我的播放器被定義時,我不使用onYoutubePlayerAPIReady。這是我找到的最好的解決方案,它的工作原理。

var player = { 
    playVideo: function(container, videoId) { 
     if (typeof(YT) == 'undefined' || typeof(YT.Player) == 'undefined') { 
      window.onYouTubePlayerAPIReady = function() { 
       player.loadPlayer(container, videoId); 
      }; 
      $.getScript('//www.youtube.com/player_api'); 
     } else { 
      player.loadPlayer(container, videoId); 
     } 
    }, 
    loadPlayer: function(container, videoId) { 
     window.myPlayer = new YT.Player(container, 
      height: 200, 
      width: 200, 
      videoId: videoId, 
     }); 
    } 
}; 


var containerId = 'podcast'; 
var videoId = '<%= @youtube_id %>'; 
player.playVideo(containerId, videoId);