Question

I have this Backbone App where I want display videos from youtube in a view. I fetch the youtube video id dynamically through an API and a Model. So far so good. The Youtube Player gets rendered, but the Player gives me an error which indicates that it didnt recognize the VideoID even though when I console.log the video_id, it returns the correct video_id.

So my View looks like this:

beforeRender: function() {
    var artistvideosModel = new ArtistVideos.ArtistVideosModel();
    artistvideosModel.artist_id = this.artist_id;
    artistvideosModel.video_youtube_id = this.video_youtube_id;
    artistvideosModel.fetch();
},

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;
  window.onYouTubeIframeAPIReady = function() {
    player = new YT.Player('vid', {
      height: '390',
      width: '640',
      videoId: this.video_youtube_id,
      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();
  }
}

Does anyone know what could be the issue here? Please help...

Thanks in advance

Was it helpful?

Solution

You need to bind the context:

window.onYouTubeIframeAPIReady = _.bind(function() {
  player = new YT.Player('vid', {
    height: '390',
    width: '640',
    videoId: this.video_youtube_id,
    events: {
      onReady: onPlayerReady,
      onStateChange: onPlayerStateChange
    }
 })
}, this);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top