[js函数] storageManager
import _get from 'lodash.get';
import _set from 'lodash.set';
import _debounce from 'lodash.debounce';
import {shallowEqual} from "./shallow-equal"; const IS_STORAGE_INITIALIZED = '$$IS_STORAGE_INITIALIZED$$'; interface PersistConfig {
save: (storageName: string, storageData: any) => void;
load: (storageName: string) => Promise<any>;
} type WatcherFn = (nextValue: any, preValue: any, storage: Storage) => void; interface Watcher {
path: string,
watcher: WatcherFn,
preValue: any
} class Storage {
private readonly storageName: string;
private storageData: Record<string, any>;
private watcherList: Watcher[];
private persistConfig: PersistConfig | null;
private readonly persistStorageFn: any; constructor(storageName: string) {
this.storageName = storageName;
this.storageData = {};
this.watcherList = []; // {path, watcher, preValue}
this.persistConfig = null; // {save:(storageName,storageData)=>{}, load:(storageName)=>{}}
this.persistStorageFn = _debounce(() => {
this.persistStorage();
}, 100);
setTimeout(() => {
this.persistStorageInit();
}, 1);
} setPersistConfig(persistConfig: PersistConfig) {
this.persistConfig = persistConfig;
} initStorageData(storageData: Record<string, any>) {
this.storageData = storageData;
this.storageData[IS_STORAGE_INITIALIZED] = true;
this.notifyWatcher();
} getValue(path: string) {
return _get(this.storageData, path);
} setValue(path: string, value: any) {
_set(this.storageData, path, value);
this.notifyWatcher();
this.persistStorageFn()
} watch(path: string, watcher: WatcherFn) {
if (typeof watcher !== "function") {
throw 'watcher must function';
}
this.watcherList.push({path, watcher, preValue: undefined});
} unwatch(path: string, watcher: WatcherFn) {
this.watcherList = this.watcherList.filter((obj) => {
return obj.path !== path && obj.watcher !== watcher;
});
} notifyWatcher() {
const watcherList = this.watcherList || [];
for (let i = 0; i < watcherList.length; i++) {
const {path, watcher, preValue} = watcherList[i];
const nextValue = this.getValue(path);
if (!shallowEqual(nextValue, preValue)) {
watcher(nextValue, preValue, this);
watcherList[i].preValue = nextValue;
}
}
} persistStorage() {
const persistConfig = this.persistConfig;
if (!persistConfig) {
return;
}
const {save} = persistConfig;
save(this.storageName, this.storageData);
} persistStorageInit() {
const persistConfig = this.persistConfig;
if (!persistConfig) {
this.initStorageData({});
return;
} const {load} = persistConfig;
load(this.storageName).then((storageData) => {
if (storageData && typeof storageData === "object") {
this.initStorageData(storageData);
} else {
this.initStorageData({});
}
}, () => {
this.initStorageData({});
});
} } class StorageManager { private storageMap: Record<string, Storage> = {}; getStorage(storageName: string) {
if (!this.storageMap[storageName]) {
this.storageMap[storageName] = new Storage(storageName);
}
return this.storageMap[storageName];
} } const storageManager = new StorageManager(); export {
storageManager,
IS_STORAGE_INITIALIZED
}
import localforage from '@ali/ascp-shared-local-forage' /**
* 使用 localStorage 存储
*/
const localStoragePersist = {
save: (storageName, storageData) => {
localStorage.setItem(storageName, JSON.stringify(storageData));
},
load: (storageName) => {
return new Promise((resolve) => {
const str = localStorage.getItem(storageName);
if (str) {
resolve(JSON.parse(str))
} else {
resolve(null);
}
})
}
} /**
* 使用 localforage 存储
*/
const localForagePersist = {
save: (storageName, storageData) => {
localforage.setItem(storageName, storageData);
},
load: (storageName) => {
return localforage.getItem(storageName);
}
}; export {
localStoragePersist,
localForagePersist
}
import {useEffect, useState} from 'react';
import {storageManager} from "../utils/storage";
function useStorageValue(storageName, persistConfig, path) {
  const storage = storageManager.getStorage(storageName);
  storage.setPersistConfig(persistConfig)
  const [value, setValue] = useState(() => {
    return storage.getValue(path);
  });
  useEffect(() => {
    const watcher = (nowValue) => {
      setValue(nowValue);
    };
    storage.watch(path, watcher);
    return () => {
      storage.unwatch(path, watcher);
    }
  }, [storageName, path]);
  return value;
}
export {
  useStorageValue
}
[js函数] storageManager的更多相关文章
- 3.3 js函数
		1.函数语法: 函数声明的方式:function 函数名(参数1,参数2-){//函数体;}函数调用:函数名(参数1,参数2-); 函数内不一定都指定返回值. 如果需要指定返回值,可用 return ... 
- Js函数function基础理解
		正文:我们知道,在js中,函数实际上是一个对象,每个函数都是Function类型的实例,并且都与其他引用类型一样具有属性和方法.因此,函数名实际上是指向函数对象的指针,不与某个函数绑定.在常见的两种定 ... 
- js函数表达式和函数声明的区别
		我们已经知道,在任意代码片段外部添加包装函数,可以将内部的变量和函数定义"隐 藏"起来,外部作用域无法访问包装函数内部的任何内容. 例如: var a = 2; function ... 
- 通用js函数集锦<来源于网络> 【二】
		通用js函数集锦<来源于网络> [二] 1.数组方法集2.cookie方法集3.url方法集4.正则表达式方法集5.字符串方法集6.加密方法集7.日期方法集8.浏览器检测方法集9.json ... 
- 通用js函数集锦<来源于网络/自己> 【一】
		通用js函数集锦<来源于网络/自己>[一] 1.返回一个全地址2.cookie3.验证用户浏览器是否是微信浏览器4.验证用户浏览器是否是微博内置浏览器5.query string6.验证用 ... 
- 100多个基础常用JS函数和语法集合大全
		网站特效离不开脚本,javascript是最常用的脚本语言,我们归纳一下常用的基础函数和语法: 1.输出语句:document.write(""); 2.JS中的注释为//3.传统 ... 
- JS函数
		1.document.write(""); 输出语句2.JS中的注释为//3.传统的HTML文档顺序是:document->html->(head,body)4.一个浏 ... 
- js函数和运算符
		函数是由事件驱动或者它被调用时执行可重复使用的代码块. <script> function myFunction(){ Alert(“hello World!”): } </scri ... 
- JavaScript学习03 JS函数
		JavaScript学习03 JS函数 函数就是包裹在花括号中的代码块,前面使用了关键词function: function functionName() { 这里是要执行的代码 } 函数参数 函数的 ... 
- JSF页面中使用js函数回调后台bean方法并获取返回值的方法
		由于primefaces在国内使用的并不是太多,因此,国内对jsf做系统.详细的介绍的资料很少,即使有一些资料,也仅仅是对国外资料的简单翻译或者是仅仅讲表面现象(皮毛而已),它们的语句甚至还是错误的, ... 
随机推荐
- appium连接手机 adb调试 app自动化
			一. 工具准备 jdk,java环境必备. android sdk,要使用内置的Android debug bridge,简称adb,调试手机用. appium,提供自动化服务,app自动化的核心库. ... 
- Ansible-playbook 快速入门到放弃
			Ansible-playbook 快速入门到放弃 隔岸红尘忙似火,当轩青嶂冷如冰. 1-简介 playbook 相当于可以把模块命令都写入到配置文件里面,这样就可以直接执行配置文件了,类似脚本. 2- ... 
- 图论之最短路径 Floyd算法
			/** 图论之最短路径 Floyd算法 */ #include<stdio.h> #include<string.h> #include<algorithm> #d ... 
- 钓鱼攻击之:CHM电子书钓鱼
			钓鱼攻击之:CHM电子书钓鱼 目录 钓鱼攻击之:CHM电子书钓鱼 1 CHM简介 2 .Chm文件因何变得危险 3 CHM 后门的优点 4 利用过程 4.1 准备工具 4.2 制作恶意chm文件 4. ... 
- js(最新)手机号码 正则验证 - 代码篇
			现在手机号码,除了以11+.12+开头的没有,别的好像都有了! 代码如下: 方法一: function checkPhone(){ var phone = $(".phone"). ... 
- html+css+js思维导图
- 98、TypeError: f.upload.addEventListener is not a function
			https://blog.csdn.net/qq_42202633/article/details/123083927 在分片上传时遇到的这个问题 
- 00.IDEA的使用
			1.IDEA的必备常用快捷键 复制本行到下一行:ctrl D 删除一行代码:ctrl Y 替换文本:ctrl R 根据光标放的位置提供快速修复选择:Alt + Enter 生成返回值:ctrl alt ... 
- web3 的身份验证之以太坊签名消息
			https://zhuanlan.zhihu.com/p/535573066 python 实现 #coding=utf-8 from web3 import Web3 from eth_accoun ... 
- think php框架接入微信支付中需要注意的问题(php 小白适用)
			接触php也有一段时间了,感觉有越来越多的地方需要学习,最近接入了微信扫码支付(pc端),记录一下,让php刚入门的小白们少走弯路. 准备阶段,到"微信公众平台"注册微信公众号,具 ... 
