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. 跳板攻击之: MSF 添加路由方式渗透内网

    跳板攻击之: MSF 添加路由方式渗透内网 目录 跳板攻击之: MSF 添加路由方式渗透内网 1 Metasploit 跳板攻击: 添加路由方式原理 2 实验环境 2.1 建立 meterpreter ...

  2. 依那西普减量维持过程中RA病人自报病情复发可能预示未来放射学进展[EULAR2015_SAT0147]

    依那西普减量维持过程中RA病人自报病情复发可能预示未来放射学进展   SAT0147 SELF-REPORTED FLARES PREDICT RADIOGRAPHIC PROGRESSION IN ...

  3. 代码随想录算法训练营day08 | leetcode 344.反转字符串/541. 反转字符串II / 剑指Offer05.替换空格/151.翻转字符串里的单词/剑指Offer58-II.左旋转字符串

    基础知识 // String -> char[] char[] string=s.toCharArray(); // char[] -> String String.valueOf(str ...

  4. .net mvc 权限验证 Filter(过滤器)

    一.知识了解 Asp.Net MVC提供了以下几种默认的Filter: 大家注意一点,Asp.Net MVC提供的ActionFilterAttribute默认实现了IActionFilter和IRe ...

  5. Leaflet 调用腾讯瓦片地图服务demo

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" ...

  6. Python批量绘制遥感影像数据的直方图

      本文介绍基于Python中gdal模块,实现对大量栅格图像批量绘制直方图的方法.   首先,明确一下本文需要实现的需求:现需对多幅栅格数据文件进行依据其像元数值的直方图绘制,具体绘制内容即各栅格图 ...

  7. springboot加入cloud,并注册到nacos

    pom.xml下新增 <dependency> <groupId>org.springframework.cloud</groupId> <artifactI ...

  8. 目标库DML 堵塞(dblink)导致OGG延迟

    [[toc]] # 问题概述xx库OGG延迟超过8个小时,但进程处于RUNNING.# 问题原因定位到有人通过A库的DBLINK修改目标库的数据. OGG同步的表, 目标的端也在做修改相同数据,无法保 ...

  9. Vue ref属性

    ref属性 1.被用来给元素或子组件注册引用信息(id的替代者) 2.应用在html标签上获取的是真实DOM元素: 应用在组件标签上是组件实例对象 vc 3.使用方法: (1)打标识:<h1 r ...

  10. day11_多态&抽象类&接口

    1.多态 1.1 多态的概述(记忆) 什么是多态     同一对象,在不同时刻表现出来的不同形态. 多态的前提 有继承/实现关系 有方法重写 有父类对象的引用执行子类对象 1.2 多态中的成员访问特点 ...