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的更多相关文章

  1. 3.3 js函数

    1.函数语法: 函数声明的方式:function 函数名(参数1,参数2-){//函数体;}函数调用:函数名(参数1,参数2-); 函数内不一定都指定返回值. 如果需要指定返回值,可用 return ...

  2. Js函数function基础理解

    正文:我们知道,在js中,函数实际上是一个对象,每个函数都是Function类型的实例,并且都与其他引用类型一样具有属性和方法.因此,函数名实际上是指向函数对象的指针,不与某个函数绑定.在常见的两种定 ...

  3. js函数表达式和函数声明的区别

    我们已经知道,在任意代码片段外部添加包装函数,可以将内部的变量和函数定义"隐 藏"起来,外部作用域无法访问包装函数内部的任何内容. 例如: var a = 2; function ...

  4. 通用js函数集锦<来源于网络> 【二】

    通用js函数集锦<来源于网络> [二] 1.数组方法集2.cookie方法集3.url方法集4.正则表达式方法集5.字符串方法集6.加密方法集7.日期方法集8.浏览器检测方法集9.json ...

  5. 通用js函数集锦<来源于网络/自己> 【一】

    通用js函数集锦<来源于网络/自己>[一] 1.返回一个全地址2.cookie3.验证用户浏览器是否是微信浏览器4.验证用户浏览器是否是微博内置浏览器5.query string6.验证用 ...

  6. 100多个基础常用JS函数和语法集合大全

    网站特效离不开脚本,javascript是最常用的脚本语言,我们归纳一下常用的基础函数和语法: 1.输出语句:document.write(""); 2.JS中的注释为//3.传统 ...

  7. JS函数

    1.document.write(""); 输出语句2.JS中的注释为//3.传统的HTML文档顺序是:document->html->(head,body)4.一个浏 ...

  8. js函数和运算符

    函数是由事件驱动或者它被调用时执行可重复使用的代码块. <script> function myFunction(){ Alert(“hello World!”): } </scri ...

  9. JavaScript学习03 JS函数

    JavaScript学习03 JS函数 函数就是包裹在花括号中的代码块,前面使用了关键词function: function functionName() { 这里是要执行的代码 } 函数参数 函数的 ...

  10. JSF页面中使用js函数回调后台bean方法并获取返回值的方法

    由于primefaces在国内使用的并不是太多,因此,国内对jsf做系统.详细的介绍的资料很少,即使有一些资料,也仅仅是对国外资料的简单翻译或者是仅仅讲表面现象(皮毛而已),它们的语句甚至还是错误的, ...

随机推荐

  1. 最大K段和

    题目大意 有一个长度为 \(N\) 的序列 \(A\) .他希望从中选出不超过 \(K\) 个连续子段,满足它们两两不相交,求总和的最大值(可以一段也不选,答案为 \(0\)). 分析 很容易想到 \ ...

  2. .Net Core 配置源码学习 (一)

    一 背景 相比.Net Framework , .NET Core的配置系统 ,有一些明显的优点 ,如: 1 支持更丰富的配置源 2 读取配置时, 可以用相同的方式读取, 并且非常方便 3 修改配置后 ...

  3. Apache HttpClient使用和源码分析

    在上文中分析了 HttpURLConnection的用法,功能还是比较简单的,没有什么封装 接下来看看Apache HttpClient是如何封装httpClient的 目录 组成 请求代码 代码分析 ...

  4. dotnet core+nginx+supervisor

    1.前提准备 安装虚拟机,安装CentOS,有云服务器的直接用云服务器就行 本地安装 xshell.xftp 2.nginx配置静态页面 我们先学习一下使用nginx配置一个静态页面,一步一步来深入 ...

  5. 09 安装虚拟机:Ubuntu Server 20.04

    09 安装虚拟机:Ubuntu Server 20.04 9.1 取得安装映像档 9.2 建立虚拟机客体 请至Proxmox VE管理界面点选右上方的[建立VM],来到建立虚拟机客体的引导程序.引导程 ...

  6. spring boot 配置多套数据源

    问题:需要在多个数据库中查询数据,不适用sql中的use语句. 导包 pom.xml <!-- mybatis,使用mybatis-plus也行,虽然plus的单表查询很强,在大部分情况下需要编 ...

  7. No.1.9

    项目样式补充 精灵图(场景:项目中将多张小图片,合并成一张大图片,这张大图片称之为精灵图) (优点:减少服务器发送次数,减轻服务器的压力,提高页面加载速度) 精灵图的使用步骤:1.创建一个盒子,设置盒 ...

  8. mysql explain 查看sql语句执行计划概述

    mysql explain 查看sql语句执行计划概述 id:选择标识符select_type:表示查询的类型.table:输出结果集的表partitions:匹配的分区type:表示表的连接类型po ...

  9. 阿里云服务器ECS(Centos8)下安装和配置python3.8

    1.安装依赖包: yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-dev ...

  10. Jest - Using test function to test the function

    Note: Please check the prev blog to see the jest configuration. calculator.js const plus = (a, b) =& ...