js设计模式之观察者模式(订阅模式)

xml 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>观察者模式</title>
</head>
<body>
<script>
    class Event {
        constructor() {

        }

        //事件容器,可以是一个也可以是多个
        handlers = {}

        //事件添加方法、事件名称,事件方法
        addEventListener(type, handler) {
            if (!(type in this.handlers)) {
                this.handlers[type] = [];
            }
            //将事件存入
            this.handlers[type].push(handler)
        }

        //触发事件
        dispatchEvent(type, ...params) {
            if (!(type in this.handlers)) {
                return new Error("未注册该事件")
            }
            //触发
            this.handlers[type].forEach(item => {
                item(...params);
            })
        }

        //移除事件
        removeEventListener(type, handler) {
            if (!(type in this.handlers)) {
                return new Error("无效事件")
            }
            if (!handler) {
                //delete删除对象元素
                delete this.handlers[type]
            }else {
                const idx = this.handlers[type].findIndex(item => item === handler)
                if (idx===undefined){
                    return new Error("无效事件")
                }
                this.handlers[type].splice(idx, 1)
                if (this.handlers[type].length === 0) {
                    delete this.handlers[type]
                }
            }
        }
    }

    //创建事件对象
    const event = new Event();

    //定义一个load事件
    function load(params) {
        console.log("load", params)
    }

    //添加事件
    event.addEventListener("load", load)

    function load2(params) {
        console.log("load2", params)
    }

    event.addEventListener("load", load2)

    //触发
    event.dispatchEvent("load", "load事件触发")
    //删除
    event.removeEventListener("load", load)
</script>
</body>
</html>
相关推荐
q***385126 分钟前
TypeScript 与后端开发Node.js
javascript·typescript·node.js
用户479492835691537 分钟前
别再当 AI 的"人肉定位器"了:一个工具让 React 组件秒定位
前端·aigc·ai编程
Nan_Shu_6141 小时前
学习:Sass
javascript·学习·es6
WYiQIU1 小时前
面了一次字节前端岗,我才知道何为“造火箭”的极致!
前端·javascript·vue.js·react.js·面试
qq_316837752 小时前
uniapp 观察列表每个元素的曝光时间
前端·javascript·uni-app
小夏同学呀2 小时前
在 Vue 2 中实现 “点击下载条码 → 打开新窗口预览 → 自动唤起浏览器打印” 的功能
前端·javascript·vue.js
芳草萋萋鹦鹉洲哦2 小时前
【vue】导航栏变动后刷新router的几种方法
前端·javascript·vue.js
zero13_小葵司2 小时前
JavaScript性能优化系列(八)弱网环境体验优化 - 8.3 数据预加载与缓存:提前缓存关键数据
javascript·缓存·性能优化
1***y1782 小时前
Vue项目性能优化案例
前端·vue.js·性能优化
Irene19912 小时前
FileList 对象总结(附:不支持迭代的类数组对象表)
javascript·类数组对象·filelist·不支持迭代