我正在使用 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);
最佳答案
如何将 onYouTubePlayerAPIReady
定义为一个全局函数,就像 API 所期望的那样,然后从该函数内部调用您的 onPlayerReady
方法?代码示例:
window.onYouTubePlayerAPIReady = function () {
var args = Array.prototype.slice.call(arguments);
args.push(videos, locales);
videoTemplate.onPlayerReady.apply(videoTemplate, args);
};
并且您修改 onPlayerReady 方法的签名以按相同顺序接受参数
关于javascript - 在 JavaScript 中安全地定义公共(public)回调函数的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10974142/