事件总线封装

此封装是对new Event()的一次练习,但能适用于大多数需要监听事件处理的情况,欢迎大家对于此封装进行 test and issue 

    // 事件总线封装
    function NqEventBus() {
      this.eventBus = {}
      NqEventBus.prototype.on = function(eventName,eventCallback) {
        if(typeof eventName !== 'string') {
          throw new TypeError('event name must be string type')
        }
        if(typeof eventCallback !== 'function') {
          throw new TypeError('event callback must be function type')
        }
        let eventInstance = this.eventBus[eventName]
        if(!eventInstance) {
          eventInstance = new Event(eventName)
          this.eventBus[eventName] = eventInstance
        }
        window.addEventListener(eventName, eventCallback)
      }
      NqEventBus.prototype.emit = function(eventName, ...payload) {
        if(typeof eventName !== 'string') {
          throw new TypeError('event name must be string type')
        }
        const eventInstance = this.eventBus[eventName]
        eventInstance['payload'] = payload
        if(eventInstance) {
          window.dispatchEvent(eventInstance)
        }
      }
      NqEventBus.prototype.off = function(eventName, eventCallback) {
        if(typeof eventName !== 'string') {
          throw new TypeError('event name must be string type')
        }
        if(typeof eventCallback !== 'function') {
          throw new TypeError('event callback must be function type')
        }
        if(eventCallback) {
          window.removeEventListener(eventName, eventCallback)
        }
      }
      NqEventBus.prototype.once = function(eventName, eventCallback) {
        if(typeof eventName !== 'string') {
          throw new TypeError('event name must be string type')
        }
        if(typeof eventCallback !== 'function') {
          throw new TypeError('event callback must be function type')
        }
        const tempCallback = (...payload) => {
          this.off(eventName, tempCallback)
          eventCallback(...payload)
        }
        this.on(eventName, tempCallback)
      }
    }

 使用方法:

let eventBus = new NqEventBus()

1. 注册处理函数

eventBus.on('事件名','事件函数')

2.触发事件处理函数

eventBus.emit('事件名','要传递的参数')

3.取消注册处理函数

eventBus.off('事件名','事件函数')

4. 也可以只执行一次监听

eventBus.once('事件名','事件函数')

 注意:传递的参数在事件对象下的payload属性下

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值