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>
相关推荐
晓得迷路了19 小时前
栗子前端技术周刊第 98 期 - NPM 生态遭受攻击、Rspack 1.5.3、Storybook 10 beta...
前端·javascript·css
江城开朗的豌豆19 小时前
解密DVA:React应用的状态管理利器
前端·javascript·react.js
码猿宝宝19 小时前
浏览器中javascript时间线,从加载到执行
开发语言·javascript·ecmascript
带娃的IT创业者19 小时前
《Python Web部署应知应会》No3:Flask网站的性能优化和实时监测深度实战
前端·python·flask
weixin_4316004419 小时前
使用 vue-virtual-scroller 实现高性能传输列表功能总结
前端·javascript·vue.js
OEC小胖胖19 小时前
App Router vs. Pages Router:我应该如何选择?
开发语言·前端·前端框架·web·next.js
GDAL19 小时前
Knockout.js Google Closure Compiler 工具模块详解
javascript·knockout
软件技术NINI19 小时前
js趣味游戏 贪吃蛇
javascript
@菜菜_达19 小时前
后端post请求返回页面,在另一个项目中请求过来会出现的问题
javascript
Wiktok19 小时前
【Wit】pure-admin后台管理系统前端与FastAPI后端联调通信实例
前端·vue3·pureadmin