js自定义事件

class Event {

  // 监听函数
  static on(eventName, callback) {
    if (!eventName) {
      return
    }

    if (!this.handles) {
      Object.defineProperty(this, "handles", {
        value: {},    // 默认值是{}
        enumerable: false, // 不可枚举
        configurable: true, // 可以delete删除
        writable: true  // 可以修改
      })
    }

    // 如果对象中没有这个名字,就创建一个数组,之后把名字和方法存在来
    if (!this.handles[eventName]) {
      this.handles[eventName] = []
    }
    // 把对应方法push到数组里
    this.handles[eventName].push(callback)
  }

  // 触发函数
  static emit(eventName) {
    let nameAry = this.handles[eventName]
    // 处理对象里存在这个名字的数组,就把数组的方法执行了
    if (nameAry instanceof Array) {
      for (let i = 0; i < nameAry.length; i++) {
        nameAry[i]()
      }
    }
  }

  // 解绑函数
  static off(eventName) {
    let nameAry = this.handles[eventName]
    if (nameAry instanceof Array) {
      this.handles[eventName] = null
    }
  }
}

Event.on('oufuhua', function () {
  console.log('哈哈哈')
})

Event.on('oufuhua', function () {
  console.log('我叫oufuhua')
})

// Event.off('oufuhua')

 Event.emit('oufuhua')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • erichow阅读 4,046评论 0 0
  • 让我万万没想到的是,原来《JavaScript高级程序设计(第3版)》里面提到的方法已经是过时的了.后来我查看了M...
    再见田园犬阅读 15,300评论 3 12
  • 有人路过曾经咿咿呀呀的戏台,一旁的戏装早已赋闲,有株草从出现裂纹的台子下钻出,那人走近看了看,他认得,这草名字叫细...
    柠一个柚子阅读 2,299评论 0 2
  • // 遍历总结 // 遍历一般有三种 for循环遍历 枚举器(NSEnumerator)遍历 for ... in...
    9bf19a4010ab阅读 2,425评论 1 0
  • 好久没有写简书了。每天似乎也挺忙的,8月了,时间好快呀!而我的工作服还没有眉目,说好的腾出来的房间,就一...
    梅燕霓阅读 1,535评论 0 1

友情链接更多精彩内容