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>
相关推荐
拾光拾趣录14 分钟前
CSS常见问题深度解析与解决方案(第三波)
前端·css
徊忆羽菲21 分钟前
Echarts3D柱状图-圆柱体-文字在柱体上垂直显示的实现方法
javascript·ecmascript·echarts
轻语呢喃31 分钟前
JavaScript :字符串模板——优雅编程的基石
前端·javascript·后端
杨进军32 分钟前
React 协调器 render 阶段
前端·react.js·前端框架
中微子34 分钟前
Blob 对象及 Base64 转换指南
前端
风铃喵游35 分钟前
让大模型调用MCP服务变得超级简单
前端·人工智能
中微子36 分钟前
智能前端实践之 shot-word demo
前端
归于尽36 分钟前
智能前端小魔术,让图片开口说单词
前端·react.js
用户98738245810137 分钟前
vite 插件
前端
无数山39 分钟前
autorelease pool
前端