export class AppBackstageReception {
constructor() {
this.callback = null;
this.state = null;
this.eventOptions = {
pauseEven: null,
resumeEven: null,
visEven: null
};
}
init(callback) {
if (typeof callback !== 'function') throw new TypeError('回调函数是必须的');
this.clear();
this.callback = callback;
this.eventOptions.visEven = () => {
if (document.visibilityState === 'visible') {
if (this.state !== null && this.state === 1) return;
this.state = 1;
this.callback && this.callback(true, {eventMessage: '从前台切换到后台', state: 1});
} else if (document.visibilityState === 'hidden') {
if (this.state !== null && this.state === 0) return;
this.state = 0;
this.callback && this.callback(false, {eventMessage: '从前台切换到后台', state: 0});
}
};
document.addEventListener('visibilitychange', this.eventOptions.visEven);
}
clear() {
if (this.callback === null) return;
this.callback = null;
document.removeEventListener('visibilitychange', this.eventOptions.resumeEven);
}
}