当前位置: 首页 > news >正文

学习ts(十一)本地存储与发布订阅模式

localStorage实现过期时间

目录

在这里插入图片描述

准备

安装

npm i rollup typescript rollup-plugin-typescript2
// tsconfig.json"module": "ESNext","moduleResolution": "node",    "strict": false,     
// rollup.config.js
import ts from 'rollup-plugin-typescript2'
import path from 'path'
import { fileURLToPath } from 'url'
const mateUrl = fileURLToPath(import.meta.url)
const dirName = path.dirname(mateUrl)
export default {input: "./src/index.ts",output: {file: path.resolve(dirName, './dist/index.js')},plugins:[ts()]
}

在这里插入图片描述

开发

// enum/index.ts
export enum Dictionaries {permanent = 'permanent',  //永久expire = '__expire__'
}
// type/index.ts
import { Dictionaries } from "../enum"export type Expire = Dictionaries.permanent | number //传递永久或者时间戳
export type Key = stringexport interface StorageCls {get: <T>(key: Key) => voidset: <T>(key: Key, value: T, expire: Expire) => voidremove: (key: Key) => voidclear: () => void
}
export interface Data<T> {value: T,[Dictionaries.expire]: Expire
}
export interface Result<T> {message: string,value: T | null
}
// index.ts
import { Key, StorageCls, Expire, Data, Result } from "./type";
import { Dictionaries } from "./enum"
export class Storage implements StorageCls {get<T>(key: Key):Result<T | null> {const value = localStorage.getItem(key)if (value) {const data = JSON.parse(value)const now = new Date().getTime()// 过期if (typeof data[Dictionaries.expire] == 'number' && data[Dictionaries.expire] < now) {this.remove(key)return {message: `您的 ${key}已过期`,value: null}} else {return {message: `成功`,value: data.value}}} else {return {message: '值无效',value: null}}}set<T>(key: Key, value: T, expire: Expire): void {const data: Data<T> = {value,[Dictionaries.expire]: expire}localStorage.setItem(key, JSON.stringify(data))}remove(key: Key) {localStorage.removeItem(key)}clear() {localStorage.clear()};}

测试

<script type="module">import {Storage} from './dist/index.js'let s = new Storage()s.set('test','orange',new Date().getTime()+3000)// setInterval(()=>{//     console.log(s.get('test'))// },1000)</script>

发布订阅模式

type Key = string
interface EventInit {on: (key: Key, fn: Function) => voidemit: (key: Key, ...args: Array<any>) => voidoff: (key: Key, fn: Function) => voidonce: (key: Key, fn: Function) => void
}interface List {[key: string]: Array<Function>
}class Dispatch implements EventInit {list: Listconstructor() {this.list = {}}on(key: Key, fn: Function) {const callback = this.list[key] || []callback.push(fn)this.list[key] = callback// console.log(this.list)}emit(key: Key, ...args: Array<any>) {if (this.list[key] && this.list[key].length > 0) {this.list[key].forEach(item => {item.apply(this, args)})} else {console.error('名称错误')}}off(key: Key, fn: Function) {if (this.list[key] && this.list[key].length > 0) {let index = this.list[key].findIndex(i => i === fn)if (index > -1) {this.list[key].splice(index, 1)} else {console.error(`方法不存在`)}} else {console.error(`名称错误${key}`)}}once(key: Key, fn: Function) {let tempFn = (...args: Array<any>) => {fn.apply(this, args)this.off(key, tempFn)}this.on(key, tempFn)}
}
const o = new Dispatch()
o.on('post', (...args) => {console.log(args)
})
o.on('post', (...args) => {console.log(args)
})
o.on('put', (...args) => {console.log(args)
})
let fn = (...args) => {console.log(args)
}
// o.on('get', fn)
o.once('get', fn)
o.emit('get', fn)
o.emit('get', fn)
// o.emit('put', 1, '373', { name: 'hello' })
// o.off('get', fn)
// o.emit('get', 2, '373', { name: 'hello' })
http://www.lryc.cn/news/147987.html

相关文章:

  • MySQL对NULL值处理
  • Vector 动态数组(迭代器)
  • 多组背包恰好装满方案数
  • Oracle查询语句中做日期加减运算
  • Unity贝塞尔曲线的落地应用-驱动飞行特效
  • VTK——设置交互样式上的鼠标回调函数
  • Flutter实现动画列表AnimateListView
  • 【LeetCode-中等题】236. 二叉树的最近公共祖先
  • 如何拼接两个视频在一起?
  • Programming abstractions in C阅读笔记:p130-p131
  • 如何在Windows本地快速搭建SFTP文件服务器,并通过端口映射实现公网远程访问
  • C#---第二十:不同类型方法的执行顺序(new / virtual / common / override)
  • lnmp架构-PHP
  • 【javascript实操记录】
  • Mysql--技术文档--悲观锁、乐观锁-《控制并发机制简单认知、深度理解》
  • 【GO】LGTM_Grafana_Tempo(2)_官方用例改后实操
  • git 口令
  • 【回眸】剑指offer(二)解题思路
  • Python 基本文件操作及os库
  • YOLOv5算法改进(9)— 替换主干网络之ShuffleNetV2
  • 三、mycat分库分表
  • gitlab提交项目Log in with Access Token错误
  • openGauss学习笔记-56 openGauss 高级特性-DCF
  • Xcode 14 pod init报错
  • 飞腾PSPA可信启动--2 数字签名证书
  • 微前端:重塑大型项目的前沿技术
  • 官方推荐使用的OkHttp4网络请求库全面解析(Android篇)
  • Spooling的原理
  • Homebrew 无法安装过时的PHP版本
  • python爬取bilibili,下载视频