Files
Pet3/miniprogram/utils/store.js
2026-06-25 18:24:29 +08:00

44 lines
1.1 KiB
JavaScript
Raw 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.
// utils/store.js — 轻量全局状态 + 订阅(不引第三方状态库)
// 读 app.globalData变更通过 set() 并广播给订阅者。
const app = () => getApp();
const listeners = new Set();
function getState() {
return app().globalData;
}
/**
* 合并更新全局状态并广播。
* @param {object} patch 要合并进 globalData 的字段
*/
function set(patch) {
Object.assign(app().globalData, patch);
listeners.forEach((fn) => fn(app().globalData));
}
/**
* 订阅状态变更,返回取消订阅函数。
* @param {(state:object)=>void} fn
*/
function subscribe(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
}
// ===== 遛狗会话V1 核心运行时状态,需持久化防丢) =====
function setWalkSession(session) {
set({ walkSession: session });
if (session) {
wx.setStorageSync('walkSession', session);
} else {
wx.removeStorageSync('walkSession');
}
}
function getWalkSession() {
return app().globalData.walkSession;
}
module.exports = { getState, set, subscribe, setWalkSession, getWalkSession };