This commit is contained in:
ChuXun
2025-10-19 20:28:31 +08:00
parent c81f8a8b03
commit eaab9a762a
100 changed files with 23416 additions and 0 deletions

128
utils/store.js Normal file
View File

@@ -0,0 +1,128 @@
/**
* 全局状态管理器
* 提供应用级数据管理和状态同步
*/
class Store {
constructor() {
this.state = {
userInfo: null,
isLogin: false,
favoriteCourses: [],
gpaCourses: [],
schedule: {},
countdowns: [],
settings: {
theme: 'light',
notifications: true,
language: 'zh-CN'
}
}
this.listeners = []
this.init()
}
/**
* 初始化:从本地存储恢复状态
*/
init() {
try {
const savedState = wx.getStorageSync('appState')
if (savedState) {
this.state = { ...this.state, ...savedState }
}
} catch (e) {
console.error('状态初始化失败:', e)
}
}
/**
* 获取状态
*/
getState(key) {
if (key) {
return this.state[key]
}
return this.state
}
/**
* 设置状态
*/
setState(key, value) {
if (typeof key === 'object') {
// 批量更新
this.state = { ...this.state, ...key }
} else {
this.state[key] = value
}
this.notify()
this.persist()
}
/**
* 订阅状态变化
*/
subscribe(listener) {
this.listeners.push(listener)
return () => {
const index = this.listeners.indexOf(listener)
if (index > -1) {
this.listeners.splice(index, 1)
}
}
}
/**
* 通知所有订阅者
*/
notify() {
this.listeners.forEach(listener => {
try {
listener(this.state)
} catch (e) {
console.error('状态通知失败:', e)
}
})
}
/**
* 持久化到本地存储
*/
persist() {
try {
wx.setStorageSync('appState', this.state)
} catch (e) {
console.error('状态持久化失败:', e)
}
}
/**
* 清空状态
*/
clear() {
this.state = {
userInfo: null,
isLogin: false,
favoriteCourses: [],
gpaCourses: [],
schedule: {},
countdowns: [],
settings: {
theme: 'light',
notifications: true,
language: 'zh-CN'
}
}
this.persist()
this.notify()
}
}
// 创建全局实例
const store = new Store()
module.exports = {
store
}