This was problematic enough for my application that I made a sort of event emitting proxy for the YouTube player object.
Usage (where player is your YouTube Iframe API Player instance):
const playerEventProxy = new YouTubeEventProxy(player);
function handleStateChange(e) {
// …
}
playerEventProxy.on('stateChange', handleStateChange);
playerEventProxy.off('stateChange', handleStateChange);
Class:
/**
* YouTubeEventProxy
* Quick and dirty hack around broken event handling in the YouTube Iframe API.
* Events are renamed, dropping the "on" and lower-casing the first character.
* Methods 'on', 'off', etc. are supported, as-provided by event-emitter.
* See also: https://stackoverflow.com/q/25880573/362536
*
* Brad Isbell <[email protected]>
* License: MIT <https://opensource.org/licenses/MIT>
*/
import EventEmitter from 'event-emitter';
// From: https://developers.google.com/youtube/iframe_api_reference#Events
const ytApiEvents = [
'onApiChange',
'onError',
'onPlaybackQualityChange',
'onPlaybackRateChange',
'onReady',
'onStateChange'
];
export default class YouTubeEventProxy extends EventEmitter {
constructor(player) {
super();
this.player = player;
ytApiEvents.forEach((eventName) => {
player.addEventListener(
eventName,
this.emit.bind(
this,
eventName.substr(2, 1).toLowerCase() + eventName.substr(3)
)
);
});
}
}
This is the event-emitter package: https://www.npmjs.com/package/event-emitter