Question

I have a Backbone App where I have a View in which I want to display a youtube player:

so in my View, in afterRender - I did this:

afterRender: function() {
              var tag = document.createElement('script');

              tag.src = "https://www.youtube.com/iframe_api";
              var firstScriptTag = document.getElementsByTagName('script')[0];
              firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);


              var player;
              function onYouTubeIframeAPIReady() {
                player = new YT.Player('vid', {
                  height: '390',
                  width: '640',
                  videoId: '',
                  events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                  }
                });
              }

              function onPlayerReady(event) {
                event.target.playVideo();
              }

              var done = false;
              function onPlayerStateChange(event) {
                if (event.data == YT.PlayerState.PLAYING && !done) {
                  setTimeout(stopVideo, 6000);
                  done = true;
                }
              }
              function stopVideo() {
                player.stopVideo();
              }
}

But its not rendering anything but I also dont get errors and in my console I can see that Youtube API is loaded... So what am I doing wrong here?

Please help..

Était-ce utile?

La solution 2

By changing

function onYouTubeIframeAPIReady() {
 // ...
}

into

window.onYouTubeIframeAPIReady = function() {
 // ...
}

It now works! Found the clue here Youtube iframe api not triggering onYouTubeIframeAPIReady

Autres conseils

See this related question: Youtube iframe api not triggering onYouTubeIframeAPIReady

I think the problem is that your onYouTubeIframeAPIReady function needs to be declared globally, not nested inside another function. (In your code, it's only defined within the scope of the afterRender method.)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top