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>
相关推荐
weixin_ab5 分钟前
【HTML分离术】
前端·html
文心快码BaiduComate20 分钟前
新手该如何选择AI编程工具?文心快码Comate全方位体验
前端·后端·程序员
夫唯不争,故无尤也23 分钟前
Tomcat 内嵌启动时找不到 Web 应用的路径
java·前端·tomcat
lichong95126 分钟前
【Xcode】Macos p12 证书过期时间查看
前端·ide·macos·证书·xcode·大前端·大前端++
oh,huoyuyan27 分钟前
如何在火语言中指定启动 Chrome 特定用户配置文件
前端·javascript·chrome
前端大聪明200230 分钟前
single-spa原理解析
前端·javascript
一枚前端小能手34 分钟前
📦 从npm到yarn到pnpm的演进之路 - 包管理器实现原理深度解析
前端·javascript·npm
影i1 小时前
CSS Transform 和父元素撑开问题
前端
@大迁世界1 小时前
Promise.all 与 Promise.allSettled:一次取数的小差别,救了我的接口
开发语言·前端·javascript·ecmascript
知识分享小能手1 小时前
微信小程序入门学习教程,从入门到精通,项目实战:美妆商城小程序 —— 知识点详解与案例代码 (18)
前端·学习·react.js·微信小程序·小程序·vue·前端技术