Skip to content

Commit 64c952f

Browse files
committed
Tidy up YouTube code
1 parent fdf2fa3 commit 64c952f

1 file changed

Lines changed: 15 additions & 11 deletions

File tree

src/players/YouTube.js

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import Base from './Base'
55

66
const SDK_URL = '//www.youtube.com/iframe_api'
77
const SDK_GLOBAL = 'YT'
8+
const SDK_GLOBAL_READY = 'onYouTubeIframeAPIReady'
89
const MATCH_URL = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/
910
const PLAYER_ID = 'youtube-player'
1011
const BLANK_VIDEO_URL = 'https://www.youtube.com/watch?v=GlCmAC4MHek'
@@ -14,14 +15,14 @@ const DEFAULT_PLAYER_VARS = {
1415
showinfo: 0
1516
}
1617

17-
let count = 0
18+
let playerIdCount = 0
1819

1920
export default class YouTube extends Base {
2021
static displayName = 'YouTube'
2122
static canPlay (url) {
2223
return MATCH_URL.test(url)
2324
}
24-
playerId = PLAYER_ID + '-' + count++
25+
playerId = PLAYER_ID + '-' + playerIdCount++
2526
componentDidMount () {
2627
if (!this.props.url && this.props.youtubeConfig.preload) {
2728
this.preloading = true
@@ -34,8 +35,8 @@ export default class YouTube extends Base {
3435
return Promise.resolve(window[SDK_GLOBAL])
3536
}
3637
return new Promise((resolve, reject) => {
37-
const previousOnReady = window.onYouTubeIframeAPIReady
38-
window.onYouTubeIframeAPIReady = function () {
38+
const previousOnReady = window[SDK_GLOBAL_READY]
39+
window[SDK_GLOBAL_READY] = function () {
3940
if (previousOnReady) previousOnReady()
4041
resolve(window[SDK_GLOBAL])
4142
}
@@ -60,7 +61,10 @@ export default class YouTube extends Base {
6061
width: '100%',
6162
height: '100%',
6263
videoId: id,
63-
playerVars: { ...DEFAULT_PLAYER_VARS, ...this.props.youtubeConfig.playerVars },
64+
playerVars: {
65+
...DEFAULT_PLAYER_VARS,
66+
...this.props.youtubeConfig.playerVars
67+
},
6468
events: {
6569
onReady: this.onReady,
6670
onStateChange: this.onStateChange,
@@ -69,12 +73,12 @@ export default class YouTube extends Base {
6973
})
7074
})
7175
}
72-
onStateChange = state => {
73-
const YT = window[SDK_GLOBAL]
74-
if (state.data === YT.PlayerState.PLAYING) this.props.onPlay()
75-
if (state.data === YT.PlayerState.PAUSED) this.props.onPause()
76-
if (state.data === YT.PlayerState.BUFFERING) this.props.onBuffer()
77-
if (state.data === YT.PlayerState.ENDED) this.props.onEnded()
76+
onStateChange = ({ data }) => {
77+
const { PLAYING, PAUSED, BUFFERING, ENDED } = window[SDK_GLOBAL].PlayerState
78+
if (data === PLAYING) this.props.onPlay()
79+
if (data === PAUSED) this.props.onPause()
80+
if (data === BUFFERING) this.props.onBuffer()
81+
if (data === ENDED) this.props.onEnded()
7882
}
7983
play () {
8084
if (!this.isReady || !this.player.playVideo) return

0 commit comments

Comments
 (0)