topfans/frontend/utils/backgroundRefreshBus.js
2026-06-16 15:19:53 +08:00

46 lines
1.1 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 后台返回事件总线
*
* 触发方App.vue 在 onShow 中检测到"从后台切回前台"时调用
* emitAppReturnFromBackground()
* 订阅方:页面通过 composables/useBackgroundRefresh.js 注册回调
*
* 为什么不用 uni.$emit / uni.$on
* 1. 事件名是字符串,缺乏约束,容易和其他业务事件撞名
* 2. 集中在一处便于后续加日志、节流、灰度等横切逻辑
*/
const listeners = new Set()
/**
* 注册后台返回监听
* @param {Function} fn 回调函数
* @returns {Function} 取消监听的函数
*/
export function onAppReturnFromBackground(fn) {
if (typeof fn !== 'function') return () => {}
listeners.add(fn)
return () => listeners.delete(fn)
}
/**
* 触发后台返回事件,通知所有订阅者
*/
export function emitAppReturnFromBackground() {
listeners.forEach(fn => {
try {
fn()
} catch (e) {
// 单个监听者异常不影响其他监听者
console.error('[backgroundRefreshBus] listener error:', e)
}
})
}
/**
* 清空所有监听(仅用于测试或强制重置)
*/
export function clearAppReturnFromBackgroundListeners() {
listeners.clear()
}