I created a class of youtube api because I need it in multiple files but when I trying to access the getPlayerState() then its giving me error of that it is not a function but when I console.log
I see in the list getPlayerState(). below is the code of my youTubeManager.js
// eslint-disable-next-line no-unused-vars
class YouTubeManager {
constructor() {
this.player = null;
this.playerState = null;
this.readyPromise = this.initYouTubeAPI();
}
initYouTubeAPI() {
return new Promise((resolve, reject) => {
// Initialize YouTube API
window.onYouTubeIframeAPIReady = () => {
this.createPlayer();
resolve();
};
const tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
tag.onerror = () => reject(Error('Error loading YouTube API'));
document.getElementsByTagName('head')[0].appendChild(tag);
});
}
createPlayer() {
// Create the YouTube player
// eslint-disable-next-line no-undef
this.player = new YT.Player('another-love', {
events: {
'onStateChange': this.onPlayerStateChange.bind(this)
}
});
}
// eslint-disable-next-line no-unused-vars
onPlayerStateChange(event) {
// eslint-disable-next-line no-undef
if (event.data === YT.PlayerState.PLAYING) {
State = event.data;
// eslint-disable-next-line no-console
console.log("video is playing");
} else if (event.data === 2) {
State = event.data;
// eslint-disable-next-line no-console
console.log("video is paused");
}
}
}
const youtubeManager = new YouTubeManager();
export default youtubeManager;
In here I am calling it but I am trying to access the playerState. its giving me error
// eslint-disable-next-line no-unused-vars
define(['jquery', './youTubeManager'], function($, youtubeManager)
{
youtubeManager.readyPromise.then(() => {
// eslint-disable-next-line no-unused-vars
const player = youtubeManager.player; // Access the player from the instance;
// eslint-disable-next-line no-console
console.log(youtubeManager);
}).catch(error => {
// eslint-disable-next-line no-console
console.error(error.message);
});
});
2
Answers
The issue is that you’re trying to access
playerState
as a function, but it’s actually a property. You should access it like this:Full Code: