ts发布订阅模式

本文介绍了如何在TypeScript中使用发布订阅模式创建一个可复用的事件系统,包括定义接口、创建Emitter类以及处理不同类型的参数。示例展示了如何添加监听器和触发事件的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Ts发布订阅模式

  • 简单类型
interface IOnEmitter<T>{
    eventName:string;
    fn:(aegs?:T)=>void
}

interface IEmitterParams<T>{
     eventName?:string;
     params?:T
}

class Emitter<T>{

    emitterList:IOnEmitter<T>[];

    constructor(){
        this.emitterList=[]
    }

    on(onEmitter:IOnEmitter<T>){
        //去重
        this.emitterList.push(onEmitter)
    }
    
    emit(emit:IEmitterParams<T>){
        this.emitterList.forEach((item)=>{
            if(item.eventName===emit.eventName){
                item.fn(emit.params)
            }
        })
    }
}


type IParamsOftheEmitter=Record<string,any>
const theEmitter=new Emitter<IParamsOftheEmitter>()

theEmitter.on({eventName:'BARK',fn:()=>{
    console.log('bark')
}})
theEmitter.on({eventName:'HI',fn:()=>{
    console.log('hi')
}})
theEmitter.on({eventName:'OK',fn:(aegs?:IParamsOftheEmitter)=>{
    console.log('ok',aegs)
}})

theEmitter.emit({eventName:'BARK'})
theEmitter.emit({eventName:'OK',params:{name:'jack'}})



type IParamsOftheEmitter2=string
const theEmitter2=new Emitter<IParamsOftheEmitter2>()

theEmitter2.on({eventName:'WHY',fn:(aegs?:IParamsOftheEmitter2)=>{
    console.log('why',aegs)
}})
theEmitter2.emit({eventName:'WHY',params:'not'})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值