/** * 初始化idata扫描模块 */ export function useInit() { //获取module var barcodeModel = uni.requireNativePlugin("iData-BarcodePlugin-BarcodeModule"); //使用示例 barcodeModel.initScan((ret) => { console.log("初始化扫描", ret); }); } // 存储当前活跃页面的回调函数 const callbackRegistry = { activePagePath: null, callbacks: new Map(), // 使用Map存储每个页面路径对应的回调函数 }; /** * 全局事件处理函数 - 内部使用 * 只执行当前活跃页面的回调函数 */ const globalEventHandler = function(e) { if (!callbackRegistry.activePagePath) return; const callback = callbackRegistry.callbacks.get(callbackRegistry.activePagePath); if (callback) { // 只执行当前活跃页面的回调 callback(e); } }; // 初始化全局事件监听器 let isGlobalListenerInitialized = false; function initGlobalListener() { if (isGlobalListenerInitialized) return; const globalEvent = uni.requireNativePlugin("globalEvent"); // 确保移除任何可能存在的旧监听器 globalEvent.removeEventListener("iDataBarcodeEvent", globalEventHandler); // 添加全局单一监听器 globalEvent.addEventListener("iDataBarcodeEvent", globalEventHandler); isGlobalListenerInitialized = true; } /** * 全局监听扫描后结果 * @param onChange 回调函数 * @returns {Function} 返回移除监听器的函数 */ export function useGlobalEvent(onChange) { // 确保全局监听器已初始化 initGlobalListener(); // 获取当前页面路径 const pages = getCurrentPages(); const currentPage = pages[pages.length - 1]; const pagePath = currentPage ? currentPage.route : null; if (!pagePath) { console.error("无法获取当前页面路径"); return () => {}; } // 更新当前活跃页面 callbackRegistry.activePagePath = pagePath; // 注册当前页面的回调 callbackRegistry.callbacks.set(pagePath, onChange); console.log(`页面 ${pagePath} 已注册扫描回调`); // 返回一个清理函数,用于手动移除监听器 return () => { callbackRegistry.callbacks.delete(pagePath); console.log(`页面 ${pagePath} 的扫描回调已移除`); }; } /** * 更新当前活跃页面,在页面显示时调用 * 在App.vue的onShow中调用 */ export function updateActivePageOnShow() { const pages = getCurrentPages(); const currentPage = pages[pages.length - 1]; const pagePath = currentPage ? currentPage.route : null; if (!pagePath) { console.error("无法获取当前页面路径"); return; } // 更新当前活跃页面 callbackRegistry.activePagePath = pagePath; console.log(`当前活跃页面已更新为: ${pagePath}`); } /** * 全局卸载监听事件 * 完全移除全局事件监听器 */ export function useGlobalEventRemove() { const globalEvent = uni.requireNativePlugin("globalEvent"); globalEvent.removeEventListener("iDataBarcodeEvent", globalEventHandler); isGlobalListenerInitialized = false; callbackRegistry.callbacks.clear(); callbackRegistry.activePagePath = null; console.log("全局扫描监听器已完全移除"); } /** * 移除特定页面的回调 * @param pagePath 页面路径,如果不提供则移除当前页面的回调 */ export function removePageCallback(pagePath) { if (!pagePath) { const pages = getCurrentPages(); const currentPage = pages[pages.length - 1]; pagePath = currentPage ? currentPage.route : null; } if (!pagePath) { console.error("无法获取页面路径"); return; } callbackRegistry.callbacks.delete(pagePath); console.log(`页面 ${pagePath} 的扫描回调已移除`); }