我正在使用 YouTube iFrame API 在页面上嵌入许多视频。此处的文档:https ://developers.google.com/youtube/iframe_api_reference#Requirements
总之,您可以使用以下代码段异步加载 API:
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
加载后,API 会触发预定义的回调函数onYouTubePlayerAPIReady
。
有关其他上下文:我在 Google Closure 中为此定义了一个库文件。我提供了一个命名空间:goog.provide('yt.video');
然后我使用goog.exportSymbol
以便 API 可以找到该函数。这一切都很好。
我的挑战是我想将 2 个变量传递给回调函数。如果不在对象的上下文中定义这两个变量,有什么方法可以做到这一点window
?
goog.provide('yt.video');
goog.require('goog.dom');
yt.video = function(videos, locales) {
this.videos = videos;
this.captionLocales = locales;
this.init();
};
yt.video.prototype.init = function() {
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
};
/*
* Callback function fired when YT API is ready
* This is exported using goog.exportSymbol in another file and
* is being fired by the API properly.
*/
yt.video.prototype.onPlayerReady = function(videos, locales) {
window.console.log('this :' + this); //logs window
window.console.log('this.videos : ' + this.videos); //logs undefined
/*
* Video settings from Django variable
*/
for(i=0; i<this.videos.length; i++) {
var playerEvents = {};
var embedVars = {};
var el = this.videos[i].el;
var playerVid = this.videos[i].vid;
var playerWidth = this.videos[i].width;
var playerHeight = this.videos[i].height;
var captionLocales = this.videos[i].locales;
if(this.videos[i].playerVars)
var embedVars = this.videos[i].playerVars;
}
if(this.videos[i].events) {
var playerEvents = this.videos[i].events;
}
/*
* Show captions by default
*/
if(goog.array.indexOf(captionLocales, 'es') >= 0) {
embedVars.cc_load_policy = 1;
};
new YT.Player(el, {
height: playerHeight,
width: playerWidth,
videoId: playerVid,
events: playerEvents,
playerVars: embedVars
});
};
};
为了初始化这一点,我目前在自执行匿名函数中使用以下内容:
var videos = [
{"vid": "video_id", "el": "player-1", "width": 640, "height": 390, "locales": ["es", "fr"], "events": {"onStateChange": stateChanged}},
{"vid": "video_id", "el": "player-2", "locales": ["es", "fr"], "width": 640, "height": 390}
];
var locales = ['es'];
var videoTemplate = new yt.video(videos, locales);