我创建了一个 youtube api 类,因为我在多个文件中需要它,但是当我尝试访问 getPlayerState() 时,它给了我错误,它不是一个函数,但是当我 console.log 时 我在列表中看到 getPlayerState()。下面是我的 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;
在这里我正在调用它,但我正在尝试访问playerState。它给了我错误
// 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);
});
});
问题是您试图将
playerState
作为函数来访问,但它实际上是一个属性。你应该像这样访问它:
const playerState = youtubeManager.player.getPlayerState();
完整代码:
// eslint-disable-next-line no-unused-vars
define(['jquery', './youTubeManager'], function($, youtubeManager) {
youtubeManager.readyPromise.then(() => {
// Access the player from the instance
const player = youtubeManager.player;
// Access the playerState property
const playerState = player.getPlayerState();
// eslint-disable-next-line no-console
console.log(playerState);
}).catch(error => {
// eslint-disable-next-line no-console
console.error(error.message);
});
});