(function () { var readyListeners = []; var readyPlayers = []; var PlayerJsReady = window.PlayerJsReady = {}; /** * Add listener for a 'ready' event coming from a specified element. * * @todo This should be optimized so that performance doesn't degrade if * many iframes and many event listeners are used. * * @param {DOMElement} iframeEl iFrame element from which to listen for * 'ready' event * @param {Function} callback Listener's callback */ PlayerJsReady.listen = function (iframeEl, callback) { /** * Player inside requested iframe might have already called ready * event and in that case we will invoke callback immediately. */ for (var i in readyPlayers) { if (iframeEl.contentWindow === readyPlayers[i].source) { return callback(readyPlayers[i].message); } } /** * If player inside requested iframe is not yet ready then we will * register a listener for 'ready' event. */ readyListeners.push({target: iframeEl, callback: callback}); }; /** * Calls all listeners of given 'ready' event. * * @param {object} ready 'ready' event */ function callReadyListeners(ready) { for (var i in readyListeners) { if (readyListeners[i].target.contentWindow === ready.source) { readyListeners[i].callback(ready.message); } } } /** * Listen to 'ready' event from player.js and call all of its listeners. */ window.addEventListener('message', function (e) { var message = PlayerJsCommon.getPlayerJsMessage(e); var ready; if (!message) { return; } if (message.event === 'ready' && message.value && message.value.src) { console.log('Ready'); ready = {source: e.source, message: message}; readyPlayers.push(ready); callReadyListeners({source: e.source, message: message}); } }); }());