我有这个Backbone App,我希望在视图中显示来自youtube的视频。我通过API和模型动态获取youtube视频ID。到现在为止还挺好。 Youtube播放器会被渲染,但播放器会给我一个错误,表明它没有识别VideoID,即使我在console.log中调用video_id,它也会返回正确的video_id。
所以我的视图看起来像这样:
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();
}
}
有谁知道这里可能出现什么问题?请帮忙......
提前致谢
答案 0 :(得分:1)
您需要绑定上下文:
window.onYouTubeIframeAPIReady = _.bind(function() {
player = new YT.Player('vid', {
height: '390',
width: '640',
videoId: this.video_youtube_id,
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
})
}, this);