PlayerJsReady.js
2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
(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});
}
});
}());