Ts实现发布订阅模式

发布订阅模式有4个方法,存储结构是一个对象键是表示类一类,值是一个对象,每一项都是一个方法
1.on方法将某给对象属性,数组添加一个方法
2.emit方法将对象属性的数组中的方法遍历执行
3.off删除对象属性数组中的某一个方法
4.once和on一样,只是添加的方法emit只能执行一次,执行一次后销毁

(function (){

  interface EventFace {
    // 定义类
    on: (TypeName: string, callback: Function) => void; //订阅消息
    emit: (TypeNam: string, ...args: Array<any>) => void; // 发布消息
    off: (TypeName: string, callback: Function) => void; //删除指定函数
    once(TypeName: string, callback: Function): void; // 只执行一次,删除指定函数
    //on(Ms:string,Fun:Function):void 接口定义函数
  }
// 定义对象 { name:[fun1,fun2],name2:[fun3,fun4]}
  interface List {
    [index: string]: Array<Function>;
  }

  class Dispatch implements EventFace {
    //   public list: List = {};
    public list: List;
    constructor() {
      this.list = {};
    }
    on(TypeName: string, callback: Function): void {
      this.list[TypeName];
      const callbackList: Array<Function> = this.list[TypeName] || [];
      callbackList.push(callback);
      this.list[TypeName] = callbackList;
    } //订阅消息
    emit(TypeNam: string, ...args: Array<any>): void {
      if(TypeNam && args)
      {

        this.list[TypeNam]?.forEach(fun=>{
          // 执行全部
          fun.apply(this,args)
        })
      }
      else
      {
        console.log("参数错误")
      }
    } // 发布消息
    off(TypeName: string, callback: Function): void {
      if(TypeName && callback)
      {

        let index:number=this.list[TypeName]?.indexOf(callback)
         console.log(index)
        if(index>-1)
        {
          this.list[TypeName]?.splice(index,1)// 返回删除的元素
        }
        else
        {
          console.log("没找到这个函数")
        }
      }else
      {
        console.log("参数错误")
      }

    } //解除绑定
    once(TypeName: string, callback: Function): void {
      if(TypeName && callback)
      {
        // 和on一样,只是它添加的只能使用一次
        let decor=(...args:Array<any>)=>
        {
          callback.apply(this,args)// 执行然后删除
          this.off(TypeName,decor)// 删除方法
        }
        // 使用on添加到,list中
        this.on(TypeName,decor);


      }else
      {
        console.log("参数错误")
      }
    } // 只执行一次
  }
  let o=new Dispatch()
  function fun1(...args:Array<any>)
  {
    console.log("fun1-1",args)
  }
  o.on("fun1",fun1);// 订阅

  o.emit("fun1",12,3,5) ///


  o.off("fun1",fun1)
  o.emit("fun1",12,3) ///

  function fun2(...arge:Array<any>)
  {
    console.log("fun2",arge)
  }
  o.once("fun2",fun2)
  o.emit("fun2",12,3,2) ///
  o.emit("fun2",12,3,2) ///

})()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值