简单的 js 发布订阅模式

news/2024/7/10 23:33:45 标签: javascript, 设计模式, es6, node.js
class Event {
    constructor () {
        this.handlers = {}
    }
    //   on
    addEventListener(type,handler) {
        if(!(type in this.handlers)) {
            this.handlers[type] = []
        }
        if(!handler) {
            throw `请添加${type}事件`
        }
        this.handlers[type].push(handler) ;
        return this;
    }
// emit
    dispatchEvent(type,...params) {
        if(!(type in this.handlers)){
            throw new Error('事件未注册')
        }
        this.handlers[type].forEach(handler =>{
            handler(...params)
        })
        return this;
    }
// off
    removeEventListener(type,handler){
        if(!(type in this.handlers)){
            throw new Error('事件未注册')
        }
        if(!handler){
            delete this.handlers[type] 
        }else {
            const idx = this.handlers[type].findIndex(ele => ele === handler)
          
            if(idx === -1) {
                throw new Error('无该绑定事件')
            }
            this.handlers[type].splice(idx,1) ;
            if(this.handlers[type].length === 0){
                delete this.handlers[type]
            }
        }
    }

}

const evn = new Event() ;
const l1 = ()=>{  console.log('l1');}

evn.addEventListener('load',l1)
evn.addEventListener('load',(msg)=>{
    console.log(msg);
})
evn.addEventListener('load',()=>{
    console.log('addEvent33333333Listener');
})

evn.dispatchEvent('load','emit').addEventListener('load2',()=>{
    console.log('load2');
}).dispatchEvent('load2','emit') ;


http://www.niftyadmin.cn/n/1367781.html

相关文章

如何手动决定Promise返回的resolve、reject状态

有时在调用第二个函数Promise返回的状态时,还有其它判断,全部写在一个函数代码太多,可以如下拆分,手动改变状态时一定要加 return 不然下个回调拿不到值!因为第一个函数res或rej代表状态完成,第二个函数都会…

Echarts 大屏rem适配方案

公式: // Wp 为页面有效宽度,Hp 为页面有效高度 const clientWidth document.documentElement.clientWidth; const clientHeight document.documentElement.clientHeight;window.pageWidth clientWidth / clientHeight > 16 / 9 ? clientHeight…

微信小程序api Promise化

// 一、以请求为例 wx.request({url: test.php, //仅为示例,并非真实的接口地址data: {x: ,y: },header: {content-type: application/json // 默认值},success (res) {console.log(res.data)} })// 二、promise化 return new Promise((res,rej)>{wx.request({ur…

vue实现PC端标签拖动效果

1.拖动需要监听鼠标按下、移动、抬起事件 2.一开始全部用methods绑定方法&#xff0c;后面发现用自定义指令directives比较方便&#xff0c;不用声明在data里声明变量&#xff0c;以及一个一个的绑定事件 <template><div class"ad" v-drag><el-badge…

vue 下载本地文件

<a :href${process.env.BASE_URL}竣工通v1.0操作手册.docx >操作帮助</a>1.文件我是放在public目录下的 2.如果你a标签加了download 属性&#xff0c;请保证名字和文件名一样否则无法下载&#xff01;&#xff01;

vue+element-ui 实现table单元格点击编辑,并且按上下键移动

1.接到需求是点击键盘上下键&#xff0c;控制输入框移动方便输入数据 2.相关实现代码 <el-table-column label"档距(m)" prop"span" width"120" align"center"><template slot-scope"scope"><el-input siz…

vue + element ui时 调用toggleRowSelection不生效

使用vuex存当前row&#xff0c;getters取row去其它组件回来时toggleRowSelection(row, true)不生效应该是函数return 取值形成了闭包&#xff0c;在操作页面遍历找到对应row&#xff0c;重新调用即可&#xff01; 主要代码 computed: {getHomePageRow () {return this.$store.…

js防抖节流

// 使用场景&#xff1a;防止狂点 function debounce(fn,delay500){// 使用vue的话, debounce.timer 换成 this.timer debounce.timer && clearTimeout(debounce.timer) ;debounce.timer setTimeout(()>{// fn....debounce.timer null},delay) }throttle (func, d…