分享一个类,可以使用类的自定义事件

类方法介绍

  • 注册事件(on函数)
  • 触发事件(emit函数)
  • 注销事件(off函数)
  • 检测事件是否存在(has函数)
  • 事件只触发一次久注销事件(once函数)

代码

export class CustomEvent {
  list: { [key: string]: Array<any> }
  constructor() {
    this.list = {}
  }
  // 注册事件
  on(event: string, fn: any) {
    // 判断是否订阅过这个事件,如果没有订阅过就给event创建一个缓存列表
    // 如果有event值,把fn加入到这个列表里面
    if (!this.list[event]) {
      this.list[event] = []
    }
    this.list[event].push(fn)
  }
  // 触发事件
  emit(event: string, payload: any) {
    // 找到这个事件对应的函数列表
    const handers = this.list[event]
    if (handers) {
      handers.forEach(hander => {
        hander(payload)
      })
    }
  }
  // 注销这个事件
  off(event: string, fn: any) {
    const handers = this.list[event]
    // 如果这个事件不存在就直接退出
    if (!handers) { return }
    const index = handers.indexOf(fn)
    if (index !== -1) {
      // 将事件从列表里面删除
      handers.splice(index, 1)
    }
  }
  // 检测这个事件是否存在
  has(event: string, fn: any) {
    const handers = this.list[event]
    if (handers) {
      return handers.indexOf(fn) !== -1
    } else {
      return false
    }
  }
  // 使这个事件只触发一次
  once(event: string, fn: any) {
    // this.on(event, fn)
    const on = (...args: any) => {
      this.off(event, on)
      fn.apply(this, args)
    }
    on.fn = fn
    this.on(event, on)
  }
}
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值