JS手写练习随笔-20221211.1 ---- 事件中心(发布订阅)
发布订阅事件中心的实现
// TS
class EventEmitter { // 事件中心 private store: Record<string, Function[]>; constructor() { this.store = {}; } /** * 为某种类型的事件添加回调/处理函数 */ on(type: string, handler: Function) { // 如果已有该"type"的记录 if (Array.isArray(this.store[type])) { this.store[type].push(handler); } // 没有则初始化一个 else { this.store[type] = [handler]; } } /** * 清除某种类型的事件上特定的处理函数 */ off(type: string, handler: Function) { if (this.store[type] === undefined || this.store[type].length === 0) { return; } this.store[type] = this.store[type].filter((fn: Function) => { return fn !== handler; }); } /** * 为某种类型的事件添加一次性的回调/处理函数 */ once(type: string, handler: Function) { const onceFn = () => { handler(); this.off(type, onceFn); }; this.on(type, onceFn); } /** * 触发相应类型的事件 */ emit(type: string, ...params: Parameters<any>) { if (this.store[type] === undefined || this.store[type].length === 0) { return; } this.store[type].forEach(fn => { fn.apply(this, params); }); } }
分类:
JavaScript
标签:
JavaScript
, TypeScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
2021-12-11 关于window.location的细节