@dune2/tools 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dune2/tools",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "i18n"
@@ -69,39 +69,44 @@ class StorageHelper<V = any> {
69
69
  v === undefined
70
70
  ? this.store.remove(this.baseKey)
71
71
  : this.store.set(this.baseKey, v);
72
- if (typeof window !== "undefined") {
73
- // On localStorage.setItem, the storage event is only triggered on other tabs and windows.
74
- // So we manually dispatch a storage event to trigger the subscribe function on the current window as well.
75
- window.dispatchEvent(
76
- new StorageEvent("storage", {
77
- key: this.key,
78
- // 这里 value 不重要,在内部会使用 get 重新获取值
79
- newValue: null,
80
- }),
81
- );
82
- }
72
+ this.notifyListeners();
83
73
  }
84
74
 
85
75
  remove(): void {
86
76
  this.set(undefined);
87
77
  }
88
78
 
79
+ private listeners = new Set<() => void>();
80
+ private notifyListeners = () => {
81
+ this.listeners.forEach((listener) => listener());
82
+ };
83
+ /**
84
+ * 订阅 storage 事件
85
+ * @param listener
86
+ * @returns
87
+ */
88
+ subscribe = (listener: () => void) => {
89
+ // for current window
90
+ this.listeners.add(listener);
91
+ // for other windows
92
+ window.addEventListener("storage", listener);
93
+
94
+ return () => {
95
+ this.listeners.delete(listener);
96
+ window.removeEventListener("storage", listener);
97
+ };
98
+ };
99
+
89
100
  /**
90
101
  * 这是 react hooks 的 useValue 的实现
91
102
  */
92
103
  useValue() {
93
104
  return useSyncExternalStore(
94
- this.useSyncExternalStoreSubscribe,
105
+ this.subscribe,
95
106
  this.useSyncExternalStoreGetSnapshot,
96
107
  this.useSyncExternalStoreGetSnapshot,
97
108
  );
98
109
  }
99
- private useSyncExternalStoreSubscribe(listener: () => void) {
100
- window.addEventListener("storage", listener);
101
- return () => {
102
- window.removeEventListener("storage", listener);
103
- };
104
- }
105
110
  private useSyncExternalStoreGetSnapshot = this.get.bind(this);
106
111
  }
107
112