
// 用于优化数据流 结合发布订阅 更新组件内部状态可以组件自己处理

import { Events } from '@tarojs/taro'
import type { ColorStore } from '.'

export const events = new Events()

export type SubscribeCallback = (changedGoods: any) => void

export class ShoppingStore {
  // 全局缓存
  private store: ColorStore = {}
  // 监听器数组
  private observers: SubscribeCallback[] = []

  constructor(initialValue?: any) {
    initialValue && this.updateStore(initialValue)
  }

  // 更新全局缓存
  private updateStore(nextStore: ColorStore) {
    this.store = nextStore
  }

  // 订阅
  subscribe(callback: SubscribeCallback) {
    this.observers.push(callback)
    // 取消订阅
    return () => {
      this.observers = this.observers.filter((fn: SubscribeCallback) => {
        return callback !== fn // 引用地址
      })
    }
  }

  // 通知
  notify(changedGoods: any) {
    // 循环调用
    this.observers.forEach((callback) => {
      callback(changedGoods)
    })
  }
}
